-
-
Notifications
You must be signed in to change notification settings - Fork 425
fix: proxy external images in package readmes #1143
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
danielroe
merged 12 commits into
npmx-dev:main
from
liuxiaopai-ai:fix/proxy-readme-images-privacy
Feb 26, 2026
Merged
Changes from 2 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
b6c0f06
fix: proxy external images in README to prevent privacy leak
invalid-email-address ffc0b5e
[autofix.ci] apply automated fixes
autofix-ci[bot] 87dc65b
Merge remote-tracking branch 'origin/main' into fix/proxy-readme-imag…
danielroe 53b2cf5
fix: return stream, protect against ssrf
danielroe 85d5bd9
refactor: use ipaddr.js to handle private ranges + move to server/ dir
danielroe 3dcea43
Merge remote-tracking branch 'origin/main' into fix/proxy-readme-imag…
danielroe baf5728
fix: handle protocol relative urls
danielroe 225c883
fix: add timeout, block svgs, prevent rebinding
danielroe 15b4291
Merge remote-tracking branch 'origin/main' into fix/proxy-readme-imag…
danielroe 3fff5e8
fix: ensure all ips are private
danielroe efaf9a7
Merge remote-tracking branch 'origin/main' into fix/proxy-readme-imag…
danielroe efc87f4
fix: add hmac signing
danielroe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import { createError, getQuery, setResponseHeaders } from 'h3' | ||
| import { CACHE_MAX_AGE_ONE_DAY } from '#shared/utils/constants' | ||
| import { isAllowedImageUrl } from '#shared/utils/image-proxy' | ||
|
|
||
| /** | ||
| * Image proxy endpoint to prevent privacy leaks from README images. | ||
| * | ||
| * Instead of letting the client's browser fetch images directly from third-party | ||
| * servers (which exposes visitor IP, User-Agent, etc.), this endpoint fetches | ||
| * images server-side and forwards them to the client. | ||
| * | ||
| * Similar to GitHub's camo proxy: https://github.blog/2014-01-28-proxying-user-images/ | ||
| * | ||
| * Usage: /api/registry/image-proxy?url=https://example.com/image.png | ||
| * | ||
| * Resolves: https://github.com/npmx-dev/npmx.dev/issues/1138 | ||
| */ | ||
| export default defineCachedEventHandler( | ||
| async event => { | ||
| const query = getQuery(event) | ||
| const url = query.url as string | undefined | ||
|
|
||
| if (!url) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Missing required "url" query parameter.', | ||
| }) | ||
| } | ||
|
|
||
| // Validate URL | ||
| if (!isAllowedImageUrl(url)) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid or disallowed image URL.', | ||
| }) | ||
| } | ||
|
|
||
| try { | ||
| const response = await fetch(url, { | ||
| headers: { | ||
| // Use a generic User-Agent to avoid leaking server info | ||
| 'User-Agent': 'npmx-image-proxy/1.0', | ||
| 'Accept': 'image/*', | ||
| }, | ||
| // Prevent redirects to non-HTTP protocols | ||
| redirect: 'follow', | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| if (!response.ok) { | ||
| throw createError({ | ||
| statusCode: response.status === 404 ? 404 : 502, | ||
| message: `Failed to fetch image: ${response.status}`, | ||
| }) | ||
| } | ||
|
|
||
| const contentType = response.headers.get('content-type') || 'application/octet-stream' | ||
|
|
||
| // Only allow image content types | ||
| if ( | ||
| !contentType.startsWith('image/') && | ||
| !contentType.startsWith('application/octet-stream') | ||
| ) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'URL does not point to an image.', | ||
| }) | ||
| } | ||
|
|
||
| // Enforce a maximum size of 10 MB to prevent abuse | ||
| const contentLength = response.headers.get('content-length') | ||
| const MAX_SIZE = 10 * 1024 * 1024 // 10 MB | ||
| if (contentLength && Number.parseInt(contentLength, 10) > MAX_SIZE) { | ||
| throw createError({ | ||
| statusCode: 413, | ||
| message: 'Image too large.', | ||
| }) | ||
| } | ||
|
|
||
| const imageBuffer = await response.arrayBuffer() | ||
|
danielroe marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Check actual size | ||
| if (imageBuffer.byteLength > MAX_SIZE) { | ||
| throw createError({ | ||
| statusCode: 413, | ||
| message: 'Image too large.', | ||
| }) | ||
| } | ||
|
|
||
| setResponseHeaders(event, { | ||
| 'Content-Type': contentType, | ||
| 'Content-Length': imageBuffer.byteLength.toString(), | ||
| 'Cache-Control': `public, max-age=${CACHE_MAX_AGE_ONE_DAY}, s-maxage=${CACHE_MAX_AGE_ONE_DAY}`, | ||
| // Security headers - prevent content sniffing and restrict usage | ||
| 'X-Content-Type-Options': 'nosniff', | ||
| 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'", | ||
| }) | ||
|
|
||
| return Buffer.from(imageBuffer) | ||
| } catch (error: unknown) { | ||
| // Re-throw H3 errors | ||
| if (error && typeof error === 'object' && 'statusCode' in error) { | ||
| throw error | ||
| } | ||
|
|
||
| throw createError({ | ||
| statusCode: 502, | ||
| message: 'Failed to proxy image.', | ||
| }) | ||
| } | ||
| }, | ||
| { | ||
| maxAge: CACHE_MAX_AGE_ONE_DAY, | ||
| swr: true, | ||
| getKey: event => { | ||
| const query = getQuery(event) | ||
| return `image-proxy:${query.url}` | ||
| }, | ||
| }, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| /** | ||
| * Image proxy utilities for privacy-safe README image rendering. | ||
| * | ||
| * Resolves: https://github.com/npmx-dev/npmx.dev/issues/1138 | ||
| */ | ||
|
|
||
| /** Trusted image domains that don't need proxying (first-party or well-known CDNs) */ | ||
| const TRUSTED_IMAGE_DOMAINS = [ | ||
| // First-party | ||
| 'npmx.dev', | ||
|
|
||
| // GitHub (already proxied by GitHub's own camo) | ||
| 'raw.githubusercontent.com', | ||
| 'github.com', | ||
| 'user-images.githubusercontent.com', | ||
| 'avatars.githubusercontent.com', | ||
| 'repository-images.githubusercontent.com', | ||
| 'github.githubassets.com', | ||
| 'objects.githubusercontent.com', | ||
|
|
||
| // GitLab | ||
| 'gitlab.com', | ||
|
|
||
| // CDNs commonly used in READMEs | ||
| 'cdn.jsdelivr.net', | ||
| 'unpkg.com', | ||
|
|
||
| // Well-known badge/shield services | ||
| 'img.shields.io', | ||
| 'shields.io', | ||
| 'badge.fury.io', | ||
| 'badgen.net', | ||
| 'flat.badgen.net', | ||
| 'codecov.io', | ||
| 'coveralls.io', | ||
| 'david-dm.org', | ||
| 'snyk.io', | ||
| 'app.fossa.com', | ||
| 'api.codeclimate.com', | ||
| 'bundlephobia.com', | ||
| 'packagephobia.com', | ||
| ] | ||
|
|
||
| /** | ||
| * Check if a URL points to a trusted domain that doesn't need proxying. | ||
| */ | ||
| export function isTrustedImageDomain(url: string): boolean { | ||
| try { | ||
| const parsed = new URL(url) | ||
| const hostname = parsed.hostname.toLowerCase() | ||
| return TRUSTED_IMAGE_DOMAINS.some( | ||
| domain => hostname === domain || hostname.endsWith(`.${domain}`), | ||
| ) | ||
| } catch { | ||
| return false | ||
| } | ||
|
danielroe marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| /** | ||
| * Validate that a URL is a valid HTTP(S) image URL suitable for proxying. | ||
| */ | ||
| export function isAllowedImageUrl(url: string): boolean { | ||
| try { | ||
| const parsed = new URL(url) | ||
| // Only allow HTTP and HTTPS protocols | ||
| if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { | ||
| return false | ||
| } | ||
| // Block localhost / private IPs to prevent SSRF | ||
| const hostname = parsed.hostname.toLowerCase() | ||
| if ( | ||
| hostname === 'localhost' || | ||
| hostname === '127.0.0.1' || | ||
| hostname === '::1' || | ||
| hostname === '0.0.0.0' || | ||
| hostname.startsWith('10.') || | ||
| hostname.startsWith('192.168.') || | ||
| hostname.startsWith('172.') || | ||
| hostname.endsWith('.local') || | ||
| hostname.endsWith('.internal') | ||
| ) { | ||
| return false | ||
| } | ||
| return true | ||
| } catch { | ||
| return false | ||
| } | ||
|
danielroe marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| /** | ||
| * Convert an external image URL to a proxied URL. | ||
| * Trusted domains are returned as-is. | ||
| * Returns the original URL for non-HTTP(S) URLs. | ||
| */ | ||
| export function toProxiedImageUrl(url: string): string { | ||
| // Don't proxy data URIs, relative URLs, or anchor links | ||
| if (!url || url.startsWith('#') || url.startsWith('data:')) { | ||
| return url | ||
| } | ||
|
|
||
| try { | ||
| const parsed = new URL(url) | ||
| if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { | ||
| return url | ||
| } | ||
| } catch { | ||
| // Not an absolute URL, return as-is (relative URLs are fine) | ||
| return url | ||
| } | ||
|
danielroe marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Trusted domains don't need proxying | ||
| if (isTrustedImageDomain(url)) { | ||
| return url | ||
| } | ||
|
|
||
| // Proxy through our server endpoint | ||
| return `/api/registry/image-proxy?url=${encodeURIComponent(url)}` | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle potential array values in query parameter.
If a request contains multiple
urlparameters (e.g.,?url=a&url=b),query.urlwill be an array, making the type cast unsafe. This also affects the cache key on line 116.🔧 Suggested fix
📝 Committable suggestion