-
Notifications
You must be signed in to change notification settings - Fork 9
handle copy-pasting images when there is CORS #738
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
Open
GaboHBeaumont
wants to merge
2
commits into
main
Choose a base branch
from
copy-paste-images
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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
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
19 changes: 19 additions & 0 deletions
19
frontend/apps/web/app/document-edit/web-image-upload.test.ts
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,19 @@ | ||
| import {afterEach, describe, expect, it, vi} from 'vitest' | ||
| import {fetchWebImportBlob} from './web-image-upload' | ||
|
|
||
| describe('fetchWebImportBlob', () => { | ||
| afterEach(() => { | ||
| vi.unstubAllGlobals() | ||
| }) | ||
|
|
||
| it('downloads remote files through the same-origin proxy', async () => { | ||
| const fetchMock = vi.fn(async () => new Response(new Blob(['image'], {type: 'image/png'}))) | ||
| vi.stubGlobal('fetch', fetchMock) | ||
|
|
||
| const result = await fetchWebImportBlob('https://example.com/image.png') | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledWith('/hm/api/web-file?url=https%3A%2F%2Fexample.com%2Fimage.png') | ||
| expect(result.type).toBe('image/png') | ||
| expect(result.size).toBe(5) | ||
| }) | ||
| }) |
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,105 @@ | ||
| import type {LoaderFunctionArgs} from '@remix-run/node' | ||
| import {MAX_FILE_SIZE_B, MAX_FILE_SIZE_MB} from '@shm/shared/constants' | ||
| import {lookup} from 'dns/promises' | ||
| import net from 'net' | ||
|
|
||
| const MAX_REDIRECTS = 5 | ||
|
|
||
| export async function loader({request}: LoaderFunctionArgs) { | ||
| const urlParam = new URL(request.url).searchParams.get('url') | ||
| if (!urlParam) return new Response('Missing url', {status: 400}) | ||
|
|
||
| try { | ||
| const response = await fetchRemoteFile(urlParam) | ||
| const contentLength = Number(response.headers.get('content-length') || '0') | ||
| if (contentLength > MAX_FILE_SIZE_B) { | ||
| return new Response(`File too large, max size is ${MAX_FILE_SIZE_MB}MB`, {status: 413}) | ||
| } | ||
|
|
||
| const buffer = await response.arrayBuffer() | ||
| if (buffer.byteLength > MAX_FILE_SIZE_B) { | ||
| return new Response(`File too large, max size is ${MAX_FILE_SIZE_MB}MB`, {status: 413}) | ||
| } | ||
|
|
||
| return new Response(buffer, { | ||
| headers: { | ||
| 'Content-Type': response.headers.get('content-type') || 'application/octet-stream', | ||
| 'Content-Length': String(buffer.byteLength), | ||
| 'Cache-Control': 'no-store', | ||
| }, | ||
| }) | ||
| } catch (error) { | ||
| console.error('hm.api.web-file loader error:', error) | ||
| return new Response(error instanceof Error ? error.message : 'Failed to fetch file', {status: 400}) | ||
| } | ||
| } | ||
|
|
||
| async function fetchRemoteFile(url: string, redirects = 0): Promise<Response> { | ||
| if (redirects > MAX_REDIRECTS) throw new Error('Too many redirects') | ||
|
|
||
| const parsedUrl = new URL(url) | ||
| if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') { | ||
| throw new Error('Only http and https URLs are supported') | ||
| } | ||
| await assertPublicHost(parsedUrl.hostname) | ||
|
|
||
| const response = await fetch(parsedUrl, { | ||
| redirect: 'manual', | ||
| headers: { | ||
| 'User-Agent': 'Seed-Web-File-Import', | ||
| }, | ||
| }) | ||
|
|
||
| if ([301, 302, 303, 307, 308].includes(response.status)) { | ||
| const location = response.headers.get('location') | ||
| if (!location) throw new Error('Redirect without location header') | ||
| return fetchRemoteFile(new URL(location, parsedUrl).toString(), redirects + 1) | ||
| } | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`) | ||
| } | ||
|
|
||
| return response | ||
| } | ||
|
|
||
| async function assertPublicHost(hostname: string) { | ||
| const normalizedHostname = hostname.replace(/^\[|\]$/g, '') | ||
| const addresses = net.isIP(normalizedHostname) | ||
| ? [{address: normalizedHostname}] | ||
| : await lookup(normalizedHostname, { | ||
| all: true, | ||
| verbatim: true, | ||
| }) | ||
|
|
||
| if (addresses.some(({address}) => isPrivateAddress(address))) { | ||
| throw new Error('URL host is not allowed') | ||
| } | ||
| } | ||
|
|
||
| function isPrivateAddress(address: string) { | ||
| if (net.isIPv6(address)) { | ||
| const normalized = address.toLowerCase() | ||
| return ( | ||
| normalized === '::1' || | ||
| normalized.startsWith('fc') || | ||
| normalized.startsWith('fd') || | ||
| normalized.startsWith('fe80:') | ||
| ) | ||
| } | ||
|
|
||
| const parts = address.split('.').map((part) => Number(part)) | ||
| if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return true | ||
| const first = parts[0]! | ||
| const second = parts[1]! | ||
|
|
||
| return ( | ||
| first === 0 || | ||
| first === 10 || | ||
| first === 127 || | ||
| (first === 100 && second >= 64 && second <= 127) || | ||
| (first === 169 && second === 254) || | ||
| (first === 172 && second >= 16 && second <= 31) || | ||
| (first === 192 && second === 168) | ||
| ) | ||
| } | ||
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
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.
this is kind of a red flag, indicates a larger security issue with this approach. Probably we should not have this
web-fileinterface at all. The client should request the file and upload it normally.Is this intended as a sort of CORS bypass?