Skip to content

#AMM-1247- feat: VAPT Captcha implementation#81

Merged
5Amogh merged 3 commits intodevelopfrom
develop-amogh
Jun 11, 2025
Merged

#AMM-1247- feat: VAPT Captcha implementation#81
5Amogh merged 3 commits intodevelopfrom
develop-amogh

Conversation

@5Amogh
Copy link
Member

@5Amogh 5Amogh commented Jun 4, 2025

📋 Description

JIRA ID: AMM-1247

This feature is part of VAPT and includes captcha implementation, includes validators for login form

✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

Summary by CodeRabbit

  • New Features
    • Added CAPTCHA verification to the login process, requiring users to complete a CAPTCHA challenge before logging in.
    • Introduced a new CAPTCHA component with accessibility support and dynamic script loading.
  • Enhancements
    • Login form inputs now enforce required fields at the HTML level.
    • Disabled login button styling improves user feedback when login is unavailable.
  • Bug Fixes
    • CAPTCHA state is reset after failed login attempts or errors to ensure a fresh challenge.
  • Chores
    • Updated environment configuration to support CAPTCHA integration across all environments.
    • Refined lint-staged configuration to limit ESLint auto-fixing to TypeScript files only.

@coderabbitai
Copy link

coderabbitai bot commented Jun 4, 2025

Walkthrough

A CAPTCHA mechanism has been integrated into the application's login process. This includes a new Angular CAPTCHA component and service, updates to the login form and authentication logic to require and validate a CAPTCHA token, and corresponding environment variable and configuration updates for site key, challenge URL, and enable flag support.

Changes

File(s) Change Summary
scripts/ci-prebuild.js Added SITE_KEY, CAPTCHA_CHALLENGE_URL, and ENABLE_CAPTCHA to default environment variables.
src/environments/environment.* (ci.ts.template, development.ts, local.ts, prod.ts) Added siteKey, captchaChallengeURL, and enableCaptcha properties to the exported environment object.
src/app/app-modules/core/components/captcha/captcha.component.* (html, ts) Introduced new CaptchaComponent with template and logic for rendering and handling CAPTCHA widget, emitting token and reset support.
src/app/app-modules/core/services/captcha.service.ts Added new CaptchaService for dynamically loading CAPTCHA script with promise-based loading and error handling.
src/app/app-modules/core/core.module.ts Declared and exported CaptchaComponent; provided CaptchaService in module providers.
src/app/login/authentication.service.ts Modified login method to accept and send an optional captchaToken parameter in the request body.
src/app/login/login.component.* (ts, html, css) Integrated CAPTCHA into login form: added CAPTCHA component, token handling, reset logic, conditional button enablement, and styles.
package.json Restricted lint-staged ESLint auto-fixing to TypeScript files only (src/**/*.ts).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LoginComponent
    participant CaptchaComponent
    participant CaptchaService
    participant AuthenticationService
    participant Backend

    User->>LoginComponent: Enter username/password
    LoginComponent->>CaptchaComponent: Render CAPTCHA
    CaptchaComponent->>CaptchaService: Load CAPTCHA script
    CaptchaService-->>CaptchaComponent: Script loaded
    User->>CaptchaComponent: Solve CAPTCHA
    CaptchaComponent->>LoginComponent: Emit tokenResolved(token)
    User->>LoginComponent: Click Login
    LoginComponent->>AuthenticationService: login(username, password, ..., captchaToken)
    AuthenticationService->>Backend: POST login request with captchaToken
    Backend-->>AuthenticationService: Respond (success/failure)
    AuthenticationService-->>LoginComponent: Return result
    LoginComponent->>CaptchaComponent: (On error) Reset CAPTCHA
Loading

Poem

In the warren, a lock on the gate,
Now a puzzle for bots to abate!
With a token in paw,
Rabbits log in—no flaw—
As the CAPTCHA keeps spam at bay’s plate.
🐇🔒✨

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.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-05T10_50_56_495Z-debug-0.log


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74f6835 and 11d0c21.

📒 Files selected for processing (9)
  • package.json (1 hunks)
  • scripts/ci-prebuild.js (1 hunks)
  • src/app/login/authentication.service.ts (1 hunks)
  • src/app/login/login.component.html (3 hunks)
  • src/app/login/login.component.ts (7 hunks)
  • src/environments/environment.ci.ts.template (2 hunks)
  • src/environments/environment.development.ts (2 hunks)
  • src/environments/environment.local.ts (2 hunks)
  • src/environments/environment.prod.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • package.json
🚧 Files skipped from review as they are similar to previous changes (8)
  • scripts/ci-prebuild.js
  • src/environments/environment.local.ts
  • src/environments/environment.ci.ts.template
  • src/environments/environment.prod.ts
  • src/app/login/login.component.html
  • src/app/login/authentication.service.ts
  • src/environments/environment.development.ts
  • src/app/login/login.component.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

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

🧹 Nitpick comments (7)
src/environments/environment.local.ts (1)

170-171: Consider providing test values for local development.

Empty CAPTCHA configuration in the local environment might make it difficult to test CAPTCHA functionality during development. Consider using test/sandbox keys for local development.

-const siteKey = '';
-const captchaChallengeURL = '';
+const siteKey = '1x00000000000000000000AA'; // Cloudflare test key
+const captchaChallengeURL = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
src/app/login/login.component.css (1)

73-78: Consider alternatives to !important declarations.

While the disabled button styling is functionally correct, the use of !important declarations suggests potential specificity issues. Consider using more specific selectors or CSS modules to avoid overriding styles with !important.

.disabledLoginButton {
    background-color: #ccc;
    color: #666;
    cursor: not-allowed;
    box-shadow: none;
}

If the !important declarations are necessary to override framework styles, consider adding a comment explaining why they're required.

src/environments/environment.ci.ts.template (1)

156-156: Add trailing comma for consistency.

Consider adding a trailing comma after captchaChallengeURL to maintain consistency with the codebase style and make future additions easier.

  siteKey: siteKey,
  captchaChallengeURL: captchaChallengeURL,
};
src/app/app-modules/core/components/captcha/captcha.component.ts (2)

14-14: Improve type safety for turnstile API

Using any type reduces type safety and IDE support. Consider creating a proper interface for the turnstile API.

-declare const turnstile: any;
+interface TurnstileAPI {
+  render(element: HTMLElement, options: {
+    sitekey: string;
+    theme: string;
+    callback: (token: string) => void;
+  }): string;
+  reset(widgetId: string): void;
+  remove?(widgetId: string): void;
+}
+
+declare const turnstile: TurnstileAPI;

49-53: Add safety checks to reset method

The reset method should include additional validation to prevent runtime errors.

  public reset() {
-   if (this.widgetId && typeof turnstile !== 'undefined') {
+   if (this.widgetId && typeof turnstile !== 'undefined' && turnstile.reset) {
      turnstile.reset(this.widgetId);
+   } else if (!this.widgetId) {
+     console.warn('CAPTCHA widget not initialized, cannot reset');
    }
  }
src/app/login/login.component.ts (2)

35-35: Improve type safety for ViewChild declaration.

The ViewChild is typed as any which reduces type safety. Consider creating a proper interface or importing the specific captcha component type.

-  @ViewChild('captchaCmp') captchaCmp: any;
+  @ViewChild('captchaCmp') captchaCmp!: CaptchaComponent;

Ensure you import the CaptchaComponent type at the top of the file.


331-336: Enhance error handling in resetCaptcha method.

The method has good type checking for the reset function but could be more robust in handling edge cases.

  resetCaptcha() {
-    if (this.captchaCmp && typeof this.captchaCmp.reset === 'function') {
+    if (this.captchaCmp?.reset && typeof this.captchaCmp.reset === 'function') {
      this.captchaCmp.reset();
      this.captchaToken = '';
+    } else {
+      // Fallback: just clear the token if component is not available
+      this.captchaToken = '';
    }
  }

This ensures the token is always cleared even if the captcha component is unavailable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bf9fb20 and 74f6835.

📒 Files selected for processing (13)
  • scripts/ci-prebuild.js (1 hunks)
  • src/app/app-modules/core/components/captcha/captcha.component.html (1 hunks)
  • src/app/app-modules/core/components/captcha/captcha.component.ts (1 hunks)
  • src/app/app-modules/core/core.module.ts (4 hunks)
  • src/app/app-modules/core/services/captcha.service.ts (1 hunks)
  • src/app/login/authentication.service.ts (1 hunks)
  • src/app/login/login.component.css (1 hunks)
  • src/app/login/login.component.html (3 hunks)
  • src/app/login/login.component.ts (8 hunks)
  • src/environments/environment.ci.ts.template (2 hunks)
  • src/environments/environment.development.ts (2 hunks)
  • src/environments/environment.local.ts (2 hunks)
  • src/environments/environment.prod.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/app/login/authentication.service.ts (3)
src/environments/environment.development.ts (1)
  • environment (44-164)
src/environments/environment.local.ts (1)
  • environment (52-172)
src/environments/environment.prod.ts (1)
  • environment (46-166)
🔇 Additional comments (15)
src/environments/environment.local.ts (1)

49-50: LGTM! Configuration follows established patterns.

The CAPTCHA configuration constants are properly declared and follow the existing naming conventions.

src/app/app-modules/core/components/captcha/captcha.component.html (1)

1-1: LGTM! Clean and appropriate CAPTCHA container implementation.

The template properly provides a container for the Cloudflare Turnstile widget with appropriate ID and template reference for component access.

src/environments/environment.development.ts (1)

42-43: Configuration follows established patterns.

The CAPTCHA constants are properly declared following the existing environment configuration structure.

src/environments/environment.prod.ts (2)

43-44: Verify CAPTCHA configuration for production deployment.

The siteKey and captchaChallengeURL are initialized as empty strings, which will prevent CAPTCHA functionality from working in production. Ensure these values are properly configured during the deployment process.

Consider implementing a build-time validation to ensure these critical security values are not empty in production builds.


164-165: CAPTCHA environment configuration added correctly.

The new CAPTCHA properties are properly integrated into the environment object and follow the established pattern.

src/app/login/login.component.css (1)

59-70: Excellent accessibility implementation.

The .sr-only class follows standard web accessibility patterns, providing content for screen readers while visually hiding it. This enhances the user experience for assistive technologies.

src/environments/environment.ci.ts.template (1)

33-34: CAPTCHA template configuration implemented correctly.

The template placeholders <%= SITE_KEY %> and <%= CAPTCHA_CHALLENGE_URL %> follow the established pattern and are properly integrated into the environment object.

Also applies to: 155-156

src/app/app-modules/core/core.module.ts (1)

89-90: LGTM: Proper Angular module registration

The CAPTCHA component and service are correctly registered in the CoreModule following Angular conventions. The component is properly declared and exported, while the service is provided as a singleton through the forRoot() method.

Also applies to: 153-153, 186-186, 204-204

src/app/login/login.component.html (3)

16-16: LGTM: Enhanced form validation

Adding the required attribute to username and password fields provides immediate client-side validation feedback.

Also applies to: 34-34


58-65: Excellent accessibility implementation

The CAPTCHA integration includes proper ARIA attributes with role="group", aria-labelledby, and a screen-reader accessible label. The centered styling provides good visual presentation.


73-76: LGTM: Proper conditional button state

The login button correctly requires both valid form input and a completed CAPTCHA token. The disabled state and CSS class provide clear visual feedback to users.

src/app/login/login.component.ts (4)

22-22: LGTM: Proper import for ViewChild decorator.

The ViewChild import is correctly added to support the captcha component reference.


149-154: LGTM: Consistent captcha token parameter.

The second login call correctly includes the captchaToken parameter, maintaining consistency with the initial login attempt.


169-169: LGTM: Proper captcha reset on error scenarios.

The captcha is appropriately reset in all error handling paths, preventing reuse of expired tokens and ensuring fresh captcha challenges for subsequent login attempts.

Also applies to: 176-176, 184-184, 198-198, 205-205


327-329: LGTM: Clean captcha resolution handler.

The method properly captures the resolved captcha token for use in login requests.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Jun 5, 2025

Quality Gate Failed Quality Gate failed

Failed conditions
5.5% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@5Amogh 5Amogh requested a review from snehar-nd June 10, 2025 14:28
@5Amogh 5Amogh merged commit 75e87c8 into develop Jun 11, 2025
3 of 4 checks passed
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.

2 participants