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: weglot impl #158

Merged
merged 2 commits into from
Feb 19, 2025
Merged

feat: weglot impl #158

merged 2 commits into from
Feb 19, 2025

Conversation

bitfalt
Copy link
Member

@bitfalt bitfalt commented Feb 19, 2025

  • Add WeglotProvider to initialize Weglot for the whole app

Summary by CodeRabbit

  • New Features
    • Integrated a new translation provider that enhances multilingual support by automatically loading language-related scripts when properly configured, ensuring a smoother experience for users accessing multiple languages.

Copy link

vercel bot commented Feb 19, 2025

@bitfalt is attempting to deploy a commit to the MindVault Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

The changes reorganize the provider hierarchy in the root layout by introducing a new WeglotProvider. In the updated structure, WeglotProvider now wraps the existing ThemeProvider, NotificationsProvider, and ErudaProvider. Additionally, a new component is added to conditionally load the Weglot JavaScript library based on an environment variable, ensuring the script and its initialization only run when the API key is present.

Changes

File Change Summary
apps/web/.../layout.tsx Wrapped existing providers (ThemeProvider, NotificationsProvider, ErudaProvider) with the new WeglotProvider in the RootLayout function.
apps/web/.../WeglotProvider.tsx Added a new WeglotProvider component that conditionally loads Weglot scripts using the API key; logs a warning when the key is missing, and passes through its children unmodified.

Sequence Diagram(s)

sequenceDiagram
    participant RL as RootLayout
    participant WP as WeglotProvider
    participant TP as ThemeProvider
    participant NP as NotificationsProvider
    participant EP as ErudaProvider
    participant DS as Weglot Script Loader

    RL->>WP: Render RootLayout
    WP->>WP: Check for API key
    alt API key present
        WP->>DS: Load Weglot Library (Script 1)
        WP->>DS: Initialize Weglot with API key (Script 2)
    else API key absent
        WP->>Console: Log warning
    end
    WP->>TP: Render ThemeProvider
    TP->>NP: Render NotificationsProvider
    NP->>EP: Render ErudaProvider
    EP->>RL: Render LayoutContent with children
Loading

Possibly related PRs

Poem

I'm a rabbit with a joyful beat,
Hopping through code with nimble feet.
Now Weglot loads with flair and might,
Nested providers take flight.
Cheering changes, day and night!
🐇✨


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Feb 19, 2025

Deploy Preview for lucent-florentine-971919 ready!

Name Link
🔨 Latest commit 0edaf24
🔍 Latest deploy log https://app.netlify.com/sites/lucent-florentine-971919/deploys/67b6302c544ab000089540c8
😎 Deploy Preview https://deploy-preview-158--lucent-florentine-971919.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

vercel bot commented Feb 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
miniapp-monorepo-web ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 19, 2025 7:27pm

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

🧹 Nitpick comments (3)
apps/web/src/providers/WeglotProvider.tsx (2)

6-8: Consider adding configuration props for Weglot initialization.

The component could be more flexible by accepting additional configuration options such as languages, defaultLanguage, etc., instead of only using the API key.

 interface WeglotProviderProps {
   children: ReactNode
+  languages?: string[]
+  defaultLanguage?: string
+  // Add other Weglot configuration options as needed
 }

11-14: Enhance error handling and logging.

Consider using a more robust error handling approach:

  1. Log additional context about the environment
  2. Consider throwing an error in development mode
   if (!process.env.NEXT_PUBLIC_WEGLOT_API_KEY) {
-    console.warn('Missing NEXT_PUBLIC_WEGLOT_API_KEY environment variable')
+    const message = 'Missing NEXT_PUBLIC_WEGLOT_API_KEY environment variable'
+    console.warn(message, {
+      environment: process.env.NODE_ENV,
+      context: 'WeglotProvider initialization'
+    })
+    if (process.env.NODE_ENV === 'development') {
+      throw new Error(message)
+    }
     return <>{children}</>
   }
apps/web/src/app/layout.tsx (1)

43-57: Fix indentation in provider hierarchy.

The indentation of the providers is inconsistent. The MiniKitProvider is not properly aligned with its siblings.

         <WeglotProvider>
           <ThemeProvider>
             <NotificationsProvider>
               <ErudaProvider>
-              <MiniKitProvider>
+                <MiniKitProvider>
                   <div className="mx-auto w-full min-h-screen overflow-hidden">
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00d6f50 and 0edaf24.

📒 Files selected for processing (2)
  • apps/web/src/app/layout.tsx (3 hunks)
  • apps/web/src/providers/WeglotProvider.tsx (1 hunks)
🔇 Additional comments (1)
apps/web/src/app/layout.tsx (1)

43-57:

❓ Verification inconclusive

Verify provider ordering impact.

The WeglotProvider is now wrapping all other providers. Verify that this ordering doesn't affect:

  1. Theme switching functionality
  2. Notification system
  3. Development tools (Eruda)

🏁 Script executed:

#!/bin/bash
# Search for any theme, notification, or Eruda initialization that might depend on DOM elements
rg -A 5 "initialize|init|setup" --type ts --type tsx

Length of output: 82


Action Required: Verify Provider Ordering Impact

We need to ensure that wrapping all providers with the WeglotProvider does not inadvertently affect:

  • Theme Switching: Confirm that the ThemeProvider still applies themes correctly.
  • Notification System: Ensure that NotificationsProvider functions as expected.
  • Development Tools (Eruda): Verify that ErudaProvider initializes without issues.

Note: The earlier search command using --type tsx failed due to an unrecognized file type. To improve verification, please run the following shell script to search both .ts and .tsx files:

#!/bin/bash
# Re-run search using custom glob patterns for both .ts and .tsx files
rg -g '*.ts' -g '*.tsx' -A 5 "initialize|init|setup"

Review any findings manually to confirm that none of the provider-related initialization routines (or DOM-dependent setups) rely on the previous provider ordering.

Comment on lines +18 to +23
<Script
id="weglot-js"
src="https://cdn.weglot.com/weglot.min.js"
strategy="beforeInteractive"
/>
<Script
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 using onError handler for script loading failures.

Add error handling to detect and handle script loading failures.

       <Script
         id="weglot-js"
         src="https://cdn.weglot.com/weglot.min.js"
         strategy="beforeInteractive"
+        onError={(e) => {
+          console.error('Failed to load Weglot script:', e)
+        }}
       />
📝 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
<Script
id="weglot-js"
src="https://cdn.weglot.com/weglot.min.js"
strategy="beforeInteractive"
/>
<Script
<Script
id="weglot-js"
src="https://cdn.weglot.com/weglot.min.js"
strategy="beforeInteractive"
onError={(e) => {
console.error('Failed to load Weglot script:', e)
}}
/>
<Script

Comment on lines +23 to +33
<Script
id="weglot-init"
strategy="beforeInteractive"
dangerouslySetInnerHTML={{
__html: `
Weglot.initialize({
api_key: "${process.env.NEXT_PUBLIC_WEGLOT_API_KEY}",
});
`
}}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

⚠️ Potential issue

🧩 Analysis chain

Security concern: API key exposure in client-side code.

The API key is currently exposed in the client-side JavaScript. Consider:

  1. Using a backend proxy to initialize Weglot
  2. Implementing proper CSP headers

Let's verify if the API key needs to be protected:


🌐 Web query:

Does Weglot API key need to be protected or is it safe to expose in client-side code?

💡 Result:

Weglot API keys should not be exposed in client-side code and require protection despite some conflicting information from different sources[1][3][5][6]. Here's the breakdown:

Key Security Considerations

  1. Public vs Secret Keys

    • Weglot uses public API keys for frontend integration[1][10], but these still require domain whitelisting via their support team[1].
    • Unlike Zoom's public-facing JWT keys[3], Weglot keys grant translation management access and aren't inherently safe for full exposure.
  2. Documentation vs Reality

    • While Weglot's API examples show direct key usage[4][10], security researchers have flagged exposed keys as vulnerabilities[5].
    • General security guidelines strongly advise against client-side exposure of any credentials[2][6].
  3. Proven Risks

    • Exposed keys allow:
      ▸ Unauthorized translation modifications
      ▸ Access to translation memory/analytics[1]
      ▸ Potential billing abuse through API overuse

Recommended Protection Methods

Approach Implementation Security Benefit
Backend Proxy Route requests through services like Buildship/Supabase[5][6] Full key isolation
Domain Whitelisting Contact Weglot support to restrict authorized domains[1] Prevents external misuse
Environment Variables Store keys server-side (never in frontend code)[2][6] Avoids accidental exposure

When Client-Side Use Might Seem Acceptable

// Example from Weglot documentation[10]:
fetch('https://api.weglot.com/translate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    api_key: 'PUBLIC_KEY_HERE', // Still requires whitelisting
    l_from: 'en',
    l_to: 'fr',
    words: [{w: 'Hello'}]
  })
})

This only works safely if:

  1. Domain is whitelisted with Weglot[1]
  2. Key has strict rate limits[2]
  3. No sensitive translation data exists[1]

Best Practice Summary

  • Never hardcode keys in frontend repositories[2][5]
  • Use backend middleware for all API interactions[5][6]
  • Regularly rotate keys and monitor usage[2][10]
  • Whitelist domains/IPs through Weglot support[1]

While Weglot's implementation might appear client-friendly initially[10], responsible security practices demand treating these keys as sensitive credentials requiring protection[2][5][6].

Citations:


Security Alert: Exposed Weglot API Key in Client-Side Code

After reviewing the latest guidance on Weglot API key security, it’s clear that even though Weglot documentation shows direct client-side usage, exposing the key through process.env.NEXT_PUBLIC_WEGLOT_API_KEY can still lead to unauthorized translation modifications, potential abuse of analytics, and billing risks. To mitigate these risks, please consider the following improvements:

  • Implement a Backend Proxy: Move the Weglot initialization logic to a secure backend endpoint to shield the API key.
  • Enhance Security Measures: Along with domain whitelisting (by coordinating with Weglot support), enforce strict Content Security Policy (CSP) headers to further protect against misuse.

File: apps/web/src/providers/WeglotProvider.tsx (Lines: 23-33)

Please update this implementation to prevent exposing sensitive credentials on the client side.

@bitfalt bitfalt merged commit 0f43d17 into MindVault-Inc:main Feb 19, 2025
8 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant