Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Components] fiserv - new components #14687

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jcortes
Copy link
Collaborator

@jcortes jcortes commented Nov 19, 2024

WHY

Resolves #14562

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a checkout creation process with customizable parameters.
    • Added functionality to retrieve checkout details using a unique identifier.
  • Enhancements

    • Implemented utility functions for JSON parsing and API request handling.
    • Centralized authentication and URL construction for improved request management.
  • Dependencies

    • Updated package.json to include new dependencies for enhanced functionality.

@jcortes jcortes added the action New Action Request label Nov 19, 2024
@jcortes jcortes self-assigned this Nov 19, 2024
Copy link

vercel bot commented Nov 19, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Nov 19, 2024 10:59pm

Copy link

vercel bot commented Nov 19, 2024

@jcortes is attempting to deploy a commit to the Pipedreamers Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

Walkthrough

This pull request introduces several new modules for handling checkout processes in the Fiserv component. It includes the creation of a checkout module, a module for retrieving checkout details, and a constants module for environment settings and API paths. Additionally, utility functions for JSON parsing and enhancements to the main application file for authentication and request handling are included. The package.json is updated to reflect new dependencies required for these functionalities.

Changes

File Path Change Summary
components/fiserv/actions/create-checkout/create-checkout.mjs New module for creating a checkout process with an action and methods for handling checkout requests.
components/fiserv/actions/retrieve-checkout-details/retrieve-checkout-details.mjs New module for retrieving checkout details with an action and methods for handling requests to fetch checkout information.
components/fiserv/common/constants.mjs New module defining constants for environment settings and API paths.
components/fiserv/common/utils.mjs New utility function for parsing JSON strings and objects.
components/fiserv/fiserv.app.mjs Significant updates including new methods for authentication, URL construction, header management, and request handling.
components/fiserv/package.json Updated to include new dependencies for the Fiserv component.

Assessment against linked issues

Objective Addressed Explanation
Initiate a payment request by passing all required parameters (#14562)
Retrieve details about a specific checkout using the identifier (#14562)

Possibly related PRs

Suggested reviewers

  • michelle0927

🐰 In the world of checkout, we hop and play,
New paths and actions brighten the way.
With constants and utils, our code is neat,
A seamless transaction, oh what a treat!
Let's celebrate changes, both big and small,
For a joyful payment process, we welcome all! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Outside diff range and nitpick comments (6)
components/fiserv/common/utils.mjs (3)

1-2: Add JSDoc documentation and consider renaming for clarity.

Since this is a utility function that will be used across Fiserv components, it should have comprehensive documentation. Also, consider a more specific name like parseJsonRecursive to better indicate its behavior.

+/**
+ * Recursively parses JSON strings within an object or string input
+ * @param {Object|string} input - The input value to parse
+ * @returns {Object|string} The parsed result
+ */
-const parseJson = (input) => {
+const parseJsonRecursive = (input) => {

18-22: Add type validation for payment-related fields.

Since this utility is used for processing payment data, consider adding validation for specific fields to ensure data integrity.

+const PAYMENT_FIELD_TYPES = {
+  transactionAmount: 'number',
+  currency: 'string',
+  // Add other payment-specific fields
+};
+
 const parseJson = (input) => {
-  const parse = (value) => {
+  const parse = (value, field = null) => {
+    // Validate payment-specific fields
+    if (field && PAYMENT_FIELD_TYPES[field]) {
+      const expectedType = PAYMENT_FIELD_TYPES[field];
+      if (typeof value !== expectedType) {
+        throw new TypeError(`Invalid type for ${field}: expected ${expectedType}`);
+      }
+    }

24-26: Add explicit type definitions.

Consider adding TypeScript or JSDoc type definitions to improve type safety and developer experience.

+/**
+ * @typedef {Object} Utils
+ * @property {function(any): any} parseJson - Recursively parses JSON strings
+ */
+
+/** @type {Utils} */
 export default {
   parseJson,
 };
components/fiserv/actions/create-checkout/create-checkout.mjs (1)

26-26: Typo in 'transactionOrigin' description: 'recieved' should be 'received'.

Please correct the spelling in the description.

Apply this diff:

- description: "This parameter is used to flag the transaction source correctly. The possible values are `ECOM` (if the order was recieved from online shop), `MAIL` & `PHONE`.",
+ description: "This parameter is used to flag the transaction source correctly. The possible values are `ECOM` (if the order was received from online shop), `MAIL` & `PHONE`.",
components/fiserv/fiserv.app.mjs (2)

64-71: Maintain consistent access to authentication properties

In the getHeaders(headers) method, the API key is accessed directly from this.$auth.api_key on line 69. For consistency with other methods that use this.getAuth(), consider accessing the API key via this.getAuth().apiKey.

Apply this diff for consistency:

        getHeaders(headers) {
          return {
            ...headers,
            "Content-Type": "application/json",
            "Accept": "application/json",
-           "API-Key": this.$auth.api_key,
+           "API-Key": this.getAuth().apiKey,
          };
        },

75-85: Make the debug flag configurable or remove it

In the _makeRequest method, the debug flag is set to true on line 77. Leaving debugging enabled in a production environment can expose sensitive information and affect performance. Consider making this flag configurable or removing it entirely.

Apply this diff to parameterize the debug flag:

        _makeRequest({
          $ = this, path, headers, data, apiPath, debug = false, ...args
        } = {}) {
          return axios($, {
            ...args,
-           debug: true,
+           debug,
            url: this.getUrl(path, apiPath),
            data,
            headers: {
              ...this.getHeaders(headers),
              ...this.getSignatureHeaders(data),
            },
          });
        },

This allows you to control the debug setting when calling _makeRequest or default it to false.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9cbf1c2 and 0dc4ec7.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • components/fiserv/actions/create-checkout/create-checkout.mjs (1 hunks)
  • components/fiserv/actions/retrieve-checkout-details/retrieve-checkout-details.mjs (1 hunks)
  • components/fiserv/common/constants.mjs (1 hunks)
  • components/fiserv/common/utils.mjs (1 hunks)
  • components/fiserv/fiserv.app.mjs (1 hunks)
  • components/fiserv/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/fiserv/common/constants.mjs
🔇 Additional comments (8)
components/fiserv/package.json (1)

18-18: ⚠️ Potential issue

Fix uuid version to latest stable release

The specified version ^11.0.3 is invalid as the latest major version of uuid is 9.x. This will cause installation failures.

Apply this diff to use the latest stable version:

  "dependencies": {
    "@pipedream/platform": "3.0.3",
-   "uuid": "^11.0.3"
+   "uuid": "^9.0.1"
  }

Let's verify the latest version and any security advisories:

components/fiserv/common/utils.mjs (1)

1-26: Verify compatibility with Fiserv API requirements.

Let's ensure this utility can handle all data types required by the Fiserv API endpoints.

✅ Verification successful

Let me gather more specific information about how this utility is being used in the Fiserv checkout process.


Based on the create-checkout.mjs implementation, I can now generate a final response since I have enough context about how the parseJson utility is used.

The parseJson utility implementation is compatible with Fiserv API requirements

The utility correctly handles all data types required by the Fiserv checkout process:

  • Recursively parses nested JSON strings
  • Preserves non-string primitive values
  • Handles null values appropriately
  • Used correctly for parsing transactionAmount, order, checkoutSettings and paymentMethodDetails objects

The implementation safely handles potential JSON parsing errors by returning the original value if parsing fails, which is appropriate for this use case since some inputs may already be objects rather than JSON strings.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Fiserv API usage patterns to verify data type handling
echo "Checking Fiserv API usage patterns..."

# Look for checkout creation calls
ast-grep --pattern 'parseJson($checkout)' || \
rg -A 5 'parseJson.*checkout'

# Look for specific Fiserv fields that need parsing
rg -l 'transactionAmount|checkoutSettings|paymentMethodDetails' components/fiserv/

# Check for any JSON schema definitions
fd -e json -e schema.json -x cat {} \; | jq . || true

Length of output: 135262


Script:

#!/bin/bash
# Look for usage of parseJson in create-checkout.mjs
echo "Checking create-checkout.mjs for parseJson usage..."
cat components/fiserv/actions/create-checkout/create-checkout.mjs

# Look for any test files that might validate the parsing
echo -e "\nChecking for test files..."
fd -e test.js -e test.mjs -e spec.js -e spec.mjs -x cat {} \; components/fiserv/

# Look for any schema or type definitions
echo -e "\nChecking for type definitions..."
fd -e d.ts -e types.ts -x cat {} \; components/fiserv/

Length of output: 5494

components/fiserv/actions/retrieve-checkout-details/retrieve-checkout-details.mjs (3)

9-17: LGTM! Props are well-defined

The props are properly typed and documented. The checkoutId prop is appropriately marked as required with a clear description.


1-8: Verify the imported app module exists

The import path seems correct, but let's verify the existence and exports of the Fiserv app module.

✅ Verification successful

Import path and app module are correctly implemented

The Fiserv app module exists at the correct location and exports all necessary methods including _makeRequest. The module is properly structured with authentication, URL handling, and request methods that will be needed by the retrieve-checkout-details action.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and structure of the Fiserv app module
# Expected: Should find the app module and confirm it exports required methods

# Check if the app file exists and contains necessary exports
rg -l "export default.*{" "components/fiserv/fiserv.app.mjs"

# Verify if the app module contains _makeRequest method
ast-grep --pattern 'export default {
  $$$
  _makeRequest($_) {
    $$$
  }
  $$$
}' "components/fiserv/fiserv.app.mjs"

Length of output: 278


Script:

#!/bin/bash
# Let's try a simpler approach to verify the app module

# Check if the app file exists
ls -l components/fiserv/fiserv.app.mjs

# Check the content of the app file
cat components/fiserv/fiserv.app.mjs

# Alternative search for exports using ripgrep with fixed string
rg -F "export default" components/fiserv/fiserv.app.mjs

Length of output: 2532


23-23: Verify API endpoint matches documentation

Let's ensure the API endpoint matches the one specified in the Fiserv documentation.

✅ Verification successful

Let me gather more specific information about the API endpoint usage.


API endpoint is correctly implemented and documented

The endpoint /checkouts/${checkoutId} is correctly implemented as it matches the official Fiserv documentation referenced in the component's description: https://docs.fiserv.dev/public/reference/get-checkouts-id. The documentation link is embedded directly in the component, providing clear traceability to the API specification.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify API endpoint consistency across the codebase
# Expected: Should find consistent usage of the checkouts endpoint

# Check for any constants defining the API path
rg -l "checkouts/" "components/fiserv/"

# Check for other usages of the checkouts endpoint
ast-grep --pattern 'path: `/checkouts/$_`'

Length of output: 403


Script:

#!/bin/bash
# Search for the complete file content to understand the context
cat components/fiserv/actions/retrieve-checkout-details/retrieve-checkout-details.mjs

# Look for any API documentation or configuration files
fd -e md -e json -e yaml -e yml . components/fiserv/ --exec grep -l "checkout"

# Search for any test files that might validate the endpoint
fd -e test.js -e test.mjs -e spec.js -e spec.mjs . components/fiserv/ --exec grep -l "checkout"

Length of output: 1315

components/fiserv/fiserv.app.mjs (3)

10-23: LGTM

The getAuth() method correctly retrieves and returns the necessary authentication details from this.$auth. The structure and variable assignments are clear and well-organized.


24-33: LGTM

The getUrl() method accurately constructs the full URL based on the environment and provided path. It correctly handles the sandbox environment and appends the appropriate API paths.


86-90: LGTM

The post(args = {}) method correctly abstracts the POST request by utilizing the _makeRequest method with the HTTP method set to "POST".

},
"dependencies": {
"@pipedream/platform": "3.0.3",
"crypto": "^1.0.1",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unnecessary crypto dependency

The crypto module is a built-in Node.js module and should not be listed as an external dependency. It's available by default in Node.js environments.

Apply this diff to remove the unnecessary dependency:

  "dependencies": {
    "@pipedream/platform": "3.0.3",
-   "crypto": "^1.0.1",
    "uuid": "^11.0.3"
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"crypto": "^1.0.1",

Comment on lines +3 to +9
if (typeof(value) === "string") {
try {
return parseJson(JSON.parse(value));
} catch (e) {
return value;
}
} else if (typeof(value) === "object" && value !== null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add safety measures to prevent recursion-related issues.

The current implementation has potential security and stability issues:

  1. No maximum recursion depth limit could lead to stack overflow with deeply nested JSON.
  2. Silent error handling could mask important parsing issues.

Consider implementing these safety measures:

+const MAX_DEPTH = 100; // Prevent excessive recursion
-const parse = (value) => {
+const parse = (value, depth = 0) => {
+  if (depth > MAX_DEPTH) {
+    throw new Error('Maximum parsing depth exceeded');
+  }
   if (typeof(value) === "string") {
     try {
-      return parseJson(JSON.parse(value));
+      return parse(JSON.parse(value), depth + 1);
     } catch (e) {
+      // Log parsing errors in development
+      if (process.env.NODE_ENV === 'development') {
+        console.warn('JSON parsing failed:', e.message);
+      }
       return value;
     }
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (typeof(value) === "string") {
try {
return parseJson(JSON.parse(value));
} catch (e) {
return value;
}
} else if (typeof(value) === "object" && value !== null) {
const MAX_DEPTH = 100; // Prevent excessive recursion
if (typeof(value) === "string") {
try {
return parse(JSON.parse(value), depth + 1);
} catch (e) {
// Log parsing errors in development
if (process.env.NODE_ENV === 'development') {
console.warn('JSON parsing failed:', e.message);
}
return value;
}
} else if (typeof(value) === "object" && value !== null) {

Comment on lines +9 to +17
} else if (typeof(value) === "object" && value !== null) {
return Object.entries(value)
.reduce((acc, [
key,
val,
]) => Object.assign(acc, {
[key]: parse(val),
}), {});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve object handling robustness and efficiency.

The current implementation has several areas for improvement:

  1. No explicit handling of arrays
  2. No protection against circular references
  3. Object reconstruction could be more efficient

Consider this enhanced implementation:

-} else if (typeof(value) === "object" && value !== null) {
+} else if (value && typeof(value) === "object") {
+  // Handle circular references
+  if (seen.has(value)) {
+    throw new Error('Circular reference detected');
+  }
+  seen.add(value);
+
+  // Handle arrays
+  if (Array.isArray(value)) {
+    return value.map(item => parse(item, depth + 1));
+  }
+
+  // Handle objects more efficiently
+  const result = {};
+  for (const [key, val] of Object.entries(value)) {
+    result[key] = parse(val, depth + 1);
+  }
+  seen.delete(value);
+  return result;
-  return Object.entries(value)
-    .reduce((acc, [
-      key,
-      val,
-    ]) => Object.assign(acc, {
-      [key]: parse(val),
-    }), {});

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +28 to +41
async run({ $ }) {
const {
getCheckoutDetails,
checkoutId,
} = this;

const response = await getCheckoutDetails({
$,
checkoutId,
});

$.export("$summary", `Successfully retrieved details for checkout ID ${this.checkoutId}`);
return response;
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling and fix inconsistent property access

The run function needs several improvements:

  1. Fix inconsistent use of this.checkoutId vs checkoutId
  2. Add error handling for API calls
  3. Add response validation
 async run({ $ }) {
   const {
     getCheckoutDetails,
     checkoutId,
   } = this;

+  try {
     const response = await getCheckoutDetails({
       $,
       checkoutId,
     });
 
-    $.export("$summary", `Successfully retrieved details for checkout ID ${this.checkoutId}`);
+    if (!response || typeof response !== 'object') {
+      throw new Error('Invalid response received from API');
+    }
+
+    $.export("$summary", `Successfully retrieved details for checkout ID ${checkoutId}`);
     return response;
+  } catch (error) {
+    throw new Error(`Failed to retrieve checkout details: ${error.message}`);
+  }
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async run({ $ }) {
const {
getCheckoutDetails,
checkoutId,
} = this;
const response = await getCheckoutDetails({
$,
checkoutId,
});
$.export("$summary", `Successfully retrieved details for checkout ID ${this.checkoutId}`);
return response;
},
async run({ $ }) {
const {
getCheckoutDetails,
checkoutId,
} = this;
try {
const response = await getCheckoutDetails({
$,
checkoutId,
});
if (!response || typeof response !== 'object') {
throw new Error('Invalid response received from API');
}
$.export("$summary", `Successfully retrieved details for checkout ID ${checkoutId}`);
return response;
} catch (error) {
throw new Error(`Failed to retrieve checkout details: ${error.message}`);
}
},

Comment on lines +18 to +27
methods: {
getCheckoutDetails({
checkoutId, ...args
} = {}) {
return this.app._makeRequest({
path: `/checkouts/${checkoutId}`,
...args,
});
},
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input validation and error handling

The current implementation could be more robust. Consider these improvements:

  1. Validate checkoutId before making the request
  2. Add error handling for edge cases
  3. Be more explicit about which parameters can be overridden via args
 methods: {
   getCheckoutDetails({
     checkoutId, ...args
   } = {}) {
+    if (!checkoutId || typeof checkoutId !== 'string') {
+      throw new Error('Invalid checkoutId provided');
+    }
+    const allowedParams = ['$'];
+    const invalidParams = Object.keys(args).filter(key => !allowedParams.includes(key));
+    if (invalidParams.length > 0) {
+      throw new Error(`Invalid parameters provided: ${invalidParams.join(', ')}`);
+    }
     return this.app._makeRequest({
       path: `/checkouts/${checkoutId}`,
-      ...args,
+      $: args.$,
     });
   },
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
methods: {
getCheckoutDetails({
checkoutId, ...args
} = {}) {
return this.app._makeRequest({
path: `/checkouts/${checkoutId}`,
...args,
});
},
},
methods: {
getCheckoutDetails({
checkoutId, ...args
} = {}) {
if (!checkoutId || typeof checkoutId !== 'string') {
throw new Error('Invalid checkoutId provided');
}
const allowedParams = ['$'];
const invalidParams = Object.keys(args).filter(key => !allowedParams.includes(key));
if (invalidParams.length > 0) {
throw new Error(`Invalid parameters provided: ${invalidParams.join(', ')}`);
}
return this.app._makeRequest({
path: `/checkouts/${checkoutId}`,
$: args.$,
});
},
},

Comment on lines +96 to +125
async run({ $ }) {
const {
createCheckout,
storeId,
merchantTransactionId,
transactionOrigin,
transactionType,
transactionAmount,
order,
checkoutSettings,
paymentMethodDetails,
} = this;

const response = await createCheckout({
$,
data: {
storeId,
merchantTransactionId,
transactionOrigin,
transactionType,
transactionAmount: utils.parseJson(transactionAmount),
order: utils.parseJson(order),
checkoutSettings: utils.parseJson(checkoutSettings),
paymentMethodDetails: utils.parseJson(paymentMethodDetails),
},
});

$.export("$summary", `Successfully created checkout. Redirect URL: ${response.redirectionUrl}`);
return response;
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Ensure proper error handling for JSON parsing and API requests.

When parsing JSON inputs (transactionAmount, order, checkoutSettings, paymentMethodDetails), consider handling potential parsing errors to prevent the application from crashing due to invalid JSON input. Additionally, ensure that errors from the createCheckout API request are properly caught and handled to inform the user appropriately.

Consider wrapping the parsing calls with try-catch blocks or using a safe parsing method that returns meaningful errors if parsing fails.

Comment on lines +43 to +48
transactionAmount: {
type: "object",
label: "Transaction Amount",
description: "Object contains `total` transaction amount, `currency`, tax and discount details. Example: `{\"total\":123,\"currency\":\"EUR\",\"components\":{\"subtotal\":115,\"vat\":3,\"shipping\":2.5}}`",
optional: true,
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Inconsistent handling of 'transactionAmount' prop type and unnecessary JSON parsing.

The transactionAmount prop is declared as type object, but in the run method (line 116), it is parsed using utils.parseJson(transactionAmount). Since transactionAmount is already an object, parsing it as JSON is unnecessary and may cause errors if the object is not serializable. Consider either changing the prop type to string if you expect JSON input as a string, or removing the JSON parsing if an object is expected.

If you expect transactionAmount to be an object, apply this diff:

- transactionAmount: utils.parseJson(transactionAmount),
+ transactionAmount: transactionAmount,

Alternatively, if you expect input as a JSON string, change the prop type to string:

- transactionAmount: {
-   type: "object",
+ transactionAmount: {
+   type: "string",

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +37 to +63
getSignatureHeaders(data) {
const {
apiKey,
secretKey,
environment,
} = this.getAuth();

if (environment === constants.ENVIRONMENT.SANDBOX) {
return;
}

const clientRequestId = uuid();
const timestamp = Date.now().toString();
const requestBody = JSON.stringify(data) || "";
const rawSignature = apiKey + clientRequestId + timestamp + requestBody;

const computedHmac =
crypto.createHmac("sha256", secretKey)
.update(rawSignature)
.digest("base64");

return {
"Client-Request-Id": clientRequestId,
"Message-Signature": computedHmac,
"Timestamp": timestamp,
};
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure getSignatureHeaders returns an object to prevent errors

In the getSignatureHeaders(data) method, when the environment is set to SANDBOX, the function returns undefined due to return; on line 45. Later, in the _makeRequest method (line 82), spreading undefined into the headers object will cause a runtime error. To prevent this, ensure that getSignatureHeaders always returns an object, even if it's empty.

Apply this diff to fix the issue:

          if (environment === constants.ENVIRONMENT.SANDBOX) {
-            return;
+            return {};
          }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
getSignatureHeaders(data) {
const {
apiKey,
secretKey,
environment,
} = this.getAuth();
if (environment === constants.ENVIRONMENT.SANDBOX) {
return;
}
const clientRequestId = uuid();
const timestamp = Date.now().toString();
const requestBody = JSON.stringify(data) || "";
const rawSignature = apiKey + clientRequestId + timestamp + requestBody;
const computedHmac =
crypto.createHmac("sha256", secretKey)
.update(rawSignature)
.digest("base64");
return {
"Client-Request-Id": clientRequestId,
"Message-Signature": computedHmac,
"Timestamp": timestamp,
};
},
getSignatureHeaders(data) {
const {
apiKey,
secretKey,
environment,
} = this.getAuth();
if (environment === constants.ENVIRONMENT.SANDBOX) {
return {};
}
const clientRequestId = uuid();
const timestamp = Date.now().toString();
const requestBody = JSON.stringify(data) || "";
const rawSignature = apiKey + clientRequestId + timestamp + requestBody;
const computedHmac =
crypto.createHmac("sha256", secretKey)
.update(rawSignature)
.digest("base64");
return {
"Client-Request-Id": clientRequestId,
"Message-Signature": computedHmac,
"Timestamp": timestamp,
};
},

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
components/fiserv/fiserv.app.mjs (2)

24-33: Add path validation to prevent URL injection.

While the URL construction is correct, it's recommended to validate the path parameter to prevent potential URL injection attacks.

Consider adding path validation:

 getUrl(path, apiPath = constants.API_PATH.DEFAULT) {
+  if (!path || typeof path !== 'string' || path.includes('..')) {
+    throw new Error('Invalid path parameter');
+  }
   const {
     url,
     environment,
   } = this.getAuth();
   const baseUrl = environment === constants.ENVIRONMENT.SANDBOX
     ? `${url}${constants.SANDBOX_PATH}${apiPath}`
     : `${url}${apiPath}`;
   return `${baseUrl}${path}`;
 },

72-85: Consider enhancing request handling robustness.

While the request implementation is functional, consider these improvements:

  1. Make debug mode configurable rather than always enabled
  2. Add retry mechanism for failed requests
  3. Add request timeout configuration

Consider this enhancement:

 _makeRequest({
-  $ = this, path, headers, data, apiPath, ...args
+  $ = this,
+  path,
+  headers,
+  data,
+  apiPath,
+  debug = false,
+  timeout = 10000,
+  retries = 3,
+  ...args
 } = {}) {
-  return axios($, {
+  const config = {
     ...args,
-    debug: true,
+    debug,
     url: this.getUrl(path, apiPath),
     data,
+    timeout,
     headers: {
       ...this.getHeaders(headers),
       ...this.getSignatureHeaders(data),
     },
-  });
+  };
+
+  return axios($, config).catch((error) => {
+    if (retries > 0 && error.response?.status >= 500) {
+      return this._makeRequest({
+        $,
+        path,
+        headers,
+        data,
+        apiPath,
+        debug,
+        timeout,
+        retries: retries - 1,
+        ...args,
+      });
+    }
+    throw error;
+  });
 },
components/fiserv/actions/create-checkout/create-checkout.mjs (1)

123-123: Enhance the summary message with more transaction details.

The current summary only includes the redirect URL. Consider adding more relevant details like the transaction ID or amount to make it more informative.

Apply this diff:

- $.export("$summary", `Successfully created checkout. Redirect URL: ${response.redirectionUrl}`);
+ $.export("$summary", `Successfully created checkout for ${transactionType} transaction. Amount: ${transactionAmount?.total} ${transactionAmount?.currency}. Redirect URL: ${response.redirectionUrl}`);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0dc4ec7 and 0b992cc.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • components/fiserv/actions/create-checkout/create-checkout.mjs (1 hunks)
  • components/fiserv/actions/retrieve-checkout-details/retrieve-checkout-details.mjs (1 hunks)
  • components/fiserv/common/constants.mjs (1 hunks)
  • components/fiserv/common/utils.mjs (1 hunks)
  • components/fiserv/fiserv.app.mjs (1 hunks)
  • components/fiserv/package.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • components/fiserv/actions/retrieve-checkout-details/retrieve-checkout-details.mjs
  • components/fiserv/common/constants.mjs
  • components/fiserv/common/utils.mjs
  • components/fiserv/package.json
🔇 Additional comments (7)
components/fiserv/fiserv.app.mjs (4)

1-4: LGTM! Appropriate imports for secure API integration.

The imports are well-chosen for the required functionality:

  • uuid for generating unique request IDs
  • crypto for secure HMAC signature generation
  • axios from the platform for HTTP requests

44-46: Return empty object in sandbox mode to prevent runtime errors.

When the environment is set to SANDBOX, the function returns undefined. This will cause a runtime error when spread into headers object.


48-62: LGTM! Secure implementation of message signing.

The HMAC signature generation follows Fiserv's documentation correctly:

  • Uses UUID v4 for unique request IDs
  • Includes all required components in the signature
  • Properly handles empty request bodies

1-93: Verify secure coding practices for payment processing.

As this is a payment processing integration, let's verify that secure coding practices are followed throughout the codebase.

components/fiserv/actions/create-checkout/create-checkout.mjs (3)

1-8: LGTM! Well-structured component definition.

The component is properly defined with clear documentation and version numbering appropriate for a new component.


88-95: LGTM! Clean method implementation.

The createCheckout method is well-implemented with proper parameter handling.


96-125: Verify required fields against the Fiserv API documentation.

Let's ensure all required fields from the API documentation are properly handled in the implementation.

Comment on lines +10 to +23
getAuth() {
const {
url,
api_key: apiKey,
secret_key: secretKey,
environment = constants.ENVIRONMENT.SANDBOX,
} = this.$auth;
return {
url,
apiKey,
secretKey,
environment,
};
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation for required authentication properties.

While the method correctly extracts auth properties, it should validate that required properties (url, api_key, secret_key) are present to fail fast and provide clear error messages.

Consider adding validation:

 getAuth() {
   const {
     url,
     api_key: apiKey,
     secret_key: secretKey,
     environment = constants.ENVIRONMENT.SANDBOX,
   } = this.$auth;
+  if (!url || !apiKey || !secretKey) {
+    throw new Error('Missing required authentication properties: url, api_key, and secret_key must be provided');
+  }
   return {
     url,
     apiKey,
     secretKey,
     environment,
   };
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
getAuth() {
const {
url,
api_key: apiKey,
secret_key: secretKey,
environment = constants.ENVIRONMENT.SANDBOX,
} = this.$auth;
return {
url,
apiKey,
secretKey,
environment,
};
},
getAuth() {
const {
url,
api_key: apiKey,
secret_key: secretKey,
environment = constants.ENVIRONMENT.SANDBOX,
} = this.$auth;
if (!url || !apiKey || !secretKey) {
throw new Error('Missing required authentication properties: url, api_key, and secret_key must be provided');
}
return {
url,
apiKey,
secretKey,
environment,
};
},

Comment on lines +49 to +54
order: {
type: "string",
label: "Order",
description: "Object contains order related details. [See the documentation](https://docs.fiserv.dev/public/reference/postcheckouts).",
optional: true,
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Inconsistent type definition for order prop.

The order prop is defined as type string but the documentation indicates it should be an object. This creates confusion and requires unnecessary JSON parsing. Consider changing the type to object to maintain consistency with the API expectations.

Apply this diff:

 order: {
-  type: "string",
+  type: "object",
   label: "Order",
   description: "Object contains order related details. [See the documentation](https://docs.fiserv.dev/public/reference/postcheckouts).",
   optional: true,
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
order: {
type: "string",
label: "Order",
description: "Object contains order related details. [See the documentation](https://docs.fiserv.dev/public/reference/postcheckouts).",
optional: true,
},
order: {
type: "object",
label: "Order",
description: "Object contains order related details. [See the documentation](https://docs.fiserv.dev/public/reference/postcheckouts).",
optional: true,
},

Comment on lines +109 to +121
const response = await createCheckout({
$,
data: {
storeId,
merchantTransactionId,
transactionOrigin,
transactionType,
transactionAmount: utils.parseJson(transactionAmount),
order: utils.parseJson(order),
checkoutSettings: utils.parseJson(checkoutSettings),
paymentMethodDetails: utils.parseJson(paymentMethodDetails),
},
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add response validation to ensure required fields are present.

The Fiserv API response should be validated to ensure it contains the expected fields before using them.

Add validation before using the response:

 const response = await createCheckout({
   $,
   data: {
     storeId,
     merchantTransactionId,
     transactionOrigin,
     transactionType,
     transactionAmount: utils.parseJson(transactionAmount),
     order: utils.parseJson(order),
     checkoutSettings: utils.parseJson(checkoutSettings),
     paymentMethodDetails: utils.parseJson(paymentMethodDetails),
   },
 });
+
+if (!response?.redirectionUrl) {
+  throw new Error('Invalid response: missing redirectionUrl');
+}

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
action New Action Request
Development

Successfully merging this pull request may close these issues.

[Components] fiserv
1 participant