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

chore: run dist with environment variables kyb-app #2645

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from

Conversation

pratapalakshmi
Copy link
Collaborator

@pratapalakshmi pratapalakshmi commented Aug 18, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced an entrypoint.sh script to initialize environment variables for the application.
    • Added a global configuration object env to store environment-related settings.
    • Included a new script tag in the HTML to utilize configurations from config.js.
  • Improvements

    • Enhanced Dockerfile for better build and deployment processes.
    • Updated request handling to use the new global configuration for API URLs.
  • Bug Fixes

    • Ensured default values for environment variables are set correctly.

Copy link

changeset-bot bot commented Aug 18, 2024

⚠️ No Changeset found

Latest commit: 79908d6

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Aug 18, 2024

Walkthrough

The changes in this pull request involve modifications to the Dockerfile, the addition of an entrypoint.sh script, and updates to various application files in the kyb-app. The Dockerfile has been enhanced for better build and runtime configurations, including the transfer of built assets to Nginx. The entrypoint.sh script initializes environment variables and generates a configuration file. A new global variable env has been introduced to store environment settings, and an external script is included in the HTML to utilize these configurations.

Changes

File Path Change Summary
apps/kyb-app/Dockerfile Updated build and runtime configuration, set WORKDIR, added RUN npm run build, and configured Nginx.
apps/kyb-app/entrypoint.sh Added script to initialize environment variables and generate config.js.
apps/kyb-app/global.d.ts Introduced new global variable env for storing environment configurations.
apps/kyb-app/index.html Added script tag to include /config.js for accessing environment variables.
apps/kyb-app/public/config.js Created global configuration object env with default values for environment variables.
apps/kyb-app/src/common/utils/request.ts Updated prefixUrl to use globalThis.env.VITE_API_URL instead of import.meta.env.VITE_API_URL.

Possibly related PRs

  • fix: docker-compose-build with .env #2489: The changes in this PR involve modifications to the .env file, which is relevant to the environment variable handling in the main PR's entrypoint.sh and config.js, as both deal with environment configurations for the application.

Suggested reviewers

  • liorzam
  • Omri-Levy
  • alonp99

🐰 In the code, we hop and play,
With scripts and configs, bright as day.
Environment set, our paths align,
Nginx awaits, our app will shine!
So let’s build and run, with joy we sing,
A rabbit's cheer for the changes we bring! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e5c465e and 79908d6.

📒 Files selected for processing (1)
  • apps/kyb-app/src/common/utils/request.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/kyb-app/src/common/utils/request.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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.

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.

@pratapalakshmi pratapalakshmi force-pushed the chore/run/time/dist/kyb-app branch from 33eb823 to 9a7d109 Compare September 8, 2024 06:44
@pratapalakshmi pratapalakshmi marked this pull request as ready for review September 8, 2024 12:23
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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5506a77 and ad69665.

Files selected for processing (7)
  • apps/kyb-app/Dockerfile (1 hunks)
  • apps/kyb-app/entrypoint.sh (1 hunks)
  • apps/kyb-app/global.d.ts (1 hunks)
  • apps/kyb-app/index.html (1 hunks)
  • apps/kyb-app/public/config.js (1 hunks)
  • apps/kyb-app/src/common/utils/request.ts (1 hunks)
  • apps/kyb-app/src/main.tsx (2 hunks)
Files skipped from review due to trivial changes (1)
  • apps/kyb-app/global.d.ts
Additional context used
Shellcheck
apps/kyb-app/entrypoint.sh

[warning] 3-3: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 8-8: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 13-13: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 19-19: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 24-24: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 29-29: In POSIX sh, [[ ]] is undefined.

(SC3010)

Additional comments not posted (7)
apps/kyb-app/index.html (1)

8-8: Script Tag Added for Configuration

The addition of the <script type="text/javascript" src="/config.js"></script> tag is approved as it ensures the global configuration is loaded early in the application lifecycle. However, ensure that no sensitive information is exposed through this script to enhance security.

Consider verifying the contents of config.js to ensure no sensitive data is exposed to the client-side.

apps/kyb-app/Dockerfile (1)

23-36: Dockerfile Enhancements for Better Structure and Functionality

The modifications to the Dockerfile are approved. These include:

  • Setting the working directory to /app which helps in standardizing the execution context.
  • Adding an entrypoint script which allows for custom initialization logic.
  • Making the script executable to avoid permission issues.

These changes enhance the Docker container's structure and functionality, facilitating smoother deployment. Ensure that the entrypoint script (entrypoint.sh) is thoroughly tested to confirm it performs as expected.

Consider adding automated tests or manual steps to verify the functionality of the entrypoint.sh script.

apps/kyb-app/entrypoint.sh (2)

34-43: Review the configuration file generation logic.

The script writes environment variables to a JavaScript configuration file. Ensure that the file path and variable names are correctly specified and that they match the application's requirements.

Verify the correctness and security implications of writing environment variables directly to a JavaScript file accessible via the web server.


3-6: Replace [[ ]] with POSIX-compliant syntax and verify default values.

The use of [[ ]] for condition checks is not POSIX compliant. Replace it with [ ] to ensure compatibility across different shell environments. Additionally, verify that the default values set for the environment variables are appropriate for the application's needs.

Apply this diff to correct the syntax:

- if [[ -z "$VITE_DOMAIN" ]]
+ if [ -z "$VITE_DOMAIN" ]
- if [[ -z "$VITE_API_KEY" ]]
+ if [ -z "$VITE_API_KEY" ]
- if [[ -z "$VITE_ENVIRONMENT_NAME" ]]
+ if [ -z "$VITE_ENVIRONMENT_NAME" ]
- if [[ -z "$VITE_DEFAULT_EXAMPLE_TOKEN" ]]
+ if [ -z "$VITE_DEFAULT_EXAMPLE_TOKEN" ]
- if [[ -z "$VITE_SENTRY_AUTH_TOKEN" ]]
+ if [ -z "$VITE_SENTRY_AUTH_TOKEN" ]
- if [[ -z "$VITE_SENTRY_DSN" ]]
+ if [ -z "$VITE_SENTRY_DSN" ]

Also applies to: 8-11, 13-16, 19-22, 24-27, 29-32

Tools
Shellcheck

[warning] 3-3: In POSIX sh, [[ ]] is undefined.

(SC3010)

apps/kyb-app/src/main.tsx (2)

17-17: Review the import of the configuration file.

Ensure that the import statement for the configuration file is correct and that the file is properly loaded into the application. This is crucial for the application's configuration management.


36-39: Address TypeScript type-checking issues.

The use of //@ts-ignore to bypass TypeScript type-checking could lead to runtime errors. Ensure that the types are correctly defined and that any potential issues are resolved before bypassing type-checking.

apps/kyb-app/src/common/utils/request.ts (1)

6-7: Review the modification of the prefixUrl property.

The change to use globalThis.env.VITE_API_URL for the prefixUrl is a significant shift that should be carefully reviewed to ensure it aligns with the application's architecture and security requirements.

Comment on lines 1 to 9
globalThis.env = {
VITE_API_URL: 'http://google.com',
VITE_KYB_DEFINITION_ID: "kyb_parent_kyc_session_example",
VITE_API_KEY: "secret",
VITE_ENVIRONMENT_NAME: "local",
VITE_DEFAULT_EXAMPLE_TOKEN: 12345678-1234-1234-1234-123456789012,
VITE_SENTRY_AUTH_TOKEN: "",
VITE_SENTRY_DSN: "",
};
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security and Syntax Concerns in Global Configuration

The configuration file introduces several potential issues:

  • Security Risk: Hardcoding sensitive information like API keys (VITE_API_KEY) and tokens (VITE_DEFAULT_EXAMPLE_TOKEN) in a public JavaScript file poses a significant security risk. Consider fetching these values securely from environment variables or a secure vault at runtime.
  • Syntax Error: The numeric token (VITE_DEFAULT_EXAMPLE_TOKEN) should be enclosed in quotes to prevent syntax errors and ensure it is treated as a string.

Consider the following changes to address these issues:

-  VITE_API_KEY: "secret",
-  VITE_DEFAULT_EXAMPLE_TOKEN: 12345678-1234-1234-1234-123456789012,
+  VITE_API_KEY: process.env.VITE_API_KEY,
+  VITE_DEFAULT_EXAMPLE_TOKEN: process.env.VITE_DEFAULT_EXAMPLE_TOKEN,

Committable suggestion was skipped due to low confidence.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should use default value if preset, if case someone set his value while running the docker container so you should consider the provided value:

globalThis.env = {
  VITE_API_URL: import.meta.env.VITE_API_URL || 'http://google.com',
  VITE_KYB_DEFINITION_ID: import.meta.env.VITE_KYB_DEFINITION_ID || 'kyb_parent_kyc_session_example',
  VITE_API_KEY: import.meta.env.VITE_API_KEY || 'secret',
  VITE_ENVIRONMENT_NAME: import.meta.env.VITE_ENVIRONMENT_NAME || 'local',
  VITE_DEFAULT_EXAMPLE_TOKEN: import.meta.env.VITE_DEFAULT_EXAMPLE_TOKEN || '12345678-1234-1234-1234-123456789012',
  VITE_SENTRY_AUTH_TOKEN: import.meta.env.VITE_SENTRY_AUTH_TOKEN || '',
  VITE_SENTRY_DSN: import.meta.env.VITE_SENTRY_DSN || '',
};

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@liorzam, thank you for the clarification.

Using import.meta.env.VAR_NAME || 'default value' is a good approach for setting default values while allowing overrides. However, please note that import.meta.env is only available at build time in Vite and may not be accessible in the config.js file at runtime when it's loaded in the browser.

Since config.js is served as a static file and loaded at runtime, accessing import.meta.env in this context may not work as expected. An alternative is to use the entrypoint.sh script to inject the environment variables into config.js at runtime, which seems to be the approach in this PR.

Additionally, we should be cautious about exposing sensitive information like API keys and tokens in frontend code, as they can be accessed by anyone using the application.

Let me know your thoughts on this.

(* ̄- ̄)


Learnings added
Learnt from: liorzam
PR: ballerine-io/ballerine#2645
File: apps/kyb-app/public/config.js:1-9
Timestamp: 2024-09-23T07:47:38.881Z
Learning: In `config.js`, avoid using `import.meta.env` as it is not available at runtime; instead, use environment variables injected via the `entrypoint.sh` script.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@@ -3,7 +3,8 @@ import * as Sentry from '@sentry/react';
import ky, { HTTPError } from 'ky';

export const request = ky.create({
prefixUrl: import.meta.env.VITE_API_URL || `${window.location.origin}/api/v1/`,
//@ts-ignore
prefixUrl: globalThis.env.VITE_API_URL,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as you see we used this import meta env which takes the value from env var

@@ -5,6 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>KYB - Collection Flow</title>
<script type="text/javascript" src="/config.js"></script>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wrong path

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No in the dist index.html and config.js stay in the same directory

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

🧹 Outside diff range and nitpick comments (6)
apps/kyb-app/public/config.js (2)

1-1: Consider a more secure configuration approach

Exposing configuration through globalThis in a public JavaScript file makes it accessible to anyone, potentially exposing sensitive information. Consider implementing a secure configuration service that provides only necessary, non-sensitive values to the frontend.


9-11: Improve error tracking configuration

While empty defaults for Sentry configuration are acceptable, consider:

  1. Adding validation to ensure Sentry is properly initialized when credentials are provided
  2. Implementing a fallback error handling mechanism when Sentry is not configured
// Example validation in your app initialization
if (globalThis.env.VITE_SENTRY_DSN) {
  // Initialize Sentry
} else {
  // Initialize fallback error handling
  console.warn('Sentry not configured, using fallback error handling');
}
apps/kyb-app/Dockerfile (1)

27-32: Consider relocating entrypoint.sh

Consider moving the entrypoint script to a dedicated docker or scripts directory for better organization and maintainability.

-COPY --from=dev /app/entrypoint.sh /app/entrypoint.sh
+COPY --from=dev /app/docker/entrypoint.sh /app/entrypoint.sh
apps/kyb-app/entrypoint.sh (1)

45-46: Add command validation and error handling

The script executes commands without validation or error handling.

Consider adding basic safeguards:

+# Ensure we have a command to execute
+if [ $# -eq 0 ]; then
+    echo "Error: No command provided"
+    exit 1
+fi
+
 # Handle CMD command
 exec "$@"
apps/kyb-app/src/main.tsx (1)

17-17: LGTM! Consider adding a comment

The config import is correctly set up for runtime configuration loading.

Consider adding a comment explaining the purpose of the ?url suffix:

+// Import runtime configuration using Vite's ?url suffix
import '../public/config.js?url';
apps/kyb-app/src/common/utils/request.ts (1)

6-7: Consider implementing a configuration service pattern.

While using globalThis.env works, consider implementing a more robust configuration service pattern that:

  1. Provides type safety
  2. Includes validation
  3. Centralizes configuration management
  4. Supports different environments

Example configuration service:

// config.service.ts
class ConfigService {
  private static instance: ConfigService;
  private config: Record<string, string>;

  private constructor() {
    this.config = {
      apiUrl: globalThis.env.VITE_API_URL,
      // other configs
    };
    this.validate();
  }

  static getInstance(): ConfigService {
    if (!ConfigService.instance) {
      ConfigService.instance = new ConfigService();
    }
    return ConfigService.instance;
  }

  private validate() {
    if (!this.config.apiUrl) {
      throw new Error('API URL is required');
    }
    // Add other validation
  }

  get apiUrl(): string {
    return this.config.apiUrl;
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ad69665 and e5c465e.

📒 Files selected for processing (7)
  • apps/kyb-app/Dockerfile (1 hunks)
  • apps/kyb-app/entrypoint.sh (1 hunks)
  • apps/kyb-app/global.d.ts (1 hunks)
  • apps/kyb-app/index.html (1 hunks)
  • apps/kyb-app/public/config.js (1 hunks)
  • apps/kyb-app/src/common/utils/request.ts (1 hunks)
  • apps/kyb-app/src/main.tsx (2 hunks)
🧰 Additional context used
🪛 Shellcheck
apps/kyb-app/entrypoint.sh

[warning] 3-3: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 8-8: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 13-13: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 19-19: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 24-24: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 29-29: In POSIX sh, [[ ]] is undefined.

(SC3010)

🪛 Biome
apps/kyb-app/src/main.tsx

[error] 16-16: Shouldn't redeclare 'initializeMonitoring'. Consider to delete it or rename it.

'initializeMonitoring' is defined here:

(lint/suspicious/noRedeclare)

🔇 Additional comments (8)
apps/kyb-app/public/config.js (1)

2-6: ⚠️ Potential issue

Runtime and security issues in configuration

  1. import.meta.env is not available at runtime in the browser. This configuration should be injected by the entrypoint.sh script instead.
  2. Default values for API URL and API key in public code pose security risks.

Apply this approach in the entrypoint script instead:

globalThis.env = {
  VITE_API_URL: '{{VITE_API_URL}}',
  VITE_KYB_DEFINITION_ID: '{{VITE_KYB_DEFINITION_ID}}',
  VITE_API_KEY: '{{VITE_API_KEY}}',
  VITE_ENVIRONMENT_NAME: '{{VITE_ENVIRONMENT_NAME}}',
  // ...
};
apps/kyb-app/index.html (1)

10-10: LGTM! Verify path resolution in production.

The absolute path /config.js is correct assuming both files are served from the same directory in the production build.

Let's verify the file locations in the production build:

✅ Verification successful

Path resolution is correct for production deployment

The verification confirms that the absolute path /config.js is correct because:

  • The entrypoint.sh script generates config.js at /usr/share/nginx/html/config.js
  • The production Dockerfile (FROM nginx:stable-alpine as prod) copies the built app to the same directory /usr/share/nginx/html
  • Both files are served from the same nginx root directory, making the absolute path /config.js resolve correctly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if config.js exists in the expected location relative to index.html
# Expected: Both files should be in the same directory in the production build

# Find the production build directory
fd -t f "index.html" dist

Length of output: 117


Script:

#!/bin/bash
# Let's check the build configuration and deployment setup to understand the file locations

# Check package.json for build configuration
fd -t f "package.json" apps/kyb-app --exec cat {}

# Check for any build or deployment scripts
fd -t f "entrypoint.sh|Dockerfile" apps/kyb-app --exec cat {}

# Look for vite.config or similar build configs
fd -t f "vite.config" apps/kyb-app --exec cat {}

Length of output: 6608

apps/kyb-app/Dockerfile (5)

12-12: LGTM: Build setup and PATH configuration

The build step is correctly placed after environment setup, and the PATH variable now uses an absolute path which is more reliable in a container context.

Also applies to: 15-15


23-24: LGTM: Consistent working directory

Setting WORKDIR to /app in production stage maintains consistency with development stage.


35-36: LGTM: Container initialization setup

The ENTRYPOINT and CMD configuration properly separates initialization (environment setup) from the main process (nginx).


27-28: Verify entrypoint.sh existence and permissions

The entrypoint script is crucial for environment configuration. Let's verify its presence and content.

#!/bin/bash
# Check if entrypoint.sh exists and contains necessary environment setup
if [ -f "apps/kyb-app/entrypoint.sh" ]; then
    echo "Entrypoint script found"
    cat "apps/kyb-app/entrypoint.sh"
else
    echo "Warning: entrypoint.sh not found in expected location"
fi

Also applies to: 31-32


19-19: Verify the security implications of --host flag

The --host flag typically allows external connections to the development server. While this might be necessary for container networking, ensure this is intentional and that appropriate network security measures are in place.

✅ Verification successful

Let me gather more information about the development server configuration and network settings.


Let me check the content of the Vite configuration file to understand the server settings.


Let me check if there are any Docker Compose or network configuration files that might provide additional context about the container's network security.


Based on the gathered information, I can now provide the final response:

The --host flag usage is appropriate in this Docker context

The --host flag is necessary here as it allows the Vite development server to accept connections from outside the container, which is required for Docker container networking. The security implications are mitigated by:

  • The server is configured to run on a specific port (5201) as seen in vite.config.ts
  • The container's network exposure is controlled by Docker's networking layer
  • Environment variables and configuration are properly managed through the entrypoint script
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any security measures in place (like reverse proxy configs or firewall rules)
rg -l "proxy_pass|location|allow|deny" example.nginx.conf

Length of output: 1004


Script:

#!/bin/bash
# Check Vite configuration and network settings
rg -l "server\s*:|host\s*:|port\s*:" apps/kyb-app/

Length of output: 197


Script:

#!/bin/bash
# Check the Vite configuration file content
cat apps/kyb-app/vite.config.ts

Length of output: 1929


Script:

#!/bin/bash
# Check for Docker Compose files and network configurations
fd -e yml -e yaml . apps/kyb-app/ | xargs cat

Length of output: 451

apps/kyb-app/src/common/utils/request.ts (1)

6-7: 🛠️ Refactor suggestion

Consider addressing type safety instead of using @ts-ignore.

The @ts-ignore comment suppresses TypeScript errors but doesn't address the underlying type safety concern. Consider properly typing the globalThis.env object to maintain type safety across the application.

Create a type declaration file (e.g., types/global.d.ts):

declare global {
  var env: {
    VITE_API_URL: string;
    // Add other environment variables as needed
  };
}

This will provide proper type checking and autocompletion for the global environment variables.

Let's verify the configuration setup:

✅ Verification successful

Using globalThis.env is the correct approach here

The verification shows that the codebase has a proper runtime configuration setup:

  1. The entrypoint.sh script creates a /usr/share/nginx/html/config.js file that correctly initializes globalThis.env with environment variables, including VITE_API_URL.
  2. This approach is part of a broader configuration strategy where runtime values are injected via the entrypoint script, allowing for dynamic configuration in containerized environments.
  3. The @ts-ignore is warranted here since the type information for the runtime-injected globalThis.env isn't available during build time.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the configuration setup for VITE_API_URL

# Test 1: Check if config.js exists and contains VITE_API_URL
echo "Checking for config.js file..."
fd -t f "config.js" -x cat {} \; | grep -A 1 "VITE_API_URL"

# Test 2: Check for other potential usages of VITE_API_URL
echo "Checking for other VITE_API_URL usages..."
rg "VITE_API_URL"

# Test 3: Check for entrypoint script that sets up the config
echo "Checking for entrypoint script..."
fd "entrypoint.sh" -x cat {}

Length of output: 6991

Comment on lines +1 to +3
declare global {
export var env: { [key: string]: any };
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving type safety and documentation

While the implementation works, there are several improvements that could make it more robust and maintainable:

  1. Replace any with a specific interface for environment variables
  2. Add readonly protection to prevent accidental mutations
  3. Include JSDoc documentation

Consider this improved implementation:

+/**
+ * Global environment configuration interface.
+ * Initialized at runtime via config.js and provides access to environment variables.
+ * @example
+ * // Access API URL
+ * globalThis.env.VITE_API_URL
+ */
 declare global {
-  export var env: { [key: string]: any };
+  export interface EnvConfig {
+    VITE_API_URL: string;
+    // Add other expected environment variables with their specific types
+  }
+  
+  export var env: Readonly<EnvConfig>;
 }

Committable suggestion skipped: line range outside the PR's diff.


💡 Codebase verification

Environment variable access patterns need standardization

The codebase shows inconsistent patterns for accessing environment variables:

  • process.env is used in vite.config.ts (4 occurrences)
  • import.meta.env is used extensively across the application (17 occurrences)
  • globalThis.env is used in a few places (4 occurrences)

Key issues:

  • The global declaration in global.d.ts suggests using globalThis.env, but most of the codebase uses import.meta.env
  • process.env usage in vite.config.ts is correct as it's a Node.js context
  • Environment variables are initialized in multiple places (entrypoint.sh, config.js, main.tsx)
🔗 Analysis chain

Verify environment variable usage across the application

Let's ensure all environment variable accesses are consistent with this global declaration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for environment variable access patterns
echo "Checking direct process.env usage (should be replaced with globalThis.env):"
rg "process\.env\." apps/kyb-app/

echo -e "\nChecking import.meta.env usage (should be used only during initialization):"
rg "import\.meta\.env" apps/kyb-app/

echo -e "\nChecking globalThis.env usage (preferred pattern):"
rg "globalThis\.env" apps/kyb-app/

Length of output: 3090

Comment on lines +7 to +8
VITE_DEFAULT_EXAMPLE_TOKEN:
import.meta.env.VITE_DEFAULT_EXAMPLE_TOKEN || '12345678-1234-1234-1234-123456789012',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove default authentication token

The default example token should not be included in the source code, even as a fallback. This could lead to unintended authentication if the environment variable is not properly set.

-  VITE_DEFAULT_EXAMPLE_TOKEN:
-    import.meta.env.VITE_DEFAULT_EXAMPLE_TOKEN || '12345678-1234-1234-1234-123456789012',
+  VITE_DEFAULT_EXAMPLE_TOKEN: '{{VITE_DEFAULT_EXAMPLE_TOKEN}}',

Committable suggestion skipped: line range outside the PR's diff.

@@ -7,6 +7,7 @@
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>KYB - Collection Flow</title>
<script type="text/javascript" src="/config.js"></script>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Security: Environment variables exposed in public config.js require attention

The following sensitive variables are being exposed in the publicly accessible config.js:

  • VITE_API_KEY: Default value "secret" is exposed and can be used for API access
  • VITE_SENTRY_AUTH_TOKEN: Though empty by default, exposing auth tokens is risky
  • VITE_DEFAULT_EXAMPLE_TOKEN: A static UUID token is exposed

Recommendations:

  • Move sensitive API keys and tokens to server-side only
  • Use session-based authentication instead of exposing API keys
  • If client-side config is needed, expose only public, non-sensitive variables
🔗 Analysis chain

Security: Review environment variable exposure.

Since config.js is publicly accessible and contains environment variables, ensure that no sensitive information (API keys, secrets, etc.) is exposed through globalThis.env.

Let's check what environment variables are being exposed:


Let me gather more specific information about the environment variables being exposed in the config.js file.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential sensitive environment variables in the configuration
# Expected: Only safe, public variables should be exposed

# Search for environment variable assignments in entrypoint.sh
rg -A 5 "globalThis.env = {" 

# Look for potentially sensitive patterns in environment variable names
rg -i "key|token|secret|password|credential" apps/kyb-app/

Length of output: 15749


Script:

#!/bin/bash
# Check the actual content of config.js to see what variables are exposed
cat apps/kyb-app/public/config.js

# Also check entrypoint.sh to see how the config is generated
cat apps/kyb-app/entrypoint.sh

Length of output: 1523

Comment on lines +8 to +11
if [[ -z "$VITE_API_KEY" ]]
then
VITE_API_KEY="secret"
fi
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security: Avoid hardcoding default API key

Using a hardcoded default API key ("secret") could be dangerous if accidentally used in non-local environments.

Consider:

  1. Making the API key required (fail if not provided)
  2. Or generating a random default value:
-    VITE_API_KEY="secret"
+    VITE_API_KEY=$(openssl rand -hex 16)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if [[ -z "$VITE_API_KEY" ]]
then
VITE_API_KEY="secret"
fi
if [[ -z "$VITE_API_KEY" ]]
then
VITE_API_KEY=$(openssl rand -hex 16)
fi
🧰 Tools
🪛 Shellcheck

[warning] 8-8: In POSIX sh, [[ ]] is undefined.

(SC3010)

Comment on lines +1 to +2
#!/usr/bin/env sh

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix shell compatibility issues

The script uses #!/usr/bin/env sh but contains bash-specific [[ syntax. This will fail in containers with only POSIX sh.

Either:

  1. Change the shebang to use bash:
-#!/usr/bin/env sh
+#!/usr/bin/env bash
  1. Or use POSIX-compatible syntax:
-if [[ -z "$VITE_DOMAIN" ]]
+if [ -z "$VITE_DOMAIN" ]

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +34 to +43
cat << EOF > /usr/share/nginx/html/config.js
globalThis.env = {
VITE_API_URL: "$VITE_DOMAIN/api/v1/",
VITE_API_KEY: "$VITE_API_KEY",
VITE_ENVIRONMENT_NAME: "$VITE_ENVIRONMENT_NAME",
VITE_DEFAULT_EXAMPLE_TOKEN: "$VITE_DEFAULT_EXAMPLE_TOKEN",
VITE_SENTRY_AUTH_TOKEN: "$VITE_SENTRY_AUTH_TOKEN",
VITE_SENTRY_DSN: "$VITE_SENTRY_DSN",
}
EOF
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security: Reconsider config file location and format

Writing configuration with sensitive values to /usr/share/nginx/html/ makes it publicly accessible through the web server.

Consider:

  1. Moving config to a non-public directory and importing it server-side
  2. Using environment variables directly in your application
  3. If client-side config is necessary, exclude sensitive values and add security headers:
 cat << EOF > /usr/share/nginx/html/config.js
 globalThis.env = {
   VITE_API_URL: "$VITE_DOMAIN/api/v1/",
-  VITE_API_KEY: "$VITE_API_KEY",
   VITE_ENVIRONMENT_NAME: "$VITE_ENVIRONMENT_NAME",
-  VITE_DEFAULT_EXAMPLE_TOKEN: "$VITE_DEFAULT_EXAMPLE_TOKEN",
-  VITE_SENTRY_AUTH_TOKEN: "$VITE_SENTRY_AUTH_TOKEN",
   VITE_SENTRY_DSN: "$VITE_SENTRY_DSN",
 }
 EOF
+
+# Add security headers to nginx config
+cat << EOF > /etc/nginx/conf.d/security-headers.conf
+add_header Content-Security-Policy "default-src 'self';" always;
+add_header X-Content-Type-Options "nosniff" always;
+EOF

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +3 to +32
if [[ -z "$VITE_DOMAIN" ]]
then
VITE_DOMAIN="http://localhost:3000"
fi

if [[ -z "$VITE_API_KEY" ]]
then
VITE_API_KEY="secret"
fi

if [[ -z "$VITE_ENVIRONMENT_NAME" ]]
then
VITE_ENVIRONMENT_NAME=local
fi


if [[ -z "$VITE_DEFAULT_EXAMPLE_TOKEN" ]]
then
VITE_DEFAULT_EXAMPLE_TOKEN=12345678-1234-1234-1234-123456789012
fi

if [[ -z "$VITE_SENTRY_AUTH_TOKEN" ]]
then
VITE_SENTRY_AUTH_TOKEN=""
fi

if [[ -z "$VITE_SENTRY_DSN" ]]
then
VITE_SENTRY_DSN=""
fi
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation and logging for environment variables

The script silently falls back to defaults without any validation or logging, which could mask configuration issues.

Consider adding:

  1. Validation for provided values
  2. Logging of which defaults are being used
+log_default() {
+    echo "Warning: $1 not set, using default value: $2"
+}

 if [ -z "$VITE_DOMAIN" ]
 then
+    log_default "VITE_DOMAIN" "http://localhost:3000"
     VITE_DOMAIN="http://localhost:3000"
+elif ! echo "$VITE_DOMAIN" | grep -qE '^https?://'
+then
+    echo "Error: VITE_DOMAIN must start with http:// or https://"
+    exit 1
 fi

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Shellcheck

[warning] 3-3: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 8-8: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 13-13: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 19-19: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 24-24: In POSIX sh, [[ ]] is undefined.

(SC3010)


[warning] 29-29: In POSIX sh, [[ ]] is undefined.

(SC3010)

@@ -13,6 +13,8 @@ import { App } from './App';
import { Head } from './Head';
import './i18next';
import './index.css';
import { initializeMonitoring } from '@/initialize-monitoring/initialize-monitoring';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove duplicate import of initializeMonitoring

The initializeMonitoring module is already imported on line 5, making this import redundant.

-import { initializeMonitoring } from '@/initialize-monitoring/initialize-monitoring';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { initializeMonitoring } from '@/initialize-monitoring/initialize-monitoring';
🧰 Tools
🪛 Biome

[error] 16-16: Shouldn't redeclare 'initializeMonitoring'. Consider to delete it or rename it.

'initializeMonitoring' is defined here:

(lint/suspicious/noRedeclare)

Comment on lines 44 to 47
//@ts-ignore
globalThis.env = globalThis.env || {
API_URL: import.meta.env.VITE_API_URL,
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve type safety and environment variable handling

The current implementation has several issues:

  1. Using @ts-ignore masks potential type errors
  2. No validation of required environment variables
  3. Lacks proper TypeScript declarations

Consider this type-safe alternative:

-//@ts-ignore
-globalThis.env = globalThis.env || {
-  API_URL: import.meta.env.VITE_API_URL,
-};
+interface AppConfig {
+  API_URL: string;
+}
+
+declare global {
+  var env: AppConfig;
+}
+
+if (!import.meta.env.VITE_API_URL) {
+  throw new Error('VITE_API_URL environment variable is required');
+}
+
+globalThis.env = {
+  API_URL: import.meta.env.VITE_API_URL,
+};

This approach:

  • Adds proper TypeScript declarations
  • Validates required environment variables
  • Maintains type safety without ignoring TypeScript checks
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//@ts-ignore
globalThis.env = globalThis.env || {
API_URL: import.meta.env.VITE_API_URL,
};
interface AppConfig {
API_URL: string;
}
declare global {
var env: AppConfig;
}
if (!import.meta.env.VITE_API_URL) {
throw new Error('VITE_API_URL environment variable is required');
}
globalThis.env = {
API_URL: import.meta.env.VITE_API_URL,
};

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