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

Added Captcha to data attribute forms #22049

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

sam-lord
Copy link
Contributor

ref BAE-370

Enables Captcha (when labs flag and config entry set) in data-attribute forms within Portal.

@coderabbitai

ref BAE-370

Used to power the data-attributes hCaptcha implementation
Copy link

coderabbitai bot commented Jan 23, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/portal/src/data-attributes.js

Oops! Something went wrong! :(

ESLint: 8.44.0

ESLint couldn't find the plugin "eslint-plugin-i18next".

(The package "eslint-plugin-i18next" was not found when loaded as a Node module from the directory "/apps/portal".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-i18next@latest --save-dev

The plugin "eslint-plugin-i18next" was referenced from the config file in "apps/portal/package.json".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

This pull request introduces CAPTCHA (hCaptcha) integration across multiple components of the application. The changes span frontend files in the portal and Ghost core, adding functionality to load and handle CAPTCHA verification during form submissions. The implementation includes script loading, form handling modifications, and corresponding test cases to ensure the new CAPTCHA feature works as expected across different parts of the application.

Changes

File Change Summary
apps/portal/src/data-attributes.js - Added imports for CAPTCHA helper functions
- Updated formSubmitHandler to accept captchaId
- Modified form submission to handle CAPTCHA token
apps/portal/src/tests/data-attributes.test.js - Added mock for hCaptcha execution
- Created new test case for CAPTCHA-enabled form submission
ghost/core/core/frontend/helpers/ghost_head.js - Added getHCaptchaScript() function
- Conditionally include hCaptcha script in page head
ghost/core/test/unit/frontend/helpers/ghost_head.test.js - Added new test suite for CAPTCHA script generation
- Created tests for CAPTCHA script inclusion based on settings

Sequence Diagram

sequenceDiagram
    participant User
    participant Form
    participant hCaptcha
    participant Server

    User->>Form: Initiate form submission
    Form->>hCaptcha: Execute CAPTCHA verification
    hCaptcha-->>Form: Return CAPTCHA token
    Form->>Server: Submit form with CAPTCHA token
    Server->>Server: Validate CAPTCHA token
    Server-->>Form: Submit response
Loading

Possibly related PRs

Suggested reviewers

  • aileen
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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: 0

🧹 Nitpick comments (4)
apps/portal/src/data-attributes.js (1)

195-204: Add error handling for CAPTCHA initialization.

While the CAPTCHA integration looks good, consider adding error handling for CAPTCHA initialization failures. This will help provide better feedback to users when CAPTCHA fails to load.

 let captchaId;
 if (hasCaptchaEnabled({site})) {
     const captchaSitekey = getCaptchaSitekey({site});
     const captchaEl = document.createElement('div');
     form.appendChild(captchaEl);
+    try {
         captchaId = window.hcaptcha.render(captchaEl, {
             size: 'invisible',
             sitekey: captchaSitekey
         });
+    } catch (err) {
+        console.error('Failed to initialize CAPTCHA:', err);
+        // Optionally, show user-friendly error message
+        const errorEl = form.querySelector('[data-members-error]');
+        if (errorEl) {
+            errorEl.innerText = 'Failed to initialize security check. Please try again later.';
+        }
+    }
 }

Also applies to: 208-208

ghost/core/core/frontend/helpers/ghost_head.js (1)

168-170: Consider script loading order for CAPTCHA.

The CAPTCHA script is loaded with both defer and async attributes. While this optimizes page load, it may cause race conditions if the form initialization code runs before the CAPTCHA script loads. Consider:

  1. Using only defer to maintain script execution order
  2. Adding a script load error handler
 function getHCaptchaScript() {
-    return `<script defer async src="https://js.hcaptcha.com/1/api.js"></script>`;
+    return `<script defer src="https://js.hcaptcha.com/1/api.js" onerror="console.error('Failed to load CAPTCHA script')"></script>`;
 }

Also applies to: 360-362

apps/portal/src/tests/data-attributes.test.js (1)

183-206: Add more test cases for CAPTCHA handling.

Consider adding the following test cases to improve coverage:

  1. Test CAPTCHA execution failure
  2. Test missing CAPTCHA response
  3. Test invalid CAPTCHA response format

Example test case:

test('handles CAPTCHA execution failure', async () => {
    window.hcaptcha.execute.mockImplementationOnce(() => {
        throw new Error('CAPTCHA execution failed');
    });
    
    const {event, form, errorEl, siteUrl, submitHandler} = getMockData();
    
    await formSubmitHandler({event, form, errorEl, siteUrl, submitHandler, captchaId: '123123'});
    
    expect(form.classList.contains('error')).toBe(true);
    expect(errorEl.innerText).toContain('security check');
});
ghost/core/test/unit/frontend/helpers/ghost_head.test.js (1)

1385-1421: Add test cases for CAPTCHA configuration errors.

The test suite covers basic enable/disable scenarios. Consider adding test cases for:

  1. Missing CAPTCHA configuration
  2. Invalid CAPTCHA configuration
  3. Partial CAPTCHA configuration

Example test case:

it('handles missing CAPTCHA configuration', async function () {
    sinon.stub(labs, 'isSet').withArgs('captcha').returns(true);
    configUtils.set({captcha: {}}); // Missing enabled flag

    const rendered = await testGhostHead(testUtils.createHbsResponse({
        locals: {
            relativeUrl: '/',
            context: ['home', 'index'],
            safeVersion: '4.3'
        }
    }));

    rendered.should.not.match(/hcaptcha/);
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0ccdbe and a98a7eb.

⛔ Files ignored due to path filters (1)
  • ghost/core/test/unit/frontend/helpers/__snapshots__/ghost_head.test.js.snap is excluded by !**/*.snap
📒 Files selected for processing (4)
  • apps/portal/src/data-attributes.js (3 hunks)
  • apps/portal/src/tests/data-attributes.test.js (2 hunks)
  • ghost/core/core/frontend/helpers/ghost_head.js (2 hunks)
  • ghost/core/test/unit/frontend/helpers/ghost_head.test.js (1 hunks)
🔇 Additional comments (3)
apps/portal/src/data-attributes.js (2)

2-2: LGTM!

The new imports are correctly added for the CAPTCHA functionality.


6-9: LGTM!

The function has been properly updated to:

  1. Accept the CAPTCHA ID parameter
  2. Execute CAPTCHA verification when ID is provided
  3. Include the CAPTCHA response token in the request body

Also applies to: 69-72

apps/portal/src/tests/data-attributes.test.js (1)

139-147: LGTM!

The hCaptcha mock is properly implemented to simulate CAPTCHA execution in tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant