Skip to content

Conversation

@tomerqodo
Copy link

@tomerqodo tomerqodo commented Dec 4, 2025

User description

Benchmark PR discourse#36240

Type: Corrupted (contains bugs)

Original PR Title: FIX: maintain extension when quoting images
Original PR Description: Also do not show quote image to anonymous

Original PR URL: discourse#36240


PR Type

Bug fix, Enhancement


Description

  • Maintain file extension when quoting images with upload:// URLs

  • Hide quote image button from anonymous users

  • Refactor quote image functionality with improved naming

  • Extract extension utility function for reusable image URL handling


Diagram Walkthrough

flowchart LR
  A["Image Quoting Logic"] -->|"Add canQuoteImage check"| B["Conditional UI Registration"]
  C["extensionFromUrl utility"] -->|"Extract extension"| D["upload:// URL Building"]
  E["User Authentication"] -->|"Check currentUser"| F["Permission Control"]
  D -->|"Apply to"| G["quote-image.js & to-markdown.js"]
Loading

File Walkthrough

Relevant files
Enhancement
lightbox.js
Add user permission check for quote button                             

frontend/discourse/app/lib/lightbox.js

  • Replace User.current() with helperContext().currentUser for better
    context management
  • Add canQuoteImage permission check to conditionally render quote
    button
  • Rename imported function from canQuoteImage to canBuildImageQuote
  • Wrap quote-image UI element registration in permission guard
+38/-33 
markdown-image-builder.js
Add extension extraction utility function                               

frontend/discourse/app/lib/markdown-image-builder.js

  • Add new extensionFromUrl() utility function to extract file extensions
    from URLs
  • Function handles null/empty URLs and returns null when no extension
    found
  • Uses regex pattern to match file extensions at end of URL
  • Provides reusable logic for extension extraction across codebase
+16/-0   
Bug fix
quote-image.js
Preserve file extension in upload URLs                                     

frontend/discourse/app/lib/lightbox/quote-image.js

  • Import extensionFromUrl utility function from markdown-image-builder
  • Append file extension to upload:// URLs when base62SHA1 is present
  • Rename canQuoteImage function to canBuildImageQuote with JSDoc
    documentation
  • Extract extension from slideData.origSrc and append to short URL
    format
+16/-2   
to-markdown.js
Apply extension preservation to markdown conversion           

frontend/discourse/app/lib/to-markdown.js

  • Import extensionFromUrl utility function
  • Apply extension preservation to link href conversion with base62SHA1
  • Apply extension preservation to image src conversion with base62SHA1
  • Try multiple sources for extension extraction (href, src,
    data-orig-src, data-download-href)
+19/-1   
Tests
quote-image-test.js
Update tests for authentication and extension handling     

frontend/discourse/tests/unit/lib/lightbox/quote-image-test.js

  • Set up helper context with currentUser in beforeEach hook
  • Log in test user to enable quote functionality
  • Restore original helper context in afterEach hook
  • Rename test and function calls from canQuoteImage to
    canBuildImageQuote
  • Update test assertion message to reflect extension preservation
+21/-7   
to-markdown-test.js
Update markdown conversion test expectations                         

frontend/discourse/tests/unit/lib/to-markdown-test.js

  • Update test expectations to include .png extension in upload:// URLs
  • Verify extension is preserved for base62SHA1 image conversions
  • Update test for lightbox link with base62SHA1 to expect .jpeg
    extension
+2/-2     

@qodo-code-review
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing audit logs: New permission-gated UI actions (quoting images, downloading) are executed without any
auditing or logging of the user, action, or outcome.

Referred Code
if (canQuoteImage) {
  lightboxEl.pswp.ui.registerElement({
    name: "quote-image",
    order: 10,
    isButton: true,
    title: i18n("lightbox.quote"),
    html: {
      isCustomSVG: true,
      inner:
        '<path id="pswp__icn-quote" d="M0 216C0 149.7 53.7 96 120 96l8 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-8 0c-30.9 0-56 25.1-56 56l0 8 64 0c35.3 0 64 28.7 64 64l0 64c0 35.3-28.7 64-64 64l-64 0c-35.3 0-64-28.7-64-64l0-32 0-32 0-72zm256 0c0-66.3 53.7-120 120-120l8 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-8 0c-30.9 0-56 25.1-56 56l0 8 64 0c35.3 0 64 28.7 64 64l0 64c0 35.3-28.7 64-64 64l-64 0c-35.3 0-64-28.7-64-64l0-32 0-32 0-72z"/>',
      outlineID: "pswp__icn-quote",
      size: 512,
    },
    onInit: (el, pswp) => {
      pswp.on("change", () => {
        const slideData = pswp.currSlide?.data;
        const slideElement = slideData?.element;
        el.style.display = canBuildImageQuote(slideElement, slideData)
          ? ""
          : "none";
      });


 ... (clipped 11 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Edge case handling: The new extensionFromUrl relies on a simple regex that may miss common cases (query
strings, fragments, uppercase/multi-dot names) without explicit handling or tests for
those edge cases.

Referred Code
export function extensionFromUrl(url) {
  if (!url) {
    return null;
  }

  const match = url.match(/\.([a-zA-Z0-9]+)$/);
  return match ? match[1] : null;
}

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
URL parsing risk: The new extensionFromUrl function parses arbitrary URLs with a regex and its output is
used to build user-facing upload URLs, which may require stricter validation or
normalization to prevent malformed or misleading links.

Referred Code
export function extensionFromUrl(url) {
  if (!url) {
    return null;
  }

  const match = url.match(/\.([a-zA-Z0-9]+)$/);
  return match ? match[1] : null;
}

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Improve regex for URL extension

Update the regex in extensionFromUrl to be case-insensitive and correctly handle
URLs with query parameters or fragments to avoid failing to extract file
extensions.

frontend/discourse/app/lib/markdown-image-builder.js [23-30]

 export function extensionFromUrl(url) {
   if (!url) {
     return null;
   }
 
-  const match = url.match(/\.([a-zA-Z0-9]+)$/);
+  const match = url.match(/\.([a-z0-9]+)(?:[?#]|$)/i);
   return match ? match[1] : null;
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the regex is too restrictive and will fail for URLs with query parameters or fragments, which is a common case. The proposed fix is accurate and significantly improves the reliability of the new extensionFromUrl function.

Medium
Improve extension detection from URL

To improve file extension detection, check slideData.src as a fallback if the
extension is not found in slideData.origSrc.

frontend/discourse/app/lib/lightbox/quote-image.js [20-30]

 // Check for base62 SHA1 to use short upload:// URL format (same as to-markdown.js)
 if (slideData.base62SHA1) {
-  const extension = extensionFromUrl(slideData.origSrc);
+  const extension =
+    extensionFromUrl(slideData.origSrc) || extensionFromUrl(slideData.src);
   src = `upload://${slideData.base62SHA1}`;
   if (extension) {
     src += `.${extension}`;
   }
 } else {
   // Prefer data-orig-src (same as to-markdown.js)
   src = slideData.origSrc || slideData.src;
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that slideData.origSrc might not have the extension and proposes a fallback to slideData.src, which improves robustness and aligns with logic in other parts of the codebase.

Medium
  • More

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.

3 participants