Skip to content

Features/add js interpreter #355

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

Merged
merged 14 commits into from
Aug 6, 2025
Merged

Conversation

iceljc
Copy link
Collaborator

@iceljc iceljc commented Jul 1, 2025

PR Type

Enhancement


Description

  • Add JavaScript interpreter component for executing code in chat

  • Refine scrollbar ID generation and markdown styling

  • Add program code rich type support

  • Improve script loading with multiple source handling


Diagram Walkthrough

flowchart LR
  A["Chat Message"] --> B["Rich Content Check"]
  B --> C["JavaScript Code?"]
  C -->|Yes| D["JS Interpreter Component"]
  C -->|No| E["Standard Markdown"]
  D --> F["Parse & Execute Code"]
  F --> G["Load External Scripts"]
  G --> H["Render Chart/Output"]
Loading

File Walkthrough

Relevant files
Enhancement
Markdown.svelte
Improve scrollbar ID handling                                                       

src/lib/common/markdown/Markdown.svelte

  • Refine scrollbar ID generation with descriptive prefix
  • Update element selector to use new ID format
+3/-4     
rc-js-interpreter.svelte
Add JavaScript interpreter component                                         

src/routes/chat/[agentId]/[conversationId]/rich-content/rc-js-interpreter.svelte

  • Create new JavaScript interpreter component
  • Add script loading with external source support
  • Implement code parsing and execution functionality
  • Add chart rendering container with scrollable support
+105/-0 
rc-message.svelte
Integrate JS interpreter in messages                                         

src/routes/chat/[agentId]/[conversationId]/rich-content/rc-message.svelte

  • Add conditional rendering for JavaScript code messages
  • Import and integrate JS interpreter component
  • Check for program code rich type and JavaScript language
+9/-2     
rich-content.svelte
Refactor conditional rendering logic                                         

src/routes/chat/[agentId]/[conversationId]/rich-content/rich-content.svelte

  • Refactor conditional rendering structure
  • Replace separate if blocks with if-else pattern
+3/-3     
enums.js
Add program code rich type                                                             

src/lib/helpers/enums.js

  • Add ProgramCode enum value to RichType
+2/-1     
http.js
Update markdown replacement pattern                                           

src/lib/helpers/http.js

  • Modify markdown replacement pattern for horizontal rules
  • Change replacement from empty string to @@@
+1/-1     
conversationTypes.js
Add language property to rich content                                       

src/lib/helpers/types/conversationTypes.js

  • Add language property to IRichContent prototype
  • Document language field for code rich content
+10/-0   

Copy link

qodo-merge-pro bot commented Jul 1, 2025

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 Security concerns

Code injection vulnerability:
The component uses eval() to execute JavaScript code extracted from chat messages without any validation, sanitization, or sandboxing. This creates a critical security vulnerability where malicious actors could execute arbitrary JavaScript code in the user's browser, potentially accessing sensitive data, making unauthorized requests, or performing other malicious actions. The regex-based code extraction from markdown also lacks proper validation and could be bypassed.

⚡ Recommended focus areas for review

Security Risk

The use of eval() to execute arbitrary JavaScript code from chat messages poses a significant security vulnerability. This allows execution of potentially malicious code without any validation or sandboxing.

    eval(code);
}
Error Handling

The code extraction and execution logic lacks proper error handling. If the regex fails or eval() throws an exception, it could crash the component or expose sensitive error information.

function initCode() {
    const text = message?.rich_content?.message?.text || message?.text || '';
    const parsedText = marked.lexer(text);
    // @ts-ignore
    const codeText = parsedText.find(token => token.type === 'code' || token.type === 'html')?.text || '';
    const code = codeText.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/i, '$1');
    eval(code);
}
Resource Management

The scrollbar initialization and DOM manipulation could lead to memory leaks if the component is destroyed without proper cleanup. No cleanup logic is provided in onDestroy.

    function initScrollbar() {
        const elem = document.querySelector(`#js-interpreter-scrollbar-${scrollbarId}`);
		if (elem) {
			// @ts-ignore
			const scrollbar = OverlayScrollbars(elem, options);
		}
    }

@iceljc iceljc marked this pull request as draft July 1, 2025 04:11
Copy link

qodo-merge-pro bot commented Jul 1, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Security
Replace eval with secure execution

Using eval() to execute arbitrary JavaScript code poses a critical security
vulnerability. Malicious code could be executed, leading to XSS attacks or data
theft. Consider using a sandboxed JavaScript execution environment or a safer
alternative like a restricted code parser.

src/routes/chat/[agentId]/[conversationId]/rich-content/rc-js-interpreter.svelte [43-50]

 function initCode() {
     const text = message?.rich_content?.message?.text || message?.text || '';
     const parsedText = marked.lexer(text);
     // @ts-ignore
     const codeText = parsedText.find(token => token.type === 'code' || token.type === 'html')?.text || '';
     const code = codeText.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/i, '$1');
-    eval(code);
+    
+    // TODO: Replace eval with a secure code execution method
+    // Consider using a sandboxed environment or code validation
+    try {
+        // Validate code before execution
+        if (isValidChartCode(code)) {
+            eval(code);
+        }
+    } catch (error) {
+        console.error('Code execution failed:', error);
+    }
 }
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: The suggestion correctly identifies a critical security vulnerability by flagging the use of eval() on user-provided content, which could lead to XSS attacks.

High
  • More

@iceljc iceljc marked this pull request as ready for review August 6, 2025 15:23
Copy link

qodo-merge-pro bot commented Aug 6, 2025

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 Security concerns

Code injection vulnerability:
The JavaScript interpreter component uses eval() to execute arbitrary code from chat messages without any sanitization or sandboxing. This creates a severe security risk as malicious users could execute arbitrary JavaScript code in the browser context, potentially accessing sensitive data, manipulating the DOM, or performing other malicious actions. The component also loads external scripts dynamically based on message content, which could be exploited to load malicious scripts from untrusted sources.

⚡ Recommended focus areas for review

Security Risk

The component uses eval() to execute arbitrary JavaScript code from chat messages, which poses significant security risks including XSS attacks and code injection vulnerabilities.

    Promise.all(promises).then(() => setTimeout(() => eval(code), 0));
} else {
    setTimeout(() => eval(code), 0);
Script Management

The script loading mechanism removes existing scripts with the same src and reloads them, which could cause memory leaks or unexpected behavior with global state.

const curScripts = document.head.getElementsByTagName("script");
const found = Array.from(curScripts).find(x => x.src === src);
if (found) {
    found.remove();
}
Error Handling

Script loading errors are only logged to console but don't prevent code execution, potentially causing runtime errors when dependencies are missing.

script.onerror = () => {
    setTimeout(() => {
        console.log(`Error when loading script: ${src}`);
        resolve(false);
    }, 0);
}

Copy link

qodo-merge-pro bot commented Aug 6, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Security
Replace eval with safer execution

Using eval() to execute arbitrary code poses significant security risks.
Consider implementing a sandboxed JavaScript execution environment or using a
safer alternative like a restricted parser for specific use cases.

src/routes/chat/[agentId]/[conversationId]/rich-content/rc-js-interpreter.svelte [65]

-setTimeout(() => eval(code), 0);
+// Consider using a sandboxed execution environment
+// or implement proper code validation before execution
+setTimeout(() => {
+    try {
+        // Add validation and sandboxing here
+        new Function(code)();
+    } catch (error) {
+        console.error('Code execution error:', error);
+    }
+}, 0);
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: The suggestion correctly identifies a critical security vulnerability by pointing out the use of eval() on potentially untrusted code, which could lead to severe exploits.

High
General
Avoid removing existing scripts

Removing existing scripts before loading new ones could break functionality if
other components depend on those scripts. Consider checking if the script is
already loaded instead of removing it.

src/routes/chat/[agentId]/[conversationId]/rich-content/rc-js-interpreter.svelte [73-76]

 const found = Array.from(curScripts).find(x => x.src === src);
 if (found) {
-    found.remove();
+    // Script already loaded, resolve immediately
+    resolve(true);
+    return;
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a flawed logic that could break other components by removing a shared script, proposing a much safer and more efficient approach.

Medium
Possible issue
Add proper property validation

The code assumes all filtered objects have a text property, but the filter only
checks for truthiness. This could cause runtime errors if objects exist but
don't have the expected structure.

src/routes/chat/[agentId]/[conversationId]/rich-content/rc-js-interpreter.svelte [48]

-const codeText = parsedText.filter(x => !!x.text).map(x => x.text).join('');
+const codeText = parsedText.filter(x => x && typeof x.text === 'string').map(x => x.text).join('');
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion improves code robustness by adding a more explicit check for the existence and type of the text property, preventing potential runtime errors if the data structure is not as expected.

Low
  • More

@iceljc iceljc merged commit e75b2c6 into SciSharp:main Aug 6, 2025
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant