Skip to content

refactor: fetches turnstile sitekey from api#1318

Merged
stalniy merged 1 commit intomainfrom
refactor/turnstile-sitekey
May 16, 2025
Merged

refactor: fetches turnstile sitekey from api#1318
stalniy merged 1 commit intomainfrom
refactor/turnstile-sitekey

Conversation

@stalniy
Copy link
Contributor

@stalniy stalniy commented May 14, 2025

Why

Our e2e tests cannot bypass turnstile check

What

  1. Follows https://developers.cloudflare.com/turnstile/tutorials/excluding-turnstile-from-e2e-tests/ to disable turnstile for our tests
  2. Fetches turnstile sitekey from nextjs api, so it can be safely changed based on private token
  3. Updates gha
  4. Refactors service object to DI container-like structure, so we don't create instances until we need them

Summary by CodeRabbit

  • New Features

    • Added dynamic fetching of the Turnstile site key from app configuration, with support for test tokens.
    • Introduced an API endpoint to provide configuration data, including the Turnstile site key.
    • Added a new React hook to access application configuration.
    • Implemented a dependency injection container for modular service instantiation.
    • Added required inputs and Doppler integration for UI tests in GitHub Actions.
  • Improvements

    • Refactored service creation for more modular and lazy initialization.
    • Moved Turnstile component rendering within the React Query context for improved integration.
    • Updated UI tests to automatically inject authentication tokens into relevant API requests.
  • Testing

    • Enhanced Playwright test setup to support custom test tokens and environment configuration.
    • Updated test imports for consistency and maintainability.
  • Chores

    • Added new environment variables to configuration files and samples.
    • Updated GitHub Actions workflows to support new test token handling and Doppler integration.

@stalniy stalniy requested a review from a team as a code owner May 14, 2025 03:45
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 14, 2025

Walkthrough

This update introduces a dynamic configuration system for the Turnstile site key, enabling secure test token injection for UI tests. It adds a new API endpoint for configuration, updates the dependency injection and service instantiation patterns, and enhances Playwright test fixtures to support authenticated test requests. Workflow and environment variable configurations are also adjusted accordingly.

Changes

File(s) Change Summary
.github/actions/console-web-ui-testing/action.yml, .github/workflows/console-web-release.yml Added required Doppler token and UI test token name inputs; updated workflow to install Doppler CLI, fetch, and inject UI test tokens for UI testing.
.github/workflows/console-web-docker-build.yml Removed base_sha parameter from Codecov action.
apps/deploy-web/src/components/turnstile/Turnstile.tsx Refactored Turnstile to fetch site key from dynamic app config instead of props; removed siteKey prop.
apps/deploy-web/src/pages/_app.tsx Moved ClientOnlyTurnstile inside QueryClientProvider.
apps/deploy-web/src/pages/api/config.ts Added new API route to serve Turnstile site key, conditionally using test or public key based on UI tests token in request header; logs warning if token missing when protection enabled.
apps/deploy-web/src/config/env-config.schema.ts Added optional TURNSTILE_TEST_SITE_KEY with default test key and optional UI_TESTS_TOKEN to server environment schema.
apps/deploy-web/src/queries/useAppConfig.ts Added useAppConfig hook for fetching remote config via React Query with infinite cache lifetime.
apps/deploy-web/src/queries/useBalancesQuery.ts Changed return type from undefined to null for missing balances; updated related hook types accordingly.
apps/deploy-web/src/services/config/config.service.ts Added ConfigService for fetching remote config; defined RemoteConfig interface.
apps/deploy-web/src/services/container/createContainer.ts Introduced generic DI container with circular dependency detection, lazy evaluation, and type-safe access.
apps/deploy-web/src/services/http-factory/http-factory.service.ts Refactored service instantiation to use DI container and modular interceptor application; added config service; replaced eager service creation with lazy factories; introduced withInterceptors helper.
apps/deploy-web/env/.env.sample Added UI_TESTS_TOKEN environment variable to sample env file.
apps/deploy-web/tests/fixture/base-test.ts Added Playwright test fixture to inject UI test token header into intercepted API requests.
apps/deploy-web/tests/fixture/test-env.config.ts Added optional UI_TESTS_TOKEN to test environment schema.
apps/deploy-web/tests/build-template.spec.ts, apps/deploy-web/tests/deploy-custom-template.spec.ts, apps/deploy-web/tests/deploy-linux.spec.ts Changed Playwright test imports to use new local base-test fixture module.
apps/deploy-web/tests/fixture/context-with-extension.ts Updated test import to use new local base-test fixture module.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant TurnstileComponent
    participant useAppConfig
    participant ConfigService
    participant API_Config_Endpoint

    Client->>TurnstileComponent: Render
    TurnstileComponent->>useAppConfig: Fetch config (enabled)
    useAppConfig->>ConfigService: getConfig()
    ConfigService->>API_Config_Endpoint: GET /api/config (with optional UI test token)
    API_Config_Endpoint-->>ConfigService: { TURNSTILE_SITE_KEY }
    ConfigService-->>useAppConfig: Config data
    useAppConfig-->>TurnstileComponent: Config data
    TurnstileComponent-->>Client: Render Turnstile with site key
Loading
sequenceDiagram
    participant PlaywrightTest
    participant base-test.ts
    participant API_Mainnet/Sandbox

    PlaywrightTest->>base-test.ts: beforeEach
    base-test.ts->>API_Mainnet/Sandbox: Intercept request, add x-ui-tests-token header
    API_Mainnet/Sandbox-->>PlaywrightTest: Response (with test context)
Loading

Poem

In code we hop, from field to field,
Now Turnstile’s key is never revealed—
It’s fetched with care, a secret dance,
While tokens for tests get their chance.
Dependency magic, config anew,
The bunnies rejoice: “CI hops smoother for you!”
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ 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
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: 5

🧹 Nitpick comments (5)
apps/deploy-web/src/services/config/config.service.ts (1)

1-11: Well-designed config service for dynamic Turnstile site key fetching

The new ConfigService follows good software design principles:

  1. It extends the base HttpService for HTTP functionality
  2. Defines a clear interface for the remote configuration
  3. Implements a simple method for fetching configuration

This approach enables dynamic configuration of the Turnstile site key based on whether the request comes from a test environment.

However, I recommend enhancing the error handling:

 export class ConfigService extends HttpService {
   async getConfig(): Promise<RemoteConfig> {
-    return this.extractData(await this.get<RemoteConfig>("/api/config"));
+    try {
+      return this.extractData(await this.get<RemoteConfig>("/api/config"));
+    } catch (error) {
+      console.error("Failed to fetch remote config:", error);
+      // Fallback to default configuration
+      return { TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "" };
+    }
   }
 }
apps/deploy-web/tests/fixture/base-test.ts (1)

15-17: Consider more specific route patterns for token injection

The current route patterns will add the token to a broad set of requests. While the mainnet and sandbox API routes make sense, the localhost pattern will intercept all requests to the local server.

If not all routes need the token, consider using more specific patterns:

  await page.route("**/api-mainnet/**", addUITestsToken);
  await page.route("**/api-sandbox/**", addUITestsToken);
- await page.route("http://localhost:3000/**", addUITestsToken);
+ await page.route("http://localhost:3000/api/**", addUITestsToken);

Or be explicit about which specific endpoints need the token if you know them.

apps/deploy-web/src/pages/api/config.ts (1)

8-10: Improve warning message clarity

The warning message about missing UI_TESTS_TOKEN is good defensive programming, but could be more actionable.

Consider improving the warning message to be more actionable:

- logger.warn(`UI_TESTS_TOKEN is not set, but turnstile protection is enabled.` + `It means UI tests will not be able to pass the turnstile protection.`);
+ logger.warn(`UI_TESTS_TOKEN is not set, but turnstile protection is enabled. UI tests will fail unless you set UI_TESTS_TOKEN in your environment. See documentation for setup instructions.`);
apps/deploy-web/src/queries/useAppConfig.ts (1)

8-14: Consider retry strategy for config fetching

The current implementation doesn't specify a retry strategy for fetching configuration. Since this is critical app configuration, you might want to ensure it reliably loads.

Add a retry strategy to the query configuration:

   const { data } = useQuery({
     queryKey: ["app-config"],
     queryFn: () => di.config.getConfig(),
     gcTime: Infinity,
+    retry: 3,
+    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
     ...options
   });
.github/actions/console-web-ui-testing/action.yml (1)

18-20: Document behavior with empty token value

The ui-tests-token input has an empty default value, but it's not clear how the system behaves with this value.

Improve the documentation to clarify the behavior with an empty token:

   ui-tests-token:
-    description: UI tests token used to bypass turnstile check
-    default: ""
+    description: UI tests token used to bypass turnstile check. If empty, tests will use the production Turnstile site key.
+    default: ""
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ed82ed2 and cabcabd.

📒 Files selected for processing (16)
  • .github/actions/console-web-ui-testing/action.yml (3 hunks)
  • .github/workflows/console-web-release.yml (1 hunks)
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx (4 hunks)
  • apps/deploy-web/src/config/env-config.schema.ts (1 hunks)
  • apps/deploy-web/src/pages/_app.tsx (1 hunks)
  • apps/deploy-web/src/pages/api/config.ts (1 hunks)
  • apps/deploy-web/src/queries/useAppConfig.ts (1 hunks)
  • apps/deploy-web/src/queries/useBalancesQuery.ts (2 hunks)
  • apps/deploy-web/src/services/config/config.service.ts (1 hunks)
  • apps/deploy-web/src/services/container/createContainer.ts (1 hunks)
  • apps/deploy-web/src/services/http-factory/http-factory.service.ts (1 hunks)
  • apps/deploy-web/tests/build-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-custom-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-linux.spec.ts (1 hunks)
  • apps/deploy-web/tests/fixture/base-test.ts (1 hunks)
  • apps/deploy-web/tests/fixture/context-with-extension.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
apps/deploy-web/src/pages/_app.tsx (1)
apps/deploy-web/src/components/turnstile/Turnstile.tsx (1)
  • ClientOnlyTurnstile (181-181)
apps/deploy-web/src/services/config/config.service.ts (1)
packages/http-sdk/src/http/http.service.ts (1)
  • HttpService (3-15)
apps/deploy-web/src/queries/useAppConfig.ts (2)
apps/deploy-web/src/services/config/config.service.ts (1)
  • RemoteConfig (9-11)
apps/deploy-web/src/context/ServicesProvider/index.tsx (1)
  • useServices (26-28)
apps/deploy-web/src/queries/useBalancesQuery.ts (2)
apps/api/src/billing/controllers/wallet/wallet.controller.ts (1)
  • getBalances (48-70)
apps/deploy-web/src/types/address.ts (1)
  • Balances (41-50)
apps/deploy-web/src/components/turnstile/Turnstile.tsx (2)
apps/deploy-web/src/config/browser-env.config.ts (1)
  • browserEnvConfig (3-40)
apps/deploy-web/src/queries/useAppConfig.ts (1)
  • useAppConfig (6-16)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test-deploy-web-build
🔇 Additional comments (21)
apps/deploy-web/tests/build-template.spec.ts (1)

1-1: Properly imported test utilities from the local fixture.

The import source for expect and test has been changed from @playwright/test to the local module ./fixture/base-test. This change is appropriate as it leverages a custom test fixture that automatically adds the x-ui-tests-token header to network requests, allowing Turnstile to be bypassed during e2e tests.

apps/deploy-web/tests/deploy-custom-template.spec.ts (1)

2-2: Properly imported test utilities from the local fixture.

The import source for expect and test has been changed from @playwright/test to the local module ./fixture/base-test. This change is appropriate as it leverages a custom test fixture that automatically adds the x-ui-tests-token header to network requests, allowing Turnstile to be bypassed during e2e tests.

apps/deploy-web/tests/deploy-linux.spec.ts (1)

1-1: Properly imported test utilities from the local fixture.

The import source for expect and test has been changed from @playwright/test to the local module ./fixture/base-test. This change is appropriate as it leverages a custom test fixture that automatically adds the x-ui-tests-token header to network requests, allowing Turnstile to be bypassed during e2e tests.

apps/deploy-web/src/pages/_app.tsx (1)

64-64:

Details

✅ Verification successful

ClientOnlyTurnstile now properly positioned within QueryClientProvider.

The ClientOnlyTurnstile component has been repositioned inside the QueryClientProvider which is appropriate since it now needs access to React Query's context to dynamically fetch the Turnstile site key via the useAppConfig hook. This change supports the dynamic configuration approach described in the PR objectives.

To ensure the component is properly retrieving the Turnstile site key, we can verify if the useAppConfig hook is being used correctly:


🏁 Script executed:

#!/bin/bash
# Check if Turnstile component is using the useAppConfig hook
rg -A 3 "const ClientOnlyTurnstile|function Turnstile" apps/deploy-web/src/components/turnstile/Turnstile.tsx

Length of output: 205


🏁 Script executed:

#!/bin/bash
# Locate the Turnstile component definition
rg -n "function Turnstile" -A 5 apps/deploy-web/src/components/turnstile/Turnstile.tsx

# Check for useAppConfig hook usage within the Turnstile component
rg -n "useAppConfig" -A 5 apps/deploy-web/src/components/turnstile/Turnstile.tsx

Length of output: 719


🏁 Script executed:

#!/bin/bash
# Verify that ClientOnlyTurnstile is nested within QueryClientProvider in _app.tsx
rg -n "QueryClientProvider" -A 10 -B 10 apps/deploy-web/src/pages/_app.tsx

Length of output: 2821


ClientOnlyTurnstile correctly accesses React Query context

The ClientOnlyTurnstile component is now properly wrapped by <QueryClientProvider> in apps/deploy-web/src/pages/_app.tsx (lines 63–64), and the underlying Turnstile implementation imports and calls useAppConfig (line 52 in apps/deploy-web/src/components/turnstile/Turnstile.tsx) to fetch the site key dynamically. No further changes are needed here.

.github/workflows/console-web-release.yml (1)

53-53: Properly integrated UI tests token for Turnstile bypass

The addition of the ui-tests-token parameter to the UI testing action ensures that e2e tests can bypass the Turnstile verification as intended. This is a clean implementation that follows security best practices by using GitHub secrets.

apps/deploy-web/tests/fixture/context-with-extension.ts (1)

2-3: Good refactoring of test imports for token injection

The import changes correctly separate the chromium import and switch to using the local base-test module. This change enables the global token injection for API requests during e2e tests, making Turnstile bypass possible while keeping the original test functionality intact.

Also applies to: 8-9

apps/deploy-web/src/config/env-config.schema.ts (1)

63-69: Well-implemented environment variables for Turnstile testing

The addition of TURNSTILE_TEST_SITE_KEY with the Cloudflare dummy key default and the optional UI_TESTS_TOKEN variable provides a clean way to handle the Turnstile bypass mechanism. The code comments documenting the source of the dummy key are particularly helpful.

apps/deploy-web/src/queries/useBalancesQuery.ts (2)

17-18: Type consistency improvement.

Changed return type from undefined to null for the absence of data. This creates more consistent typing throughout the application and makes the behavior more explicit.


64-64: Type signature updated to match implementation.

The generic type parameter for UseQueryOptions has been updated to reflect the change from undefined to null in the underlying function, maintaining type consistency throughout the component.

apps/deploy-web/src/components/turnstile/Turnstile.tsx (5)

17-17: Added import for dynamic configuration.

The new import enables the component to fetch the Turnstile site key from the app configuration service instead of using a hardcoded value.


47-47: Removed hardcoded site key in favor of dynamic configuration.

This change aligns with the PR's objective to dynamically fetch the Turnstile site key, making it possible to modify it for e2e tests without changing code.


52-52: Fetch configuration dynamically based on enabled state.

The useAppConfig hook is passed the enabled parameter to control when configuration is loaded, which is an efficient approach that prevents unnecessary API calls when Turnstile is disabled.


113-113: Check for both enabled state and site key availability.

This conditional correctly handles cases where the component should not render - either when explicitly disabled or when the site key is not available in the configuration.


135-135: Use dynamically loaded site key for Turnstile widget.

The component now uses the site key from the app configuration rather than a hardcoded value, supporting the PR's objective of making the site key configurable for testing.

apps/deploy-web/src/services/container/createContainer.ts (2)

1-28: Well-implemented dependency injection container.

This utility creates a container with lazily evaluated properties, ensuring efficient resource usage and proper dependency management. The circular dependency detection is a good safeguard against potential runtime issues.

The implementation correctly:

  1. Creates getters for lazy initialization
  2. Tracks resolution path to detect cycles
  3. Caches instances to ensure singletons
  4. Provides helpful error messages for circular dependencies

This pattern supports the PR's objective by enabling modular and testable service configuration.


30-32: Type-safe container type definition.

This type alias ensures that the container's properties match the return types of the factory functions, providing compile-time type safety for accessing resolved instances.

apps/deploy-web/src/services/http-factory/http-factory.service.ts (5)

9-10: Added imports for new configuration service and container utility.

These imports support the PR's objective by introducing the configuration service needed for dynamic Turnstile site key fetching and the container utility for modular service management.


15-64: Refactored service creation to use dependency injection container.

The implementation has been improved to use a modular container-based approach that:

  1. Lazy-loads services only when needed
  2. Applies interceptors consistently
  3. Simplifies service creation and management
  4. Adds a new configuration service for dynamic app settings

This supports the PR's objective of fetching the Turnstile site key dynamically from an API endpoint.


60-63: Added configuration service with appropriate interceptors.

The new config service will handle fetching remote configuration including the Turnstile site key. It's properly configured with the global request middleware for consistent request handling.


73-77: Helper function for applying interceptors to axios instances.

This utility function cleanly encapsulates the logic for adding request and response interceptors to axios instances, improving code readability and maintainability.


79-83: Type definitions for interceptors.

These types provide proper typing for the interceptor configuration, ensuring type safety when configuring services with interceptors.

@stalniy stalniy force-pushed the refactor/turnstile-sitekey branch from cabcabd to 0856fe1 Compare May 14, 2025 03:55
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: 0

🧹 Nitpick comments (2)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (2)

79-83: Consider filtering undefined interceptors.

The interceptors array may contain undefined values (as indicated by the type), but there's no filtering of these values before applying them.

function withInterceptors<T extends Axios>(axios: T, interceptors: Interceptors) {
-  interceptors.request?.forEach(interceptor => axios.interceptors.request.use(interceptor));
-  interceptors.response?.forEach(interceptor => axios.interceptors.response.use(interceptor));
+  interceptors.request?.filter(Boolean).forEach(interceptor => axios.interceptors.request.use(interceptor));
+  interceptors.response?.filter(Boolean).forEach(interceptor => axios.interceptors.response.use(interceptor));
  return axios;
}

15-64: Consider adding error handling for service initialization.

The container pattern is excellent, but there's no explicit error handling for service initialization failures. Consider adding try/catch blocks or a global error handler for services that might fail during initialization.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cabcabd and 0856fe1.

📒 Files selected for processing (17)
  • .github/actions/console-web-ui-testing/action.yml (3 hunks)
  • .github/workflows/console-web-release.yml (1 hunks)
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx (4 hunks)
  • apps/deploy-web/src/config/env-config.schema.ts (1 hunks)
  • apps/deploy-web/src/pages/_app.tsx (1 hunks)
  • apps/deploy-web/src/pages/api/config.ts (1 hunks)
  • apps/deploy-web/src/queries/useAppConfig.ts (1 hunks)
  • apps/deploy-web/src/queries/useBalancesQuery.ts (2 hunks)
  • apps/deploy-web/src/services/config/config.service.ts (1 hunks)
  • apps/deploy-web/src/services/container/createContainer.ts (1 hunks)
  • apps/deploy-web/src/services/http-factory/http-factory.service.ts (1 hunks)
  • apps/deploy-web/tests/build-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-custom-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-linux.spec.ts (1 hunks)
  • apps/deploy-web/tests/fixture/base-test.ts (1 hunks)
  • apps/deploy-web/tests/fixture/context-with-extension.ts (1 hunks)
  • apps/deploy-web/tests/fixture/test-env.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • apps/deploy-web/tests/deploy-custom-template.spec.ts
  • apps/deploy-web/tests/fixture/test-env.config.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • apps/deploy-web/tests/build-template.spec.ts
  • apps/deploy-web/src/pages/_app.tsx
  • apps/deploy-web/tests/fixture/context-with-extension.ts
  • apps/deploy-web/src/services/config/config.service.ts
  • apps/deploy-web/tests/deploy-linux.spec.ts
  • apps/deploy-web/src/queries/useAppConfig.ts
  • .github/actions/console-web-ui-testing/action.yml
  • apps/deploy-web/src/config/env-config.schema.ts
  • .github/workflows/console-web-release.yml
  • apps/deploy-web/src/services/container/createContainer.ts
  • apps/deploy-web/src/queries/useBalancesQuery.ts
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx
  • apps/deploy-web/tests/fixture/base-test.ts
  • apps/deploy-web/src/pages/api/config.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test-deploy-web-build
🔇 Additional comments (5)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (5)

3-3: Good use of explicit type imports.

The change from importing all of axios to importing specific types improves code clarity and potentially reduces bundle size.


9-10: Good additions for dependency management.

Importing the ConfigService and createContainer supports the goal of fetching the Turnstile sitekey dynamically and implementing a DI container pattern.


15-64: Excellent refactoring to use container pattern.

The refactoring to use a container pattern for service instantiation greatly improves code organization and maintainability by:

  1. Centralizing service creation
  2. Enabling dependency injection
  3. Allowing for service instance caching
  4. Making service configuration more consistent

This approach aligns well with the PR objective of making the Turnstile sitekey configurable.


60-63: Good addition of ConfigService.

Adding the ConfigService as a dependency enables the fetching of dynamic configuration including the Turnstile sitekey, which directly supports the PR objectives.


73-77: Well-designed helper function for interceptor management.

The withInterceptors function elegantly modularizes the process of attaching request and response interceptors to Axios instances, reducing code duplication and improving readability.

@stalniy stalniy force-pushed the refactor/turnstile-sitekey branch from 0856fe1 to e1de86d Compare May 14, 2025 04:29
coderabbitai[bot]

This comment was marked as outdated.

@stalniy stalniy force-pushed the refactor/turnstile-sitekey branch 2 times, most recently from 624eb09 to c765087 Compare May 14, 2025 04:46
@codecov
Copy link

codecov bot commented May 14, 2025

Codecov Report

Attention: Patch coverage is 52.30769% with 31 lines in your changes missing coverage. Please review.

Project coverage is 33.56%. Comparing base (162f732) to head (61d4f93).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
apps/deploy-web/src/pages/api/config.ts 0.00% 10 Missing ⚠️
apps/deploy-web/src/queries/useAppConfig.ts 0.00% 7 Missing ⚠️
.../deploy-web/src/components/turnstile/Turnstile.tsx 0.00% 4 Missing ⚠️
.../src/services/http-factory/http-factory.service.ts 80.95% 4 Missing ⚠️
apps/deploy-web/src/queries/useBalancesQuery.ts 0.00% 3 Missing ⚠️
...s/deploy-web/src/services/config/config.service.ts 50.00% 2 Missing ⚠️
...ploy-web/src/services/container/createContainer.ts 93.75% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1318      +/-   ##
==========================================
+ Coverage   33.50%   33.56%   +0.05%     
==========================================
  Files         770      774       +4     
  Lines       19009    19052      +43     
  Branches     3537     3551      +14     
==========================================
+ Hits         6369     6394      +25     
- Misses      11891    12308     +417     
+ Partials      749      350     -399     
Flag Coverage Δ *Carryforward flag
api 64.09% <ø> (ø) Carriedforward from 162f732
deploy-web 12.70% <52.30%> (+0.16%) ⬆️
notifications 89.49% <ø> (ø) Carriedforward from 162f732
provider-proxy 80.09% <ø> (ø) Carriedforward from 162f732

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
apps/deploy-web/src/config/env-config.schema.ts 58.33% <ø> (ø)
apps/deploy-web/src/pages/_app.tsx 0.00% <ø> (ø)
...ploy-web/src/services/container/createContainer.ts 93.75% <93.75%> (ø)
...s/deploy-web/src/services/config/config.service.ts 50.00% <50.00%> (ø)
apps/deploy-web/src/queries/useBalancesQuery.ts 27.77% <0.00%> (ø)
.../deploy-web/src/components/turnstile/Turnstile.tsx 0.00% <0.00%> (ø)
.../src/services/http-factory/http-factory.service.ts 86.66% <80.95%> (+8.40%) ⬆️
apps/deploy-web/src/queries/useAppConfig.ts 0.00% <0.00%> (ø)
apps/deploy-web/src/pages/api/config.ts 0.00% <0.00%> (ø)

... and 136 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@stalniy stalniy force-pushed the refactor/turnstile-sitekey branch 5 times, most recently from 9d000f7 to 8b631cc Compare May 15, 2025 14:19
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: 0

🧹 Nitpick comments (1)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (1)

79-83: Well-defined types for interceptors

These type definitions provide good type safety for the interceptor pattern. The optional arrays allow flexibility in applying different interceptors to different services.

However, consider making these types more reusable by moving them to a separate types file if they might be used in other modules.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between c765087 and 8b631cc.

📒 Files selected for processing (19)
  • .github/actions/console-web-ui-testing/action.yml (3 hunks)
  • .github/workflows/console-web-docker-build.yml (0 hunks)
  • .github/workflows/console-web-release.yml (1 hunks)
  • apps/deploy-web/env/.env.sample (1 hunks)
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx (4 hunks)
  • apps/deploy-web/src/config/env-config.schema.ts (1 hunks)
  • apps/deploy-web/src/pages/_app.tsx (1 hunks)
  • apps/deploy-web/src/pages/api/config.ts (1 hunks)
  • apps/deploy-web/src/queries/useAppConfig.ts (1 hunks)
  • apps/deploy-web/src/queries/useBalancesQuery.ts (2 hunks)
  • apps/deploy-web/src/services/config/config.service.ts (1 hunks)
  • apps/deploy-web/src/services/container/createContainer.ts (1 hunks)
  • apps/deploy-web/src/services/http-factory/http-factory.service.ts (1 hunks)
  • apps/deploy-web/tests/build-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-custom-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-linux.spec.ts (1 hunks)
  • apps/deploy-web/tests/fixture/base-test.ts (1 hunks)
  • apps/deploy-web/tests/fixture/context-with-extension.ts (1 hunks)
  • apps/deploy-web/tests/fixture/test-env.config.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • .github/workflows/console-web-docker-build.yml
🚧 Files skipped from review as they are similar to previous changes (17)
  • apps/deploy-web/env/.env.sample
  • apps/deploy-web/tests/build-template.spec.ts
  • apps/deploy-web/tests/deploy-linux.spec.ts
  • apps/deploy-web/src/pages/_app.tsx
  • apps/deploy-web/tests/deploy-custom-template.spec.ts
  • apps/deploy-web/tests/fixture/test-env.config.ts
  • apps/deploy-web/src/pages/api/config.ts
  • apps/deploy-web/tests/fixture/context-with-extension.ts
  • apps/deploy-web/src/services/config/config.service.ts
  • .github/workflows/console-web-release.yml
  • apps/deploy-web/src/config/env-config.schema.ts
  • .github/actions/console-web-ui-testing/action.yml
  • apps/deploy-web/tests/fixture/base-test.ts
  • apps/deploy-web/src/services/container/createContainer.ts
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx
  • apps/deploy-web/src/queries/useBalancesQuery.ts
  • apps/deploy-web/src/queries/useAppConfig.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (11)
apps/deploy-web/src/services/container/createContainer.ts (1)
  • createContainer (1-28)
apps/deploy-web/src/services/auth/auth.service.ts (1)
  • authService (23-23)
apps/deploy-web/src/services/analytics/analytics.service.ts (1)
  • analyticsService (254-271)
packages/http-sdk/src/stripe/stripe.service.ts (1)
  • StripeService (12-20)
packages/http-sdk/src/tx-http/tx-http.service.ts (1)
  • TxHttpService (15-34)
apps/provider-console/src/utils/customRegistry.ts (1)
  • customRegistry (2-2)
packages/http-sdk/src/template/template-http.service.ts (1)
  • TemplateHttpService (34-46)
packages/http-sdk/src/auth/auth-http.service.ts (1)
  • AuthHttpService (5-13)
apps/deploy-web/src/services/provider-proxy/provider-proxy.service.ts (1)
  • ProviderProxyService (4-23)
packages/http-sdk/src/api-key/api-key-http.service.ts (1)
  • ApiKeyHttpService (4-16)
apps/deploy-web/src/services/config/config.service.ts (1)
  • ConfigService (3-7)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test-deploy-web-build
🔇 Additional comments (5)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (5)

3-3: Type imports added to support new interceptor implementation

The explicit import of Axios types is necessary for the new interceptor pattern introduced in this refactoring.


9-10: Added imports for the new dependency injection pattern

These imports support the refactoring to a lazy dependency injection container pattern, which is a good improvement that delays service instantiation until needed.


15-64: Well-structured refactoring to a dependency injection container

The refactoring from eagerly instantiated services to a lazy DI container is well-implemented. Each service is now created through a factory function and properly configured with interceptors. This approach:

  1. Improves performance by only instantiating services when needed
  2. Prevents circular dependencies (as handled in createContainer)
  3. Makes the code more maintainable with consistent initialization patterns

The addition of the config service (lines 60-63) aligns with the PR objective of fetching Turnstile sitekey from an API.


73-77: Clean implementation of interceptor application

The withInterceptors helper function provides a consistent way to apply request and response interceptors to Axios instances. This improves code maintainability by centralizing interceptor application logic.


56-59:

Details

✅ Verification successful

Verify axios instance usage

You're creating a generic axios instance without specifying a baseURL. Make sure this is intentional and that consumers of this instance are aware they need to provide full URLs.


🏁 Script executed:

#!/bin/bash
# Look for usages of the axios service to ensure they provide full URLs
rg -A 5 "services\.(axios|httpFactory\.axios)" --type ts

Length of output: 3032


All axios calls supply full URLs

I’ve checked all uses of services.axios—each call is passed a complete URL (either via ApiUrlService.* helpers or serverEnvConfig.BASE_API_MAINNET_URL), so the omission of a default baseURL is intentional and safe. No changes are needed here.

@stalniy stalniy force-pushed the refactor/turnstile-sitekey branch from 8b631cc to 61d4f93 Compare May 16, 2025 05:37
@stalniy stalniy enabled auto-merge (squash) May 16, 2025 05:37
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: 0

🧹 Nitpick comments (1)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (1)

15-64: Consider adding error handling to interceptors.

While the implementation is solid, there's no explicit error handling for interceptors. If any interceptor throws an exception, it might affect the entire request/response chain.

Consider adding error handling to protect against interceptor failures:

function withInterceptors<T extends Axios>(axios: T, interceptors: Interceptors) {
-  interceptors.request?.forEach(interceptor => axios.interceptors.request.use(interceptor));
-  interceptors.response?.forEach(interceptor => axios.interceptors.response.use(interceptor));
+  interceptors.request?.forEach(interceptor => 
+    axios.interceptors.request.use(
+      interceptor,
+      error => Promise.reject(error)
+    )
+  );
+  interceptors.response?.forEach(interceptor => 
+    axios.interceptors.response.use(
+      interceptor,
+      error => Promise.reject(error)
+    )
+  );
  return axios;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 8b631cc and 61d4f93.

📒 Files selected for processing (19)
  • .github/actions/console-web-ui-testing/action.yml (3 hunks)
  • .github/workflows/console-web-docker-build.yml (0 hunks)
  • .github/workflows/console-web-release.yml (1 hunks)
  • apps/deploy-web/env/.env.sample (1 hunks)
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx (4 hunks)
  • apps/deploy-web/src/config/env-config.schema.ts (1 hunks)
  • apps/deploy-web/src/pages/_app.tsx (1 hunks)
  • apps/deploy-web/src/pages/api/config.ts (1 hunks)
  • apps/deploy-web/src/queries/useAppConfig.ts (1 hunks)
  • apps/deploy-web/src/queries/useBalancesQuery.ts (2 hunks)
  • apps/deploy-web/src/services/config/config.service.ts (1 hunks)
  • apps/deploy-web/src/services/container/createContainer.ts (1 hunks)
  • apps/deploy-web/src/services/http-factory/http-factory.service.ts (1 hunks)
  • apps/deploy-web/tests/build-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-custom-template.spec.ts (1 hunks)
  • apps/deploy-web/tests/deploy-linux.spec.ts (1 hunks)
  • apps/deploy-web/tests/fixture/base-test.ts (1 hunks)
  • apps/deploy-web/tests/fixture/context-with-extension.ts (1 hunks)
  • apps/deploy-web/tests/fixture/test-env.config.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • .github/workflows/console-web-docker-build.yml
✅ Files skipped from review due to trivial changes (1)
  • apps/deploy-web/tests/build-template.spec.ts
🚧 Files skipped from review as they are similar to previous changes (16)
  • apps/deploy-web/env/.env.sample
  • apps/deploy-web/src/pages/_app.tsx
  • apps/deploy-web/tests/deploy-custom-template.spec.ts
  • .github/workflows/console-web-release.yml
  • apps/deploy-web/tests/fixture/context-with-extension.ts
  • apps/deploy-web/tests/deploy-linux.spec.ts
  • apps/deploy-web/src/services/config/config.service.ts
  • apps/deploy-web/src/pages/api/config.ts
  • apps/deploy-web/src/config/env-config.schema.ts
  • apps/deploy-web/tests/fixture/base-test.ts
  • apps/deploy-web/src/queries/useAppConfig.ts
  • apps/deploy-web/src/queries/useBalancesQuery.ts
  • apps/deploy-web/tests/fixture/test-env.config.ts
  • apps/deploy-web/src/components/turnstile/Turnstile.tsx
  • .github/actions/console-web-ui-testing/action.yml
  • apps/deploy-web/src/services/container/createContainer.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test-deploy-web-build
🔇 Additional comments (4)
apps/deploy-web/src/services/http-factory/http-factory.service.ts (4)

3-3: Good additions for the new dependency injection pattern.

The imports of Axios types and the new ConfigService and createContainer utilities properly support the refactoring to a container-based approach with lazy initialization.

Also applies to: 9-10


15-64: Well-structured service container implementation.

The refactoring to use a container-based approach with factory functions is a good architectural improvement that:

  1. Enables lazy initialization (services are only created when needed)
  2. Makes the code more modular and maintainable
  3. Provides a consistent pattern for adding interceptors to each service
  4. Properly preserves the existing behavior (auth headers, analytics tracking)

The addition of the config service aligns perfectly with the PR objective to fetch the Turnstile sitekey dynamically.


73-77: Clean utility function for interceptor management.

The withInterceptors helper function is a good abstraction that centralizes the logic for attaching interceptors to Axios instances. The implementation is concise and reusable.


79-83: Well-designed type definitions for interceptors.

The type definitions for interceptors provide good type safety and help document the expected shape of interceptor functions. The use of optional arrays in the Interceptors interface allows for flexibility in configuration.

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.

3 participants

Comments