Skip to content

中文版 AI 姿势参考图库 · 1439 组 / 2878 张图片 / 完整汉化 · 零依赖静态画廊

feat(proxy): support PROXY_ALLOWED_ORIGINS env var and default useProxy to false except for Qwen/Doubao

Alone88d8f84f2f0e7d
diff --git a/functions/api/proxy.ts b/functions/api/proxy.ts
index 252e8bf..f970488 100644
--- a/functions/api/proxy.ts
+++ b/functions/api/proxy.ts
@@ -1,19 +1,47 @@
-// Cloudflare Pages Function: /api/proxy
+// Cloudflare Pages Function / Worker: /api/proxy
// 用于在生产环境解决阿里云百炼 (DashScope) 与字节火山方舟 (Volcengine Ark) 官方接口的浏览器 CORS 限制
-// 仅放行下方白名单内的上游域名,避免该端点被当作对公网开放的转发代理使用。
+// 仅放行白名单内的上游域名,支持通过环境变量 PROXY_ALLOWED_ORIGINS 动态扩展(逗号/空格/换行分隔)。
+
+export interface ProxyEnv {
+ /**
+ * 可选环境变量:动态配置允许通过 /api/proxy 转发的上游域名列表(多个域名用逗号、分号或空白分隔)。
+ * 例如:PROXY_ALLOWED_ORIGINS="https://api.example.com,https://relay.example.org"
+ * 若设置为 "*" 则放行所有 https 源站。
+ */
+ PROXY_ALLOWED_ORIGINS?: string
+}
/**
- * 允许转发的上游 origin 白名单。
+ * 默认允许转发的上游 origin 白名单。
*
* 必须按 origin 精确匹配,不能改用 startsWith 或正则前缀匹配,
* 否则 `https://dashscope.aliyuncs.com.example.com` 之类的域名可以绕过。
*/
-const ALLOWED_ORIGINS = new Set([
+const DEFAULT_ALLOWED_ORIGINS = [
'https://dashscope.aliyuncs.com', // 阿里云百炼 / Qwen
'https://ark.cn-beijing.volces.com', // 火山方舟 / Doubao
'https://generativelanguage.googleapis.com', // Google Gemini
'https://api.openai.com', // OpenAI
-])
+]
+
+function isOriginAllowed(targetOrigin: string, envRaw?: string): boolean {
+ const allowed = new Set<string>(DEFAULT_ALLOWED_ORIGINS)
+ if (envRaw && typeof envRaw === 'string') {
+ const tokens = envRaw
+ .split(/[\s,;]+/)
+ .map((s) => s.trim())
+ .filter(Boolean)
+ for (const token of tokens) {
+ if (token === '*') return true
+ try {
+ allowed.add(new URL(token).origin)
+ } catch {
+ // 忽略格式非法的配置项
+ }
+ }
+ }
+ return allowed.has(targetOrigin)
+}
/** 单次转发的请求体上限:生图接口携带 base64 图片时 10 MiB 足够。 */
const MAX_BODY_BYTES = 10 * 1024 * 1024
@@ -47,8 +75,8 @@ const limitBodySize = (body: ReadableStream<Uint8Array> | null, limit: number) =
)
}
-export const onRequestPost = async (context: { request: Request }) => {
- const { request } = context
+export const onRequestPost = async (context: { request: Request; env?: ProxyEnv }) => {
+ const { request, env } = context
const targetUrl = request.headers.get('x-target-url')
if (!targetUrl) return jsonResponse(400, 'Missing x-target-url header')
@@ -60,8 +88,8 @@ export const onRequestPost = async (context: { request: Request }) => {
return jsonResponse(400, 'Invalid x-target-url header')
}
- // 只允许白名单内的 https 上游,其余一律拒绝
- if (target.protocol !== 'https:' || !ALLOWED_ORIGINS.has(target.origin)) {
+ // 只允许白名单(含环境变量 PROXY_ALLOWED_ORIGINS)内的 https 上游,其余一律拒绝
+ if (target.protocol !== 'https:' || !isOriginAllowed(target.origin, env?.PROXY_ALLOWED_ORIGINS)) {
return jsonResponse(403, 'Target origin not allowed')
}
diff --git a/src/routes/settings.tsx b/src/routes/settings.tsx
index 4abf547..d764aec 100644
--- a/src/routes/settings.tsx
+++ b/src/routes/settings.tsx
@@ -245,7 +245,10 @@ function SettingsPage() {
</Select>
</Field>
- <Field label="服务端 CORS 代理 (/api/proxy)">
+ <Field
+ label="服务端 CORS 代理 (/api/proxy)"
+ hint="默认关闭(浏览器直连);切换到阿里云百炼 (Qwen) 或火山方舟 (Doubao) 时会自动开启。仅支持白名单域名(可通过服务端环境变量 PROXY_ALLOWED_ORIGINS 扩展)"
+ >
<div className="flex h-9 items-center justify-between rounded-xl border bg-background px-3">
<span className="text-xs text-muted-foreground">
{apiConfig.useProxy ? '已启用(解决跨域限制)' : '已关闭(浏览器直连)'}
diff --git a/src/services/aiGenerator.ts b/src/services/aiGenerator.ts
index 4c363ac..5994ca3 100644
--- a/src/services/aiGenerator.ts
+++ b/src/services/aiGenerator.ts
@@ -385,28 +385,12 @@ function dataUrlToBlob(dataUrl: string): Blob {
return new Blob([arr], { type: mime })
}
-// 与 functions/api/proxy.ts 白名单保持一致的 4 个官方源站
-const PROXY_ALLOWED_ORIGINS = new Set([
- 'https://dashscope.aliyuncs.com',
- 'https://ark.cn-beijing.volces.com',
- 'https://generativelanguage.googleapis.com',
- 'https://api.openai.com',
-])
-
async function smartFetch(
targetUrl: string,
init: RequestInit,
useProxy: boolean
): Promise<Response> {
- let canUseProxy = useProxy
- if (canUseProxy) {
- try {
- canUseProxy = PROXY_ALLOWED_ORIGINS.has(new URL(targetUrl).origin)
- } catch {
- canUseProxy = false
- }
- }
- if (!canUseProxy) {
+ if (!useProxy) {
return fetch(targetUrl, init)
}
const headers = new Headers(init.headers)
diff --git a/src/store/studioStore.tsx b/src/store/studioStore.tsx
index 66315b2..cd6f588 100644
--- a/src/store/studioStore.tsx
+++ b/src/store/studioStore.tsx
@@ -45,12 +45,15 @@ const RECIPE_KEY = 'pose_atlas_recipe_v3'
const HISTORY_KEY = 'pose_atlas_history_v3'
const SAFE_MODE_KEY = 'pose_atlas_safe_mode_v1'
-const COMFY_CONFIG_VERSION = 2
+const COMFY_CONFIG_VERSION = 3
+
+const shouldEnableProxyByDefault = (provider?: ImageProviderId) =>
+ provider === 'qwen' || provider === 'doubao'
const DEFAULT_API_CONFIG: ApiConfig = {
activeProvider: 'gemini',
imagePassMode: 'url',
- useProxy: true,
+ useProxy: false,
stylePreset: 'realistic',
sendStitchedSheet: false,
providers: {
@@ -151,13 +154,22 @@ function migrateComfy(
function mergeStoredConfig(raw: unknown): ApiConfig {
if (!raw || typeof raw !== 'object') return DEFAULT_API_CONFIG
const obj = raw as Partial<ApiConfig>
+ const storedVer = obj.comfyuiParams?.configVersion ?? 1
const comfy = migrateComfy(
{ ...DEFAULT_API_CONFIG.providers.comfyui, ...obj.providers?.comfyui },
{ ...DEFAULT_API_CONFIG.comfyuiParams, configVersion: 1, ...obj.comfyuiParams }
)
+ const activeProvider = obj.activeProvider ?? DEFAULT_API_CONFIG.activeProvider
+ // v3 起服务端 CORS 代理默认关闭,仅在切换到 Qwen / Doubao 时自动关联开启
+ const useProxy =
+ storedVer < 3
+ ? shouldEnableProxyByDefault(activeProvider)
+ : (obj.useProxy ?? shouldEnableProxyByDefault(activeProvider))
return {
...DEFAULT_API_CONFIG,
...obj,
+ activeProvider,
+ useProxy,
providers: {
gemini: { ...DEFAULT_API_CONFIG.providers.gemini, ...obj.providers?.gemini },
gpt: { ...DEFAULT_API_CONFIG.providers.gpt, ...obj.providers?.gpt },
@@ -473,7 +485,13 @@ export function StudioProvider({ children }: { children: ReactNode }) {
}
const updateApiConfig = (patch: Partial<ApiConfig>) => {
- setApiConfig((prev) => ({ ...prev, ...patch }))
+ setApiConfig((prev) => {
+ const next = { ...prev, ...patch }
+ if (patch.activeProvider && patch.useProxy === undefined) {
+ next.useProxy = shouldEnableProxyByDefault(patch.activeProvider)
+ }
+ return next
+ })
}
const updateProviderConfig = (provider: ImageProviderId, patch: Partial<ProviderEndpointConfig>) => {
diff --git a/worker.ts b/worker.ts
index 8e1a513..6f0ec37 100644
--- a/worker.ts
+++ b/worker.ts
@@ -1,6 +1,6 @@
-import { onRequestPost } from './functions/api/proxy'
+import { onRequestPost, type ProxyEnv } from './functions/api/proxy'
-export interface Env {
+export interface Env extends ProxyEnv {
ASSETS: {
fetch: (request: Request) => Promise<Response>
}
@@ -13,7 +13,7 @@ export default {
// Handle /api/proxy CORS forwarding for DashScope (Qwen) & Volcengine Ark (Doubao)
if (url.pathname === '/api/proxy') {
if (request.method === 'POST') {
- return onRequestPost({ request })
+ return onRequestPost({ request, env })
}
return new Response(JSON.stringify({ error: { message: 'Method Not Allowed' } }), {
status: 405,
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 4d67d62..d97ce11 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -7,6 +7,11 @@
"enabled": true
},
"previews": {},
+ // 可选环境变量:在 Cloudflare 控制台 Variables and Secrets 或下方 vars 中配置 PROXY_ALLOWED_ORIGINS
+ // 多个上游域名用逗号分隔,例如:"https://api.example.com,https://relay.example.org"
+ "vars": {
+ "PROXY_ALLOWED_ORIGINS": ""
+ },
"assets": {
"directory": "./dist",
"binding": "ASSETS",