Skip to content

feat(image): [image] The image component supports base64 in svg format #2858

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 1 commit into from
Feb 7, 2025

Conversation

zzcr
Copy link
Member

@zzcr zzcr commented Feb 6, 2025

PR

feat: image组件支持svg格式的base64

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features
    • Enhanced image support now accepts base64‑encoded SVG images in addition to PNG, JPEG, and GIF formats.
    • Users will benefit from improved vector image rendering, ensuring better display quality and compatibility.
    • This update contributes to a smoother visual experience when utilizing inline images, fostering greater flexibility in image usage.

Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

This change updates the regular expression in the filterImageUrl function located in the image module. The regex now accepts SVG images encoded in base64 by including the svg+xml MIME type alongside the previously supported types. No other parts of the code or public API declarations have been altered.

Changes

File Change Summary
packages/.../image/index.ts Updated the regex pattern in filterImageUrl to include the svg+xml MIME type.

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • kagol

Poem

I’m a bunny with a code delight,
Tweaking regex in the soft moonlight.
SVGs now hop into our view,
Base64 images shining anew.
With every change, our app feels so bright!
🐰💻✨

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between eca3888 and 7cfc224.

📒 Files selected for processing (1)
  • packages/renderless/src/image/index.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: PR E2E Test (pnpm test:e2e3)
🔇 Additional comments (2)
packages/renderless/src/image/index.ts (2)

187-191: Add tests for SVG base64 support.

Please add test cases to verify:

  1. Valid SVG base64 URLs are accepted
  2. Invalid SVG base64 URLs are rejected
  3. XSS filtering is applied to non-base64 SVG URLs

Would you like me to help generate test cases for the SVG base64 support?


187-191: LGTM! Implementation securely handles SVG base64 support.

The regex pattern correctly validates base64-encoded SVG images while maintaining XSS protection for non-base64 URLs.

Since SVGs can contain executable content, please verify that the image component renders SVGs safely by searching the web:

✅ Verification successful

🌐 Web query:

How to safely render SVG images in Vue.js to prevent XSS?

💡 Result:



To safely render SVG images in Vue.js and prevent XSS vulnerabilities, implement these security measures:

### 1. **Avoid Unsafe Directives**
- **Never use `v-html`** for untrusted SVG content ([2][7]). This directive bypasses Vue’s default HTML escaping:
  ```vue
  <!-- Dangerous: Avoid with untrusted sources -->
  <div v-html="userProvidedSvg"></div>
  ```

### 2. **Use Safe Embedding Methods**
- **Render via `<img>` tags** when possible – browsers block script execution in SVGs loaded this way ([6]):
  ```vue
  <img :src="sanitizedSvgUrl" alt="Safe SVG">
  ```
- **Avoid direct DOM insertion** via `innerHTML` or similar methods ([2][7]).

### 3. **Sanitize SVG Content**
- Use libraries like **DOMPurify** ([5]) or **sanitize-html** ([2][4]) to remove malicious elements/attributes:
  ```javascript
  import DOMPurify from 'dompurify';
  
  const cleanSVG = DOMPurify.sanitize(untrustedSVG, {
    USE_PROFILES: { svg: true },
    ADD_TAGS: ['svg', 'path'], // Allowlist safe tags
    ADD_ATTR: ['viewBox', 'd'] // Allowlist safe attributes
  });
  ```

### 4. **Apply Content Security Policy (CSP)**
- Add headers to block inline scripts and external resources:
  ```http
  Content-Security-Policy: default-src 'self'; script-src 'none'
  ```
  This neutralizes embedded `<script>` tags in SVGs ([3][4][6]).

### 5. **Encode Untrusted Data**
- Use Vue’s built-in text interpolation (`{{ }}`) for non-HTML content ([2][7]):
  ```vue
  <span>{{ userProvidedText }}</span>
  ```

### 6. **Sandbox Risky Content**
- Use sandboxed iframes for untrusted SVG rendering:
  ```vue
  <iframe :src="sanitizedSvgUrl" sandbox="allow-same-origin"></iframe>
  ```
  The `sandbox` attribute blocks script execution ([3][6]).

---

### Key Risks to Mitigate
| Attack Vector          | Mitigation Strategy                          |
|------------------------|----------------------------------------------|
| Embedded `<script>`     | Sanitization + CSP headers ([3][4][6])       |
| Event handlers (e.g., `onload`) | Sanitize attributes + avoid `v-html` ([1][2]) |
| Mutation XSS           | Avoid legacy jQuery/VueJS mixing ([1])      |

For high-security applications, consider converting user-uploaded SVGs to raster formats (PNG/JPG) before rendering ([4]). Always validate and sanitize inputs at both client and server levels ([10]).

Citations:

- 1: https://portswigger.net/research/evading-defences-using-vuejs-script-gadgets
- 2: https://dev-academy.com/vue-xss/
- 3: https://digi.ninja/blog/svg_xss.php
- 4: https://hackernoon.com/the-dangers-of-svg-files-a-lesser-known-vector-for-xss-attacks
- 5: https://github.com/cure53/DOMPurify/commits?after=7cf4890aea9e93b4e467b5f81a3f2292b2837eb7+34
- 6: https://dev.to/js_bits_bill/how-svgs-can-be-dangerous-js-bits-mjh
- 7: https://vuejs.org/guide/best-practices/security
- 8: https://js.devexpress.com/Vue/Documentation/Guide/Common/Security_Considerations/
- 9: https://dev.to/vinibrsl/a-lesser-known-vector-for-xss-attacks-svg-files-5hm5?comments_sort=top
- 10: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

LGTM: The regex update securely adds support for base64-encoded SVG images.

  • The updated pattern now matches the svg+xml MIME type, ensuring that valid base64-encoded SVGs pass through unmodified.
  • Non-base64 URLs are still sanitized via xss.filterUrl, maintaining robust XSS protection.
  • The web guidelines confirm that safely rendering SVGs in Vue typically involves using <img> tags with sanitized URLs, a practice consistent with this implementation.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@github-actions github-actions bot added the enhancement New feature or request (功能增强) label Feb 6, 2025
Copy link

Walkthrough

This PR enhances the image component by adding support for base64 encoded SVG format. It modifies the regular expression used to detect base64 image formats, allowing SVG images to be recognized and processed correctly.

Changes

File Summary
packages/renderless/src/image/index.ts Updated the regular expression in filterImageUrl function to include svg+xml in the list of supported base64 image types.

@@ -185,7 +185,7 @@ export const mounted =
}

export const filterImageUrl = (props) => () => {
const isBase64 = /^data:(image|application)\/(png|jpg|jpeg|gif|octet-stream);base64,([a-zA-Z0-9+/]+={0,2})/
const isBase64 = /^data:(image|application)\/(png|jpg|jpeg|gif|octet-stream|svg\+xml);base64,([a-zA-Z0-9+/]+={0,2})/

Choose a reason for hiding this comment

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

The regular expression has been updated to include svg+xml in the list of supported base64 image types. This change allows the component to correctly identify and process base64 encoded SVG images.

@zzcr zzcr merged commit a7e721e into dev Feb 7, 2025
10 of 11 checks passed
@kagol kagol deleted the support-svg-base64-0206 branch April 14, 2025 12:20
@coderabbitai coderabbitai bot mentioned this pull request Apr 15, 2025
13 tasks
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
enhancement New feature or request (功能增强)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant