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

feat(TV-57): implement altcha captcha #931

Open
wants to merge 12 commits into
base: next
Choose a base branch
from

Conversation

Fabinatix97
Copy link
Member

@Fabinatix97 Fabinatix97 commented Mar 12, 2025

Pull Request Checklist (Feature Branch to next):

  • Ich habe die neuesten Änderungen aus dem next Branch in meinen Feature-Branch gemergt.
  • Das Code-Review wurde abgeschlossen.
  • Fachliche Tests wurden durchgeführt und sind abgeschlossen.

Summary by CodeRabbit

  • New Features

    • Enhanced the CAPTCHA system with distinct challenge and verification flows for improved security.
    • Introduced an interactive CAPTCHA widget within the appointment scheduling experience for smoother user verification.
    • Updated API functionality to support detailed CAPTCHA information retrieval.
    • Added a new TypeScript interface for structured CAPTCHA data management.
    • Added a new Vue component for CAPTCHA handling and validation.
    • Integrated new environment variables for CAPTCHA configuration.
  • Documentation

    • Revised configuration guidelines to reflect the new CAPTCHA setup and endpoints.

Copy link
Contributor

coderabbitai bot commented Mar 12, 2025

Walkthrough

The changes refactor the Altcha CAPTCHA configuration across backend and frontend modules. Updates include renaming and replacing environment variables and class properties, transitioning from a secret key to a site secret along with new endpoints for challenge and verification. The AltchaCaptcha class and corresponding tests have been updated accordingly, and the CaptchaService now uses the new model. On the frontend, a new dependency is added; an API function, a Vue component, and relevant TypeScript interfaces/types are introduced. Additionally, the Vite configuration and JSON schema are modified to support custom elements and updated property names.

Changes

File(s) Change Summary
zmscitizenapi/README.md
zmscitizenapi/src/Zmscitizenapi/Application.php
Updated Altcha CAPTCHA configuration: removed ALTCHA_CAPTCHA_SECRET_KEY and replaced ALTCHA_CAPTCHA_ENDPOINT/ALTCHA_CAPTCHA_ENDPOINT_PUZZLE with ..._ENDPOINT_VERIFY and ..._ENDPOINT_CHALLENGE; added ALTCHA_CAPTCHA_SITE_SECRET and corresponding static properties.
zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php Renamed properties (e.g., apiUrlchallengeUrl, secretKeyverifyUrl, and removed puzzle); updated constructor and method signatures (e.g., verifyCaptcha now accepts payload); adjusted getCaptchaDetails return structure.
zmscitizenapi/src/Zmscitizenapi/Services/Security/CaptchaService.php Changed captcha model from FriendlyCaptcha to AltchaCaptcha in both import and method return type.
zmscitizenapi/tests/Zmscitizenapi/ApplicationTest.php
zmscitizenapi/tests/Zmscitizenapi/Services/Security/CaptchaServiceTest.php
Updated tests to reflect new environment variables and assertions (e.g., replacing ALTCHA_CAPTCHA_SECRET_KEY with ALTCHA_CAPTCHA_SITE_SECRET and checking for 'captchaVerify' instead of 'captchaEndpoint').
zmscitizenview/package.json Added new dependency: "altcha": "^1.2.0".
zmscitizenview/src/api/ZMSAppointmentAPI.ts Added function fetchCaptchaDetails to retrieve CAPTCHA details using the new endpoint; updates to import statements for types and endpoint constants.
zmscitizenview/src/api/models/CaptchaDetails.ts Introduced a new TypeScript interface CaptchaDetails defining the structure for captcha-related data.
zmscitizenview/src/components/Appointment/Altcha.vue Added a new Vue component using <script setup> with TypeScript that imports the altcha package; handles the <altcha-widget> events, updates an internal reactive variable, and emits changes via update:payload.
zmscitizenview/src/components/Appointment/ServiceFinder.vue Integrated the new Altcha component with two-way binding (v-model) via a reactive variable altchaPayload.
zmscitizenview/src/types/AltchaTypes.ts Added new TypeScript definitions for Altcha widget events, including interfaces for event details and a custom element type (AltchaWidget).
zmscitizenview/vite.config.ts Configured the Vue plugin to recognize custom elements starting with the prefix altcha- using the isCustomElement function.
zmsentities/schema/citizenapi/captcha/altchaCaptcha.json Updated JSON schema by renaming "captchaEndpoint" to "captchaVerify" and "puzzle" to "captchaChallenge"; adjusted descriptions and the required fields accordingly.

Sequence Diagram(s)

sequenceDiagram
  participant UI as User Interface
  participant API as ZMSAppointmentAPI
  participant Server as Captcha Server

  UI->>API: Call fetchCaptchaDetails(baseUrl?)
  API->>Server: HTTP GET (constructed URL using baseUrl + endpoint)
  Server-->>API: Return JSON (CaptchaDetails | ErrorDTO)
  API-->>UI: Return captcha details/error response
Loading
sequenceDiagram
  participant User as End User
  participant AltchaComp as Altcha.vue
  participant Widget as <altcha-widget>

  User->>AltchaComp: Interact with CAPTCHA widget
  AltchaComp->>Widget: Listen for 'statechange' event
  Widget-->>AltchaComp: Emit statechange (e.g., "verified")
  AltchaComp->>AltchaComp: Update internalValue & emit update:payload
  AltchaComp-->>User: Reflect updated payload via v-model binding
Loading

Suggested reviewers

  • ThomasAFink
  • MoDaae

Poem

I'm a bunny with some code to share,
Hopping through change with a keen software flair.
Endpoints and secrets now set anew,
Widget events and API flows in view.
With a twitch of my nose and a hop so light,
I celebrate our changes with rabbit delight! 🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between 4aacd01 and 1cb5c36.

📒 Files selected for processing (2)
  • zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php (2 hunks)
  • zmscitizenview/src/components/Appointment/Altcha.vue (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 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.

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

🧹 Nitpick comments (4)
zmscitizenview/src/api/models/CaptchaDetails.ts (1)

1-41: Enhance JSDoc documentation

The interface itself is well-structured with proper typing. However, the JSDoc comments could be more descriptive by explaining the purpose of each property instead of just repeating the type information.

 /**
- *
  * @export
  * @interface CaptchaDetails
+ * Interface representing the data structure for Altcha CAPTCHA challenges
  */
 export interface CaptchaDetails {
   /**
-  *
+  * The hashing algorithm used for the CAPTCHA challenge
    * @type {string}
    * @memberof CaptchaDetails
    */
   algorithm: string;

   /**
-  *
+  * The CAPTCHA challenge string to be solved
    * @type {string}
    * @memberof CaptchaDetails
    */
   challenge: string;

   /**
-  *
+  * The maximum number value used in the challenge (if applicable)
    * @type {number}
    * @memberof CaptchaDetails
    */
   maxnumber?: number;

   /**
-  *
+  * Salt value used in the challenge generation
    * @type {string}
    * @memberof CaptchaDetails
    */
   salt: string;

   /**
-  *
+  * Signature to verify the authenticity of the challenge
    * @type {string}
    * @memberof CaptchaDetails
    */
   signature: string;
 }
zmscitizenapi/README.md (1)

71-73: New environment variables correctly documented.

The documentation has been properly updated to include the new environment variables for Altcha captcha. The variables are clearly described with their default values.

However, the bare URLs in the description should be formatted according to Markdown best practices.

Consider formatting the URLs using Markdown syntax:

-| ALTCHA_CAPTCHA_SITE_SECRET | Altcha site secret | "" |
-| ALTCHA_CAPTCHA_ENDPOINT_CHALLENGE | Altcha challenge endpoint | https://captcha-k.muenchen.de/api/v1/captcha/challenge |
-| ALTCHA_CAPTCHA_ENDPOINT_VERIFY | Altcha verification endpoint | https://captcha-k.muenchen.de/api/v1/captcha/verify |
+| ALTCHA_CAPTCHA_SITE_SECRET | Altcha site secret | "" |
+| ALTCHA_CAPTCHA_ENDPOINT_CHALLENGE | Altcha challenge endpoint | `https://captcha-k.muenchen.de/api/v1/captcha/challenge` |
+| ALTCHA_CAPTCHA_ENDPOINT_VERIFY | Altcha verification endpoint | `https://captcha-k.muenchen.de/api/v1/captcha/verify` |
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

72-72: Bare URL used
null

(MD034, no-bare-urls)


73-73: Bare URL used
null

(MD034, no-bare-urls)

zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php (2)

59-81: Consider implementing or removing commented code

There's a large block of commented code for a potential requestCaptcha method. Consider either implementing this functionality if it's needed or removing the commented code to keep the codebase clean.

If this is intended for future implementation, consider adding a TODO comment explaining when this will be implemented, or move it to a separate development branch until ready.


86-97: verifyCaptcha method updated for new API contract

The verifyCaptcha method has been updated to use the new property names and API contract, changing from solution to payload parameter and including siteKey and siteSecret in the request.

Consider adding proper error logging when a RequestException occurs to help with troubleshooting:

 } catch (RequestException $e) {
+    error_log('AltchaCaptcha verification failed: ' . $e->getMessage());
     return false;
 }

However, note that according to coding guidelines, error_log() should be replaced with a proper logging mechanism:

 } catch (RequestException $e) {
+    // Using PSR-3 logger that should be injected
+    $this->logger->error('AltchaCaptcha verification failed', [
+        'error' => $e->getMessage(),
+        'code' => $e->getCode()
+    ]);
     return false;
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4da0801 and 4160ef1.

⛔ Files ignored due to path filters (1)
  • zmscitizenview/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (14)
  • zmscitizenapi/README.md (1 hunks)
  • zmscitizenapi/src/Zmscitizenapi/Application.php (2 hunks)
  • zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php (2 hunks)
  • zmscitizenapi/src/Zmscitizenapi/Services/Security/CaptchaService.php (2 hunks)
  • zmscitizenapi/tests/Zmscitizenapi/ApplicationTest.php (3 hunks)
  • zmscitizenapi/tests/Zmscitizenapi/Services/Security/CaptchaServiceTest.php (2 hunks)
  • zmscitizenview/package.json (1 hunks)
  • zmscitizenview/src/api/ZMSAppointmentAPI.ts (2 hunks)
  • zmscitizenview/src/api/models/CaptchaDetails.ts (1 hunks)
  • zmscitizenview/src/components/Appointment/Altcha.vue (1 hunks)
  • zmscitizenview/src/components/Appointment/ServiceFinder.vue (3 hunks)
  • zmscitizenview/src/types/AltchaTypes.ts (1 hunks)
  • zmscitizenview/vite.config.ts (1 hunks)
  • zmsentities/schema/citizenapi/captcha/altchaCaptcha.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.{js,jsx,ts,tsx}`: Flag any usage of console.log() as i...

**/*.{js,jsx,ts,tsx}: Flag any usage of console.log() as it should be replaced with proper logging:

  1. For development: Use proper debug tools or logging libraries
  2. For production: Remove console.log() statements or use structured logging
  3. For errors: Use error tracking services (e.g., Sentry)
  4. For debugging: Consider using debug libraries that can be enabled/disabled

Example replacement:

// Instead of:
console.log('User data:', userData);

// Use:
logger.debug('Processing user data', { userData });
// or for development only:
if (process.env.NODE_ENV === 'development') {
  debug('User data:', userData);
}
  • zmscitizenview/vite.config.ts
  • zmscitizenview/src/api/models/CaptchaDetails.ts
  • zmscitizenview/src/api/ZMSAppointmentAPI.ts
  • zmscitizenview/src/types/AltchaTypes.ts
`**/*.php`: Flag any usage of error_log() as it should be re...

**/*.php: Flag any usage of error_log() as it should be replaced with proper logging mechanisms:

  1. For error handling: Use a proper logging framework with error levels (PSR-3 LoggerInterface)
  2. For debugging: Use a dedicated debug logger or remove debug statements
  3. For CLI output: Use a CLI output handler or symfony/console
  4. For application events: Use structured logging with proper log levels

Example replacement:

// Instead of:
error_log("Import failed - " . $e->getMessage());

// Use:
$logger->error("Import failed", ['error' => $e->getMessage()]);
  • zmscitizenapi/tests/Zmscitizenapi/Services/Security/CaptchaServiceTest.php
  • zmscitizenapi/src/Zmscitizenapi/Services/Security/CaptchaService.php
  • zmscitizenapi/src/Zmscitizenapi/Application.php
  • zmscitizenapi/tests/Zmscitizenapi/ApplicationTest.php
  • zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php
🧠 Learnings (1)
zmscitizenapi/src/Zmscitizenapi/Application.php (1)
Learnt from: ThomasAFink
PR: it-at-m/eappointment#674
File: zmscitizenapi/src/Zmscitizenapi/Application.php:57-77
Timestamp: 2025-01-08T09:53:23.015Z
Learning: CAPTCHA configuration must be validated when enabled to ensure all required environment variables are set and valid, including secret keys, site keys and endpoint URLs for both FriendlyCaptcha and AltchaCaptcha.
🪛 markdownlint-cli2 (0.17.2)
zmscitizenapi/README.md

72-72: Bare URL used
null

(MD034, no-bare-urls)


73-73: Bare URL used
null

(MD034, no-bare-urls)

🔇 Additional comments (27)
zmscitizenview/package.json (1)

17-17: Added new Altcha dependency

The altcha package has been successfully added to the dependencies section which is needed for the CAPTCHA implementation.

zmscitizenview/vite.config.ts (1)

14-19: Vue configuration updated to support Altcha custom elements

Appropriate configuration has been added to recognize custom elements with the 'altcha-' prefix, which is required for the Altcha CAPTCHA component to function properly.

zmscitizenview/src/api/ZMSAppointmentAPI.ts (1)

242-250: Implementation of fetchCaptchaDetails looks good

The new function follows the same pattern as other API functions in this file and properly handles the response.

zmscitizenview/src/components/Appointment/ServiceFinder.vue (3)

91-93: Good integration of the Altcha component.

The Altcha component is properly integrated with appropriate margins and using v-model for two-way data binding.


114-114: LGTM: Component import is correctly placed.

The Altcha component import is properly added to the imports section.


126-127: LGTM: Payload state initialization.

The altchaPayload ref is correctly initialized with an empty string.

zmscitizenview/src/types/AltchaTypes.ts (3)

1-4: Well-structured interface for the Altcha state event detail.

The AltchaStateEventDetail interface is well-typed with an optional payload and appropriate state literals.


6-6: LGTM: Proper extension of CustomEvent.

The AltchaStateEvent interface correctly extends CustomEvent with the appropriate generic parameter.


8-17: Well-defined type for the Altcha widget.

The AltchaWidget type properly extends HTMLElement with the necessary event listener methods, providing strong typing for the component interactions.

zmscitizenview/src/components/Appointment/Altcha.vue (4)

4-5: LGTM: Correct dependency import.

The altcha package is properly imported, which makes the custom element available in the template.


7-21: LGTM: Well-implemented two-way binding.

The component correctly sets up a two-way binding pattern using props, emits, and a watcher for the internal value.


23-32: Robust event handling for state changes.

The onStateChange function correctly processes the event details and updates the internal value based on the verification state.


34-44: LGTM: Proper lifecycle management.

The component correctly adds event listeners on mount and removes them on unmount to prevent memory leaks.

zmscitizenapi/tests/Zmscitizenapi/Services/Security/CaptchaServiceTest.php (2)

31-31: Test assertion updated correctly for the new property name.

The assertion has been properly updated to check for the 'captchaVerify' key instead of 'captchaEndpoint', aligning with the changes made to the AltchaCaptcha model.


49-49: Assertion updated correctly to validate the new property.

This assertion has been correctly modified to verify that the expected endpoint matches the 'captchaVerify' property value, which is consistent with the changes to the captcha implementation.

zmscitizenapi/src/Zmscitizenapi/Services/Security/CaptchaService.php (2)

7-7: Import statement updated correctly for the new captcha implementation.

The import statement has been properly updated to use the AltchaCaptcha class instead of FriendlyCaptcha, reflecting the transition to the new captcha model.


16-18: Method signature and implementation properly updated.

Both the return type and implementation of the getCaptchaDetails method have been updated to use AltchaCaptcha, ensuring consistency with the new captcha implementation.

zmsentities/schema/citizenapi/captcha/altchaCaptcha.json (3)

9-12: Property renamed and description updated properly.

The property has been correctly renamed from 'captchaEndpoint' to 'captchaVerify' and its description has been updated to "Endpoint for captcha verification".


13-16: Property renamed and description updated properly.

The property has been correctly renamed from 'puzzle' to 'captchaChallenge' and its description has been updated to "Challenge endpoint URL for AltchaCaptcha".


22-22: Required fields list updated correctly.

The required fields list has been properly updated to reflect the renamed properties, ensuring the schema validation will work correctly with the new property names.

zmscitizenapi/tests/Zmscitizenapi/ApplicationTest.php (3)

102-104: Environment variables updated to match new Altcha CAPTCHA configuration

The test now sets up the new environment variables for Altcha CAPTCHA, replacing the old ALTCHA_CAPTCHA_SECRET_KEY with ALTCHA_CAPTCHA_SITE_SECRET and adding specific endpoint variables for challenge and verification. This aligns with the updated implementation in the Application class.


114-116: Test assertions updated to verify new Altcha properties

The assertions correctly verify that the new Application properties are properly initialized from the corresponding environment variables, ensuring the config is correctly loaded.


232-234: Test teardown updated to clean environment variables

The tearDown method now properly cleans up the new environment variables, which is important for test isolation.

zmscitizenapi/src/Zmscitizenapi/Application.php (1)

45-47: New Altcha CAPTCHA configuration properties added

The static properties for Altcha CAPTCHA have been updated to align with the new implementation requirements, replacing the old secret key with site secret and adding specific endpoint properties for challenge and verification.

zmscitizenapi/src/Zmscitizenapi/Models/Captcha/AltchaCaptcha.php (3)

19-23: Properties updated to match new Altcha CAPTCHA implementation

The properties have been updated from apiUrl, secretKey, and puzzle to siteSecret, challengeUrl, and verifyUrl to align with the new Altcha CAPTCHA implementation.


31-33: Constructor updated to use new Application properties

The constructor now correctly initializes the class properties from the updated Application static properties.


53-54: Updated getCaptchaDetails with new property names

The getCaptchaDetails method now returns the challenge and verify URLs with updated property names that match the schema changes.

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