-
-
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 6 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
Some comments aren't visible on the classic Files Changed page.
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,134 @@ | ||
| import { createError, getQuery, setResponseHeaders, sendStream } from 'h3' | ||
| import { Readable } from 'node:stream' | ||
| import { CACHE_MAX_AGE_ONE_DAY } from '#shared/utils/constants' | ||
| import { isAllowedImageUrl } from '#server/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 defineEventHandler(async event => { | ||
| const query = getQuery(event) | ||
| const rawUrl = query.url | ||
| const url = (Array.isArray(rawUrl) ? rawUrl[0] : rawUrl) 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/*', | ||
| }, | ||
| redirect: 'follow', | ||
| }) | ||
|
|
||
| // Validate final URL after any redirects to prevent SSRF bypass | ||
| if (response.url !== url && !isAllowedImageUrl(response.url)) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Redirect to disallowed URL.', | ||
| }) | ||
| } | ||
|
|
||
| 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/')) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'URL does not point to an image.', | ||
| }) | ||
| } | ||
|
|
||
| // Check Content-Length header if present (may be absent or dishonest) | ||
| const MAX_SIZE = 10 * 1024 * 1024 // 10 MB | ||
| const contentLength = response.headers.get('content-length') | ||
| if (contentLength && Number.parseInt(contentLength, 10) > MAX_SIZE) { | ||
| throw createError({ | ||
| statusCode: 413, | ||
| message: 'Image too large.', | ||
| }) | ||
| } | ||
|
|
||
| if (!response.body) { | ||
| throw createError({ | ||
| statusCode: 502, | ||
| message: 'No response body from upstream.', | ||
| }) | ||
| } | ||
|
|
||
| setResponseHeaders(event, { | ||
| 'Content-Type': contentType, | ||
| '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'", | ||
| }) | ||
|
|
||
| // Stream the response with a size limit to prevent memory exhaustion. | ||
| // This avoids buffering the entire image into memory before sending. | ||
| let bytesRead = 0 | ||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| const upstream = Readable.fromWeb(response.body as any) | ||
| const limited = new Readable({ | ||
| read() { | ||
| /* pulling is driven by upstream push */ | ||
| }, | ||
| }) | ||
|
|
||
| upstream.on('data', (chunk: Buffer) => { | ||
| bytesRead += chunk.length | ||
| if (bytesRead > MAX_SIZE) { | ||
| upstream.destroy() | ||
| limited.destroy(new Error('Image too large')) | ||
| } else { | ||
| limited.push(chunk) | ||
| } | ||
| }) | ||
| upstream.on('end', () => limited.push(null)) | ||
| upstream.on('error', (err: Error) => limited.destroy(err)) | ||
|
|
||
| return sendStream(event, limited) | ||
| } 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.', | ||
| }) | ||
| } | ||
| }) |
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,117 @@ | ||
| /** | ||
| * Image proxy utilities for privacy-safe README image rendering. | ||
| * | ||
| * Resolves: https://github.com/npmx-dev/npmx.dev/issues/1138 | ||
| */ | ||
|
|
||
| import ipaddr from 'ipaddr.js' | ||
|
|
||
| /** 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 { | ||
| const parsed = URL.parse(url) | ||
| if (!parsed) return false | ||
|
|
||
| const hostname = parsed.hostname.toLowerCase() | ||
| return TRUSTED_IMAGE_DOMAINS.some( | ||
| domain => hostname === domain || hostname.endsWith(`.${domain}`), | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Validate that a URL is a valid HTTP(S) image URL suitable for proxying. | ||
| * Blocks private/reserved IPs (SSRF protection) using ipaddr.js for comprehensive | ||
| * IPv4, IPv6, and IPv4-mapped IPv6 range detection. | ||
| */ | ||
| export function isAllowedImageUrl(url: string): boolean { | ||
| const parsed = URL.parse(url) | ||
| if (!parsed) return false | ||
|
|
||
| // Only allow HTTP and HTTPS protocols | ||
| if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { | ||
| return false | ||
| } | ||
|
|
||
| const hostname = parsed.hostname.toLowerCase() | ||
|
|
||
| // Block non-IP hostnames that resolve to internal services | ||
| if (hostname === 'localhost' || hostname.endsWith('.local') || hostname.endsWith('.internal')) { | ||
| return false | ||
| } | ||
|
|
||
| // For IP addresses, use ipaddr.js to check against all reserved ranges | ||
| // (loopback, private RFC 1918, link-local 169.254, IPv6 ULA fc00::/7, etc.) | ||
| // ipaddr.process() also unwraps IPv4-mapped IPv6 (e.g. ::ffff:127.0.0.1 → 127.0.0.1) | ||
| const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname | ||
| if (ipaddr.isValid(bare)) { | ||
| const addr = ipaddr.process(bare) | ||
| if (addr.range() !== 'unicast') { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| /** | ||
| * 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 | ||
| } | ||
|
|
||
| const parsed = URL.parse(url) | ||
| if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) { | ||
| return url | ||
| } | ||
|
|
||
| // 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.
Uh oh!
There was an error while loading. Please reload this page.