-
Notifications
You must be signed in to change notification settings - Fork 1
Feature/secure mode #8
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
base: master
Are you sure you want to change the base?
Conversation
WalkthroughThe changes enhance the security and configuration management of the Tawkto module. In the admin controller, a new constant Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Controller as Admin Tawkto Controller
participant Config as Config Service
participant Crypto as Encryption Module
User->>Controller: Submit form with security options
Controller->>Controller: Check for NO_CHANGE in API key
Controller->>Config: Retrieve current security settings
Controller->>Crypto: Encrypt API key if required
Controller->>Controller: Merge new security options
Controller->>User: Return success or error message
sequenceDiagram
participant Browser
participant Catalog as Catalog Tawkto Controller
participant Session as Session Manager
participant Decrypt as Decryption Module
Browser->>Catalog: Request visitor data
Catalog->>Session: Check/initiate session
Catalog->>Catalog: Process visitor data based on parameters
alt Secure mode enabled
Catalog->>Decrypt: Retrieve and decrypt js_api_key
end
Catalog->>Browser: Return visitor and security information
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (8)
system/config/tawkto.php (1)
14-18: Store security secrets in environment variables
Including the JavaScript API key in configuration files can risk exposure if the file becomes accessible. Consider using environment variables or a secure vault for maintaining sensitive keys.admin/view/stylesheet/index.css (2)
32-37: Avoid absolute positioning on alerts
Absolute positioning can complicate layout management and responsiveness. Consider relative or static positioning for the.alertclass to prevent potential overlapping elements.
38-42: Unify ID-based and class-based styling
Styling an ID (#optionsSuccessMessage) and a class (.alert) in tandem can cause confusion or conflict. Consider consolidating styling into a single class for consistency.catalog/controller/module/tawkto.php (1)
177-185: Consider user-friendly error handling
Currently, an exception in secure mode returnsnulland drops visitor data. Logging and graceful fallbacks can help maintain user experience if decryption fails.admin/view/template/module/tawkto.twig (3)
198-225: Ensure consistency in displaying or hiding the stored API key.
The new “Security Settings” section correctly introduces options for secure mode and the JavaScript API key, but displayingNO_CHANGEas the password value might confuse users. Consider substituting a placeholder for the password field to clarify that the key is already stored if unchanged.
436-443: Consider explicit show/hide instead of toggle for clarity.
While using.toggle()is acceptable, using explicit.show()and.hide()can be clearer, especially for sequential display logic. Also verify thatr.messageis always defined to avoid empty or undefined error text.
466-493: Missing handling for security fields in front-end store object.
Although the server now supports secure mode fields, those fields are not updated or displayed in the localstoreHierarchyobject here. If you plan to reflect the new security settings immediately upon submitting, consider tracking them as well.admin/controller/module/tawkto.php (1)
466-523: Encryption approach is acceptable; consider additional authenticity checks.
AES-256-CBC with a random IV is suitable for confidentiality, but consider using GCM or adding an HMAC for data authenticity. Also confirm thatcredentials.jsonis secured (e.g., not committed to source control).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
admin/controller/module/tawkto.php(6 hunks)admin/view/stylesheet/index.css(2 hunks)admin/view/template/module/tawkto.twig(3 hunks)catalog/controller/module/tawkto.php(4 hunks)catalog/view/template/module/tawkto.twig(1 hunks)system/config/tawkto.php(1 hunks)
🔇 Additional comments (15)
catalog/view/template/module/tawkto.twig (1)
12-14: Re-introducing visitor setting may override privacy preferences
Previously, visitor data was only set ifenable_visitor_recognitionwas true. Now, the code assignsTawk_API.visitorwhenevervisitoris non-null, potentially bypassing privacy controls. Verify that this behavioral change is intentional.admin/view/stylesheet/index.css (1)
55-59: Check positioning consistency at smaller viewports
The.alertclass is absolutely positioned in the base rules but becomes relatively positioned under the media query. Ensure this contrast is deliberate and won’t cause unexpected shifts on smaller screens.catalog/controller/module/tawkto.php (6)
34-36: Ensure session handling is consolidated
Starting a session here is correct, but verify you don’t start sessions elsewhere or after headers have been sent, which can cause warnings or inconsistent session states.
44-44: Guard against missing config array keys
Older installations might not havemodule_tawkto_security. Verify that$security_optsis defined before use to avoid undefined index errors.Also applies to: 53-55
57-61: Enforce robust default parameters
enable_visitor_recognition,secure_mode_enabled, andjs_api_keyrequire valid defaults. Ensure the rest of the code expects NULL-safe or fallback values if they’re missing.
160-168: Transition to parameter arrays is a solid improvement
Providing an associative array togetVisitor()allows for more flexible, extensible calls.
204-220: Scrutinize session-based secret storage
Maintaining decrypted keys in_SESSIONcould pose challenges if load-balancing or session replication aren’t fully aligned. Evaluate the potential security and synchronization risks.
222-257:❓ Verification inconclusive
Validate symmetric encryption setup
Ensure that your IV and algorithm usage precisely match between encryption and decryption processes. Mismatches can lead to silent failures or corrupted data.
🏁 Script executed:
#!/bin/bash # Searching for "encryptData" usage to confirm that encryption and IV creation match this decryption logic rg -A 5 $'encryptData('Length of output: 99
Action Required: Verify Consistent Encryption/Decryption Configuration
The decryption method uses a fixed IV length (first 16 bytes) and the AES-256-CBC algorithm. Please ensure that the encryption side (likely via an
encryptDatafunction) generates its IV and processes data with the same parameters. Note that our initial search for the encryption counterpart produced a regex error due to unescaped parentheses. To help verify that the encryption logic matches the decryption process, please re-run the following command with proper escaping:#!/bin/bash # Searching for "encryptData(" usage using proper escaping rg -A 5 'encryptData\('If you identify that the encryption routine does not align with the decryption logic (in terms of IV creation or algorithm parameters), please adjust the code accordingly. Otherwise, if everything is consistent, no changes are needed.
admin/view/template/module/tawkto.twig (2)
250-252: Error message addition looks good.
Adding a dedicated error message container is a helpful UI enhancement.
444-465: Potential overwriting of existing store settings.
Reinitializingdisplay_opts,privacy_opts, andcart_optswith fixed defaults removes any unhandled or future properties. Confirm this is intentional or consider merging with existing subkeys instead of overwriting.admin/controller/module/tawkto.php (5)
16-16: Constant declaration is clear.
IntroducingNO_CHANGEis a convenient approach to detecting unchanged API keys.
153-166: Security options integration is consistent.
Addingsecurity_optsto each store ingetStoreHierarchy()provides a complete view of store settings.
257-258: New security config initialization is fine.
Retrieving$securityOptsfromtawkto_securitymatches the existing pattern of reading module-specific configs.
326-343: Merging settings is appropriate.
Ensuring$currentSettingsis populated and merged with the new changes preserves existing configuration keys.
452-464:getSecurityOpts()logic is sound but watch out for inconsistent behavior withNO_CHANGE.
Hiding the actual stored API key is a good practice to maintain confidentiality, but ensure the front-end counterpart doesn’t remove the key whenNO_CHANGEis set.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
admin/controller/module/tawkto.php (1)
478-492: Secure implementation of credentials management.The method:
- Attempts to load existing credentials
- Creates secure random encryption keys if none exist
- Persists credentials for future use
One potential improvement would be to set restrictive file permissions when creating the credentials file.
- file_put_contents($filePath, json_encode($credentials)); + file_put_contents($filePath, json_encode($credentials)); + chmod($filePath, 0600); // Restrict access to owner only
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)
📒 Files selected for processing (3)
admin/controller/module/tawkto.php(6 hunks)catalog/controller/module/tawkto.php(4 hunks)system/config/tawkto.php(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- system/config/tawkto.php
🧰 Additional context used
🧠 Learnings (1)
admin/controller/module/tawkto.php (2)
Learnt from: eug-L
PR: tawk/tawk-opencart4#8
File: admin/controller/module/tawkto.php:300-322
Timestamp: 2025-03-07T07:17:03.722Z
Learning: In the tawk.to OpenCart module, when handling the 'js_api_key' with a value of 'NO_CHANGE', the key is intentionally unset from the local $securityOpts array to prevent it from overwriting the existing encrypted key during the array_merge() operation with the current settings.
Learnt from: eug-L
PR: tawk/tawk-opencart4#8
File: admin/controller/module/tawkto.php:296-299
Timestamp: 2025-03-07T07:19:59.870Z
Learning: In the tawkto module, security options ($securityOpts) are initialized with default values from the config file. These default values include 'secure_mode_enabled' set to false and 'js_api_key' set to null. When processing form submissions, only checked checkboxes are included, so unchecked options automatically retain their default values.
🔇 Additional comments (17)
catalog/controller/module/tawkto.php (8)
34-36: Appropriate session initialization.The session is properly initialized only when necessary and with the right preconditions checked (session not already active and headers not sent).
44-45: Good addition of security options.Adding security configuration options enhances the module's capabilities.
54-59: Properly structured security options handling.The code follows the same pattern as other options (privacy, cart), maintaining consistency.
61-66: Well structured parameters for visitor data.The refactored method accepts an array of parameters, providing a cleaner way to pass multiple configurations.
167-174: Good early return pattern for visitor recognition.The code efficiently returns null when visitor recognition is disabled, avoiding unnecessary processing.
183-189: Secure implementation of visitor hash.The code properly checks for secure mode being enabled and the presence of an encrypted API key before calculating the hash.
214-251: Efficient visitor hash implementation with caching.The hash generation is well-implemented with:
- Session caching to prevent recalculation on each request
- Validation of email and config version to ensure cache correctness
- Proper error handling for encryption failures
258-288: Robust decryption implementation with thorough error handling.The decryption method properly:
- Validates the credentials file existence
- Checks for encryption key presence
- Handles base64 decoding errors
- Extracts IV and encrypted data appropriately
- Handles decryption failures
admin/controller/module/tawkto.php (9)
16-16: Good use of constant for indicating no change.Using a constant instead of a magic string improves readability and maintainability.
153-153: Consistent addition of security options to store hierarchy.The security options are added in the same pattern as other options, maintaining architectural consistency.
Also applies to: 166-166
257-257: Good initialization of security options.Initializing from config follows the pattern used for other option types.
296-298: Proper handling of secure mode option.The implementation follows the same pattern as other boolean options.
300-323: Thorough implementation of API key handling with validation.The code:
- Properly handles the NO_CHANGE case by unsetting the key to prevent overwriting existing values
- Validates API key length
- Includes appropriate error handling for encryption failures
- Returns meaningful error messages
The implementation aligns with the learnings previously captured about intentionally unsetting the key to prevent overwriting during array_merge operations.
338-343: Comprehensive initialization of configuration settings.The code properly checks and initializes all configuration arrays, including the new security options and config version.
345-349: Proper merging of settings and version increment.The code:
- Merges all settings consistently
- Increments the config version to ensure client-side cache invalidation for security changes
This is essential for security changes to take effect immediately.
458-470: Well-implemented security options retrieval with API key protection.The method correctly:
- Gets default options from config if not set in settings
- Masks the API key value with NO_CHANGE to prevent showing the actual encrypted value
503-529: Strong encryption implementation with proper error handling.The method:
- Uses AES-256-CBC encryption with a secure random IV
- Includes comprehensive error handling for all potential failure points
- Properly combines and encodes the IV with the encrypted data
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
admin/controller/module/tawkto.php (1)
241-357: 🛠️ Refactor suggestionAdd permissions check to the setoptions method.
Unlike the
setwidgetandremovewidgetmethods, thesetoptionsmethod does not check if the user has permission to modify the extension, which could be a security vulnerability.public function setoptions() { header('Content-Type: application/json'); + if (!$this->checkPermission()) { + echo json_encode(array('success' => false, 'message' => 'Permission denied')); + die(); + } $store_id = isset($_POST['store']) ? intval($_POST['store']) : null; if (is_null($store_id)) { echo json_encode(array('success' => false)); die(); } // rest of the method remains unchanged
🧹 Nitpick comments (1)
catalog/controller/module/tawkto.php (1)
19-19: Consider moving the constant declaration to the top of the file.The
CREDENTIALS_FILEconstant should be placed at the top of the file for better visibility and easier maintenance.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)
📒 Files selected for processing (3)
admin/controller/module/tawkto.php(6 hunks)admin/view/template/module/tawkto.twig(3 hunks)catalog/controller/module/tawkto.php(5 hunks)
🧰 Additional context used
🧠 Learnings (1)
admin/controller/module/tawkto.php (1)
Learnt from: eug-L
PR: tawk/tawk-opencart4#8
File: admin/controller/module/tawkto.php:300-322
Timestamp: 2025-03-20T12:09:56.977Z
Learning: In the tawk.to OpenCart module, when handling the 'js_api_key' with a value of 'NO_CHANGE', the key is intentionally unset from the local $securityOpts array to prevent it from overwriting the existing encrypted key during the array_merge() operation with the current settings.
🔇 Additional comments (22)
catalog/controller/module/tawkto.php (8)
42-57: Well-structured configuration retrieval!The code properly retrieves both default and store-specific security settings, ensuring backward compatibility with existing configurations.
59-64: Good implementation of parameter passing.The refactored approach of passing parameters to the
getVisitormethod improves modularity and testability.
169-172: Great approach for handling secure mode configuration.The code properly extracts the necessary parameters for secure mode operation from the passed parameters.
180-186: Secure mode hash generation correctly implemented.The implementation properly checks for secure mode being enabled and a valid API key before attempting to generate a hash.
213-215: Efficient session management implementation.The code only starts a session if it's not already active and headers haven't been sent, which addresses previous feedback about avoiding unnecessary session overhead.
221-229: Good caching strategy for visitor hash.The implementation efficiently reuses the cached hash when the email and config version haven't changed, reducing unnecessary processing.
243-252: Well-implemented hash generation and session storage.The code securely generates a hash using HMAC-SHA256 and properly stores it in the session with relevant metadata.
259-287: Comprehensive error handling in the decryption process.The
decryptDatamethod includes thorough error checking for:
- Missing credentials file
- Missing encryption key
- Failed base64 decoding
- Failed decryption
This ensures secure and robust handling of encrypted data.
admin/view/template/module/tawkto.twig (4)
198-224: Well-structured Security Settings section.The new section provides clear labels and helpful descriptions for the security features, making it easy for users to understand the purpose of each setting.
218-218: Update help text to be more descriptive.The current description is brief. Consider expanding it to explain that the JavaScript API key is used to authenticate visitor recognition when secure mode is enabled, helping administrators understand its significance.
250-252: Good addition of error message display.Adding an error message element improves the user experience by providing feedback when an operation fails.
436-439: Improved error handling in form submission.The code now properly handles API failures by displaying an error message and aborting the process.
admin/controller/module/tawkto.php (10)
16-17: Consider moving constants to the top of the file.The constants are buried in the middle of the file. Consider moving them to the top for better visibility.
154-154: Good addition of security options to the store hierarchy.The code now includes security options in the store hierarchy, making them available in the admin UI.
258-258: Consistent initialization of security options.The code initializes security options from the configuration, consistent with how other option types are handled.
297-299: Proper handling of boolean checkbox value.The code correctly sets the
secure_mode_enabledflag to true when the checkbox is checked.
301-326: Comprehensive validation and error handling for API key.The code:
- Handles the
NO_CHANGEcase correctly- Validates empty values
- Checks the key length
- Handles encryption errors
- Provides clear error feedback
This ensures robust and secure processing of sensitive API keys.
344-346: Good initialization of config version.The code initializes the configuration version if it doesn't exist, ensuring version tracking works properly from the start.
352-352: Excellent versioning strategy.Incrementing the configuration version when options change helps track changes and ensures cached data is properly invalidated.
461-473: Well-implemented security options retrieval.The
getSecurityOptsmethod follows the same pattern as other option retrievers and includes the important security enhancement of returningNO_CHANGEfor the API key instead of the actual encrypted value.
481-493: Secure credentials management.The
getCredentialsmethod properly:
- Checks for existing credentials
- Creates secure random credentials if needed
- Persists credentials to the file system
This ensures secure and consistent encryption key management.
504-530: Strong encryption implementation.The encryption method:
- Uses a secure algorithm (AES-256-CBC)
- Generates a proper random IV
- Includes comprehensive error handling
- Returns the encrypted data in a secure format
This implementation follows security best practices for encrypting sensitive data.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
catalog/controller/module/tawkto.php (1)
262-288: Consider moving credentials file check to constructor.The credentials file check is performed on each decryption attempt. Consider validating this once during initialization to fail early and improve performance.
public function __construct($registry) { parent::__construct($registry); $this->config->addPath(DIR_EXTENSION . 'tawkto/system/config/'); $this->config->load('tawkto'); + + // Validate credentials file exists early + if (!file_exists(self::CREDENTIALS_FILE)) { + error_log('Tawkto credentials file not found: ' . self::CREDENTIALS_FILE); + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)
📒 Files selected for processing (1)
catalog/controller/module/tawkto.php(5 hunks)
🔇 Additional comments (11)
catalog/controller/module/tawkto.php (11)
19-19: Good addition of a constant for the credentials file path.Adding the CREDENTIALS_FILE constant improves maintainability by centralizing the file path definition. This follows proper OOP principles and makes future updates easier.
42-43: Added security options and config version retrieval.Good addition of security options and configuration version retrieval, which aligns with the security enhancements in the PR.
52-57: Security options and config version settings retrieval is consistent.The implementation follows the same pattern as the existing privacy and cart options, which maintains code consistency.
59-64: Visitor data construction now includes security parameters.The getVisitor method has been properly updated to include security-related parameters. The array format makes the code more maintainable and extensible.
163-172: Updated getVisitor method with proper parameter handling.The getVisitor method now accepts parameters and extracts security settings properly. The early return if visitor recognition is disabled is a good performance optimization.
180-186: Secure visitor hash implementation.Good conditional implementation of secure mode. The hash is only generated when secure mode is enabled and an API key is provided.
219-221: Only start session when necessary.The session is only started if it's not already active and headers haven't been sent, which is good practice. However, this logic should be wrapped in the secure mode check to avoid unnecessary session overhead.
- if (session_status() === PHP_SESSION_NONE && !headers_sent()) { - session_start(); - } + // Only start session if secure mode is enabled and API key is set + if ($secure_mode_enabled && !is_null($js_api_key)) { + if (session_status() === PHP_SESSION_NONE && !headers_sent()) { + session_start(); + } + }
223-234: Efficient session-based hash caching.Good implementation of session-based caching for the visitor hash. The validation checks ensure that the cached hash is only used when the email and config version match.
236-242: Proper error handling for decryption.The code appropriately handles decryption errors by catching exceptions, logging the error, and returning an empty string.
244-253: Secure hash generation and caching.The hash is properly generated using HMAC SHA-256 and stored in the session with appropriate metadata.
255-288: Robust decryption implementation with proper error handling.The decryptData method includes thorough error handling:
- Checks if the credentials file exists
- Validates that the encryption key is present
- Ensures the data can be decoded
- Handles decryption failures
The implementation uses secure cryptographic methods (AES-256-CBC) with proper IV handling.
Summary by CodeRabbit
New Features
Style
Chores