Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@TWilson023
Copy link
Collaborator

@TWilson023 TWilson023 commented Jun 23, 2025

Summary by CodeRabbit

  • New Features

    • Added support for uploading and validating SVG images in addition to existing image formats.
    • Improved validation for image URLs to ensure they meet specific requirements.
  • Refactor

    • Enhanced image validation logic for better modularity and normalization.

@TWilson023 TWilson023 requested a review from steven-tey June 23, 2025 22:42
@vercel
Copy link
Contributor

vercel bot commented Jun 23, 2025

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

Name Status Preview Updated (UTC)
dub 🔄 Building (Inspect) Visit Preview Jun 23, 2025 10:42pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

Walkthrough

The changes expand image validation logic to support SVG images in addition to existing raster formats. New schemas are introduced to modularize base64 and URL validation, and the image validation in program resource logic is updated to allow SVG images. No control flow or public API signatures are altered.

Changes

File(s) Change Summary
apps/web/lib/zod/schemas/misc.ts Added schemas for base64 SVG images, modularized URL validation, and updated image validation to allow SVG.
apps/web/lib/actions/partners/program-resources/add-program-resource.ts Updated import and usage to use the new image schema that allows SVG images.

Poem

In the warren of code, a new path we pave,
SVGs now welcome, let images behave!
With schemas refined and URLs checked twice,
Our resources grow nimble, our logic precise.
🐇✨
Hooray for the formats, both raster and vector—
The code hops ahead, ever the connector!

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

🔭 Outside diff range comments (1)
apps/web/lib/actions/partners/program-resources/add-program-resource.ts (1)

108-112: Fix file size calculation logic for URL inputs.

The current logic assumes the file input is always a base64 string, but uploadedImageAllowSVGSchema also accepts URLs. This will cause errors when a URL is provided.

Apply this fix to handle both base64 and URL inputs:

-      // Extract file size from base64 string
-      const base64Data = file.replace(/^data:.+;base64,/, "");
-      const fileSize = Math.ceil((base64Data.length * 3) / 4);
+      // Calculate file size based on input type
+      let fileSize: number;
+      
+      if (file.startsWith('data:')) {
+        // Extract file size from base64 string
+        const base64Data = file.replace(/^data:.+;base64,/, "");
+        fileSize = Math.ceil((base64Data.length * 3) / 4);
+      } else {
+        // For URL inputs, we can't determine size here
+        // Consider fetching the file or using a default size validation
+        fileSize = 0; // or implement actual size fetching
+      }

       if (fileSize / 1024 / 1024 > 10)
         throw new Error("File size is too large");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d91dfd7 and 4803c40.

📒 Files selected for processing (2)
  • apps/web/lib/actions/partners/program-resources/add-program-resource.ts (2 hunks)
  • apps/web/lib/zod/schemas/misc.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/web/lib/actions/partners/program-resources/add-program-resource.ts (1)
apps/web/lib/zod/schemas/misc.ts (1)
  • uploadedImageAllowSVGSchema (121-123)
apps/web/lib/zod/schemas/misc.ts (1)
packages/utils/src/constants/main.ts (1)
  • R2_URL (77-77)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (6)
apps/web/lib/zod/schemas/misc.ts (3)

103-109: Good modularization of URL validation logic.

The extraction of URL validation into a separate uploadedImageUrlSchema improves code reusability and maintainability.


115-116: Good refactoring to use the modularized URL schema.

The update to use uploadedImageUrlSchema maintains consistency and leverages the new modular approach.


121-123: ```shell
#!/bin/bash

Check for parse/parseAsync usage of the resource schema in add-program-resource.ts

echo "Looking for logoResourceSchema.parse or parseAsync calls..."
rg -n "logoResourceSchema.(parse|parseAsync)" -C2 apps/web/lib/actions/partners/program-resources/add-program-resource.ts

echo -e "\nLooking for any .parse or .parseAsync invocations in this file..."
rg -n ".parseAsync(" -C2 apps/web/lib/actions/partners/program-resources/add-program-resource.ts
rg -n ".parse(" -C2 apps/web/lib/actions/partners/program-resources/add-program-resource.ts


</details>
<details>
<summary>apps/web/lib/actions/partners/program-resources/add-program-resource.ts (3)</summary>

`6-6`: **Good update to support SVG images in program resources.**

The import change aligns with the PR objective to fix program resource logo SVGs.

---

`26-26`: **Schema usage updated correctly.**

The `logoResourceSchema` now uses the SVG-supporting schema as intended.

---

`114-114`: To confirm whether we need to switch to `parseAsync`, let’s pull in the surrounding context and schema definition:


```shell
#!/bin/bash

echo "1) Locate the parse call:"
rg -n "programResourceFileSchema\.parse" apps/web/lib/actions/partners/program-resources/add-program-resource.ts

echo -e "\n2) Show lines 100–130 around that usage:"
sed -n '100,130p' apps/web/lib/actions/partners/program-resources/add-program-resource.ts

echo -e "\n3) Find the import source for programResourceFileSchema:"
rg -n "import.*programResourceFileSchema" apps/web/lib/actions/partners/program-resources/add-program-resource.ts

echo -e "\n4) Search for the schema’s definition across the repo:"
rg -n "programResourceFileSchema" -n .

Comment on lines +93 to +101
// Base64 encoded raster image or SVG
export const base64ImageAllowSVGSchema = z
.string()
.trim()
.regex(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,/, {
message:
"Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
})
.transform((v) => v || null);
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

Critical security issue: Missing async validation for SVG base64 content.

The new base64ImageAllowSVGSchema only validates the regex pattern but lacks the async refinement check present in the original base64ImageSchema (lines 70-90). This means malicious content could be uploaded if it matches the SVG regex pattern, as the actual file buffer content is not validated.

Apply this fix to add proper async validation:

// Base64 encoded raster image or SVG
export const base64ImageAllowSVGSchema = z
  .string()
  .trim()
  .regex(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,/, {
    message:
      "Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
  })
+  .refine(
+    async (str) => {
+      const base64Data = str.split(",")[1];
+
+      if (!base64Data) {
+        return false;
+      }
+
+      try {
+        const buffer = new Uint8Array(Buffer.from(base64Data, "base64"));
+        
+        // For SVG, check if it's valid XML structure
+        if (str.includes('svg+xml')) {
+          const svgContent = buffer.toString();
+          return svgContent.includes('<svg') && svgContent.includes('</svg>');
+        }
+        
+        // For other formats, use fileTypeFromBuffer
+        const fileType = await fileTypeFromBuffer(buffer);
+        return fileType && allowedImageTypes.includes(fileType.mime);
+      } catch (e) {
+        return false;
+      }
+    },
+    {
+      message: "Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
+    },
+  )
  .transform((v) => v || null);
📝 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
// Base64 encoded raster image or SVG
export const base64ImageAllowSVGSchema = z
.string()
.trim()
.regex(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,/, {
message:
"Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
})
.transform((v) => v || null);
// Base64 encoded raster image or SVG
export const base64ImageAllowSVGSchema = z
.string()
.trim()
.regex(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,/, {
message:
"Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
})
.refine(
async (str) => {
const base64Data = str.split(",")[1];
if (!base64Data) {
return false;
}
try {
const buffer = new Uint8Array(Buffer.from(base64Data, "base64"));
// For SVG, check if it's valid XML structure
if (str.includes("svg+xml")) {
const svgContent = buffer.toString();
return svgContent.includes("<svg") && svgContent.includes("</svg>");
}
// For other formats, use fileTypeFromBuffer
const fileType = await fileTypeFromBuffer(buffer);
return fileType && allowedImageTypes.includes(fileType.mime);
} catch (e) {
return false;
}
},
{
message:
"Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
},
)
.transform((v) => v || null);
🤖 Prompt for AI Agents
In apps/web/lib/zod/schemas/misc.ts around lines 93 to 101, the
base64ImageAllowSVGSchema currently only validates the string format with a
regex but lacks the async refinement that verifies the actual decoded file
content for security. To fix this, add an async refinement step similar to the
one in base64ImageSchema (lines 70-90) that decodes the base64 string and
validates the file buffer content to ensure it is a safe and valid image,
preventing malicious uploads.

@steven-tey steven-tey merged commit e1d2041 into main Jun 23, 2025
6 of 7 checks passed
@steven-tey steven-tey deleted the resource-svgs branch June 23, 2025 22:49
@coderabbitai coderabbitai bot mentioned this pull request Jul 21, 2025
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