feat: add image proxy

This commit is contained in:
DIYgod
2025-10-01 19:57:35 +08:00
parent 8c93378e66
commit 473bf7fb2e
11 changed files with 1776 additions and 38 deletions
+58
View File
@@ -0,0 +1,58 @@
import { Hono } from 'hono'
import { FetchImageError, fetchRemoteImage } from './lib/image-fetcher'
const app = new Hono()
const hopByHopHeaders = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailers',
'transfer-encoding',
'upgrade'
])
const createForwardHeaders = (upstream: Response): Headers => {
const headers = new Headers()
upstream.headers.forEach((value, key) => {
if (hopByHopHeaders.has(key.toLowerCase())) {
return
}
headers.append(key, value)
})
if (!headers.has('Content-Type')) {
headers.set('Content-Type', 'application/octet-stream')
}
headers.set('Cache-Control', 'public, max-age=31536000')
return headers
}
app.get('/', async (c) => {
const url = c.req.query('url')
if (!url) {
return c.json({ error: 'Missing url parameter' }, 400)
}
try {
const upstream = await fetchRemoteImage(url)
const headers = createForwardHeaders(upstream)
return new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers
})
} catch (error) {
if (error instanceof FetchImageError) {
return c.json({ error: error.message }, error.status ?? 502)
}
console.error('Unexpected error fetching image', error)
return c.json({ error: 'Unexpected error fetching image' }, 502)
}
})
export default app
@@ -36,11 +36,6 @@ export const imageRefererMatches: ImageRefererMatch[] = [
}
]
export type RemoteImage = {
buffer: ArrayBuffer
contentType: string | null
}
export class FetchImageError extends Error {
status?: number
@@ -51,7 +46,42 @@ export class FetchImageError extends Error {
}
}
export const fetchRemoteImage = async (imageUrl: string): Promise<RemoteImage> => {
const resolveRefererFor = (parsed: URL): { referer: string; origin: string } => {
const origin = parsed.origin
const matchedReferer = imageRefererMatches.find(({ url }) => url.test(parsed.href))
const referer = matchedReferer?.referer ?? origin
if (!matchedReferer) {
return { referer, origin }
}
try {
const refererUrl = new URL(referer)
return { referer, origin: refererUrl.origin }
} catch {
return { referer, origin: referer }
}
}
const CACHE_TTL_SECONDS = 60 * 60 * 24 * 365
const CACHE_TTL_BY_STATUS: Record<string, number> = {
'200-299': CACHE_TTL_SECONDS,
'301-308': CACHE_TTL_SECONDS,
'400-599': 0
}
const buildUpstreamHeaders = (parsed: URL): Headers => {
const { referer, origin } = resolveRefererFor(parsed)
const headers = new Headers({
'User-Agent': DEFAULT_UA,
Accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
Referer: referer,
Origin: origin
})
return headers
}
export const fetchRemoteImage = async (imageUrl: string): Promise<Response> => {
let parsed: URL
try {
parsed = new URL(imageUrl)
@@ -63,37 +93,19 @@ export const fetchRemoteImage = async (imageUrl: string): Promise<RemoteImage> =
throw new FetchImageError('Only http and https protocols are supported')
}
const origin = parsed.origin
const matchedReferer = imageRefererMatches.find(({ url }) => url.test(parsed.href))
const resolvedReferer = matchedReferer?.referer ?? origin
let resolvedOrigin = origin
if (matchedReferer) {
try {
resolvedOrigin = new URL(resolvedReferer).origin
} catch {
resolvedOrigin = resolvedReferer
}
}
const headers = new Headers({
'User-Agent': DEFAULT_UA,
Accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
Referer: resolvedReferer,
Origin: resolvedOrigin
})
const headers = buildUpstreamHeaders(parsed)
const response = await fetch(parsed.toString(), {
headers,
redirect: 'follow'
redirect: 'follow',
cf: {
cacheEverything: true,
cacheTtlByStatus: CACHE_TTL_BY_STATUS
}
})
if (!response.ok) {
throw new FetchImageError(`Failed to fetch image: ${response.statusText}`, response.status)
}
const buffer = await response.arrayBuffer()
const contentType = response.headers.get('content-type')
return { buffer, contentType }
return response
}
+21
View File
@@ -0,0 +1,21 @@
{
"name": "image-proxy",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "$npm_execpath run build && vite preview",
"deploy": "$npm_execpath run build && wrangler deploy",
"cf-typegen": "wrangler types --env-interface CloudflareBindings"
},
"dependencies": {
"hono": "^4.9.9"
},
"devDependencies": {
"@cloudflare/vite-plugin": "^1.2.3",
"@cloudflare/workers-types": "^4.20250927.0",
"vite": "^6.3.5",
"wrangler": "^4.17.0"
},
"packageManager": "pnpm@10.17.1+sha512.17c560fca4867ae9473a3899ad84a88334914f379be46d455cbf92e5cf4b39d34985d452d2583baf19967fa76cb5c17bc9e245529d0b98745721aa7200ecaf7a"
}
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"lib": [
"ESNext",
"WebWorker"
],
"types": [
"@cloudflare/workers-types",
"vite/client"
]
}
}
+6
View File
@@ -0,0 +1,6 @@
import { cloudflare } from '@cloudflare/vite-plugin'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [cloudflare()]
})
+12
View File
@@ -0,0 +1,12 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "image-proxy",
"compatibility_date": "2025-08-03",
"main": "./index.ts",
"observability": {
"enabled": true,
"logs": {
"enabled": true
}
}
}
+8 -4
View File
@@ -4,11 +4,15 @@ import { ensureCodecsInitialised } from './lib/codec-init'
import { detectImageFormat, formatToContentType } from './lib/detect-format'
import type { ImageFormat } from './lib/detect-format'
import { resolveDimensions } from './lib/dimensions'
import { FetchImageError, fetchRemoteImage } from './lib/image-fetcher'
import { FetchImageError, fetchRemoteImageThroughProxy } from './lib/image-proxy-client'
import { decodeImage, encodeImage, resizeImage } from './lib/image-processor'
import { generateThumbHash } from './lib/thumbhash'
const app = new Hono()
type Bindings = {
IMAGE_PROXY: Fetcher
}
const app = new Hono<{ Bindings: Bindings }>()
const parseDimensionParam = (value: string | undefined | null): number | undefined => {
if (value === undefined || value === null || value === '') {
@@ -75,7 +79,7 @@ app.get('/', async (c) => {
let remote
try {
remote = await fetchRemoteImage(url)
remote = await fetchRemoteImageThroughProxy(url, c.env.IMAGE_PROXY)
} catch (error) {
if (error instanceof FetchImageError) {
return c.json({ error: error.message }, error.status ?? 502)
@@ -177,7 +181,7 @@ app.get('/meta/', async (c) => {
let remote
try {
remote = await fetchRemoteImage(url)
remote = await fetchRemoteImageThroughProxy(url, c.env.IMAGE_PROXY)
} catch (error) {
if (error instanceof FetchImageError) {
return c.json({ error: error.message }, error.status ?? 502)
@@ -0,0 +1,53 @@
export type RemoteImage = {
buffer: ArrayBuffer
contentType: string | null
}
export class FetchImageError extends Error {
status?: number
constructor(message: string, status?: number) {
super(message)
this.name = 'FetchImageError'
this.status = status
}
}
const buildProxyRequest = (imageUrl: string): Request => {
const proxyUrl = new URL('/', 'https://image-proxy.internal')
proxyUrl.searchParams.set('url', imageUrl)
return new Request(proxyUrl.toString(), {
method: 'GET'
})
}
export const fetchRemoteImageThroughProxy = async (
imageUrl: string,
proxy: Fetcher
): Promise<RemoteImage> => {
const request = buildProxyRequest(imageUrl)
let response: Response
try {
response = await proxy.fetch(request)
} catch {
throw new FetchImageError('Failed to reach image proxy')
}
if (!response.ok) {
let message = 'Failed to fetch image via proxy'
try {
const data = await response.clone().json()
if (typeof data?.error === 'string' && data.error.length > 0) {
message = data.error
}
} catch {
// Ignore JSON parsing errors; we'll fall back to the default message.
}
throw new FetchImageError(message, response.status)
}
const buffer = await response.arrayBuffer()
const contentType = response.headers.get('content-type')
return { buffer, contentType }
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"name": "cloudflare-image-converter",
"name": "image-transformer",
"type": "module",
"scripts": {
"dev": "vite",
+8 -2
View File
@@ -1,6 +1,6 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "image-converter",
"name": "image-transformer",
"compatibility_date": "2025-08-03",
"main": "./index.ts",
"observability": {
@@ -8,5 +8,11 @@
"logs": {
"enabled": true
}
}
},
"services": [
{
"binding": "IMAGE_PROXY",
"service": "image-proxy"
}
]
}