12 个视觉参考图库与浏览器无限画布 AI 创作台(5,700+ 素材、中英提示词、多图对比、ComfyUI & MCP)· Visual reference library & infinite-canvas AI studio in the browser
JavaScript ai-artai-try-onchinesecloudflare-pagescomfyuidrawing-referencefashiongeminigpt-imageimage-generationinfinite-canvasmcpmoodboardoutfit-referencepose-referencepromptpwareference-boardseedreamvirtual-try-on
fix: 自定义中转代理开关生效、代理放行非 443 端口、新增 Gemini 协议(#14 #17)
atuizz962e04460856
diff --git a/functions/api/proxy.js b/functions/api/proxy.jsindex 9216ad1..2a6e8a1 100644--- a/functions/api/proxy.js+++ b/functions/api/proxy.js@@ -1,6 +1,7 @@// 衣姿 PoseWear 转发代理(v10):只转发、不记录、不存储任何请求内容或密钥。-// 限制:① 只接受本站页面发起的请求(Origin / Referer 同源);② 只转发到官方接口域名,-// 自定义中转必须带 x-proxy-custom: 1 且路径符合图片接口格式;③ 结果图片只从官方结果 CDN 下载;④ 每 IP 频率限制。+// 限制:① 只接受本站页面发起的请求(Origin / Referer 同源);② 官方接口只走标准 https;+// 自定义中转必须带 x-proxy-custom: 1 且路径符合图片接口格式,可用 http/https 任意端口(内网地址除外);+// ③ 结果图片只从官方结果 CDN 下载;④ 每 IP 频率限制。const API_PATH=/^\/(api\/v3|v\d+(beta|alpha)?)\/(images\/(edits|generations)|models(\/[^/]+(:generateContent)?)?)$/;const OFFICIAL=[/^api\.openai\.com$/,/^generativelanguage\.googleapis\.com$/,/^ark\.[a-z0-9-]+\.volces\.com$/,/^ark\.[a-z0-9-]+\.bytepluses\.com$/];const IMG_HOSTS=[/^oaidalleapiprodscus\.blob\.core\.windows\.net$/,/(^|\.)volces\.com$/,/(^|\.)bytepluses\.com$/,/(^|\.)googleusercontent\.com$/];@@ -19,7 +20,9 @@ export async function onRequest(ctx){const {request}=ctx;if(!['GET','POST'].includes(request.method))return j(405,'只支持 GET / POST');if(!sameSite(request))return j(403,'只接受本站页面发起的请求');let t;try{t=new URL(request.headers.get('x-target-url')||'')}catch(e){return j(400,'缺少或无效的 x-target-url')}- if(t.protocol!=='https:'||t.username||t.password||(t.port&&t.port!=='443'))return j(400,'目标地址必须是标准 https 地址');+ if(t.username||t.password)return j(400,'目标地址不能带账号密码');+ const official0=OFFICIAL.some(r=>r.test(t.hostname));+ if(official0?(t.protocol!=='https:'||(t.port&&t.port!=='443')):!/^https?:$/.test(t.protocol))return j(400,official0?'官方接口地址必须是标准 https 地址':'目标地址必须是 http/https 地址');const ip=request.headers.get('cf-connecting-ip')||'0';const img=request.headers.get('x-proxy-kind')==='image';if(img){if(request.method!=='GET')return j(405,'图片下载只支持 GET');diff --git a/src/index.html b/src/index.htmlindex 517436a..a9716a3 100644--- a/src/index.html+++ b/src/index.html@@ -63,8 +63,8 @@<p class="fine" id="cfHelp"></p><div class="grp">连接</div><label class="fld">Base URL<input id="cfBase" placeholder="https://api.openai.com" spellcheck="false"></label><label class="fld">API Key<span class="kw"><input id="cfKey" type="password" placeholder="sk-…" autocomplete="off" spellcheck="false"><button class="sm ghost" id="cfEye" type="button">显示</button></span></label><label class="fld">模型<input id="cfModel" list="cfModels" spellcheck="false"><datalist id="cfModels"></datalist></label>-<div class="grp">高级</div><label class="fld" id="cfProtoW">接口协议<select id="cfProto"><option value="edits">images/edits · multipart(OpenAI 官方格式)</option><option value="json">images/generations · JSON 多图(多数中转 / gpt-image-2)</option><option value="xai">xAI · images/edits JSON(Grok Imagine)</option></select></label><label class="fld" id="cfFieldW">图片字段名<select id="cfField"><option value="image[]">image[](官方,多图)</option><option value="image">image(部分中转)</option></select></label>-<label class="tg"><input type="checkbox" id="cfProxy"><span><b>通过本站代理转发</b><small>中转不支持跨域(CORS)时再打开。只转发,不保存。自定义中转总是经本站转发。</small></span></label>+<div class="grp">高级</div><label class="fld" id="cfProtoW">接口协议<select id="cfProto"><option value="edits">images/edits · multipart(OpenAI 官方格式)</option><option value="json">images/generations · JSON 多图(多数中转 / gpt-image-2)</option><option value="xai">xAI · images/edits JSON(Grok Imagine)</option><option value="gemini">Gemini · models/:generateContent(Nano Banana 等)</option></select></label><label class="fld" id="cfFieldW">图片字段名<select id="cfField"><option value="image[]">image[](官方,多图)</option><option value="image">image(部分中转)</option></select></label>+<label class="tg"><input type="checkbox" id="cfProxy"><span><b>通过本站代理转发</b><small>中转不支持跨域(CORS)时再打开。只转发,不保存。不勾选时由浏览器直连中转地址(含非 443 端口)。</small></span></label><div class="note"><b>密钥</b>只存在这个浏览器里,请求直接发给你填的地址。用公共电脑记得清除。</div><p class="fine" id="cfMsg" aria-live="polite"></p></div>diff --git a/src/studio.js b/src/studio.jsindex 23193ac..cc165c2 100644--- a/src/studio.js+++ b/src/studio.js@@ -144,15 +144,15 @@ $('#cfSave').onclick=()=>{const o=cfgRead();if(o.prov=='custom'&&!o.base)return$('#cfClr').onclick=()=>{cfg.key='';$('#cfKey').value='';SV('wbCfg',cfg);render();msg('已从本机清除密钥')};function msg(t,bad){const m=$('#cfMsg');m.textContent=t;m.className='fine '+(bad?'bad':'good')}$('#cfTest').onclick=async()=>{const o=cfgRead();if(!o.key)return msg('请先填写 API Key',1);if(o.prov=='custom'&&!o.base)return msg('请填写 Base URL',1);const old=Object.assign({},cfg);Object.assign(cfg,o);msg('正在连接…');- try{const g=cfg.prov=='gemini',url=g?`${root()}/models/${encodeURIComponent(modelOf())}`:`${root()}/models`;const r=await call(url,{method:'GET',headers:auth()});const j=await r.json().catch(()=>null);+ try{const g=proto()=='gemini',url=g?`${root()}/models/${encodeURIComponent(modelOf())}`:`${root()}/models`;const r=await call(url,{method:'GET',headers:auth()});const j=await r.json().catch(()=>null);if(!r.ok){if(cfg.prov=='seedream'&&r.status==404){if((r.headers.get('content-type')||'').includes('text/html')){const e=Error('');e.zh='本站代理未生效:/api/proxy 返回的是网站静态页面而不是接口响应,Seedream 暂时连不上,请稍后再试或联系站长';throw e}return msg('地址可达、密钥已被接受(方舟不提供模型列表接口,可直接生成测试)')}throw await apiErr(r,j)}if(g)msg(`连接成功:模型 ${j&&j.displayName||modelOf()} 可用`);else{const ids=(j&&j.data||[]).map(m=>m.id),has=ids.includes(modelOf());msg(`连接成功:共 ${ids.length} 个模型`+(ids.length?(has?`,包含 ${modelOf()}`:`,但未找到 ${modelOf()}(中转可能不列出,可直接尝试)`):''))}}catch(e){msg(nice(e),1)}finally{Object.assign(cfg,old)}};// ---------- 请求 -----------function auth(){return cfg.prov=='gemini'?{'x-goog-api-key':cfg.key}:{Authorization:'Bearer '+cfg.key}}+function auth(){return proto()=='gemini'?{'x-goog-api-key':cfg.key}:{Authorization:'Bearer '+cfg.key}}const p2=n=>String(n).padStart(2,'0'),stamp=d=>`${d.getFullYear()}${p2(d.getMonth()+1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}`;const OFF=/^(api\.openai\.com|generativelanguage\.googleapis\.com|ark\.[a-z0-9-]+\.(volces|bytepluses)\.com)$/;-function call(url,o){let hn='';try{hn=new URL(url).hostname}catch(e){}const cu=cfg.prov=='custom'||!OFF.test(hn);if(!cfg.proxy&&!cu)return fetch(url,o);const h=new Headers(o.headers||{});h.set('x-target-url',url);if(cu)h.set('x-proxy-custom','1');return fetch('/api/proxy',Object.assign({},o,{headers:h}))}+function call(url,o){let hn='';try{hn=new URL(url).hostname}catch(e){}const cu=cfg.prov=='custom'||!OFF.test(hn);if(!cfg.proxy)return fetch(url,o);const h=new Headers(o.headers||{});h.set('x-target-url',url);if(cu)h.set('x-proxy-custom','1');return fetch('/api/proxy',Object.assign({},o,{headers:h}))}async function fetchResult(url){let r=await fetch(url).catch(()=>null);if(!r||!r.ok)r=await fetch('/api/proxy',{headers:{'x-target-url':url,'x-proxy-kind':'image'}}).catch(()=>null);if(r&&r.ok)return r.blob();const e=Error('');e.zh='结果图片无法在浏览器中下载,请直接打开:'+url;throw e}const SAFE_RE=/safety system|safety_violations|moderation_blocked|content_policy_violation|content policy|SensitiveContent|sensitive content|PROHIBITED_CONTENT|IMAGE_SAFETY|\bSAFETY\b|BLOCKLIST|SPII|blocked by|内容安全|敏感/i;diff --git a/tests/v16-proxy.mjs b/tests/v16-proxy.mjsnew file mode 100644index 0000000..fb41c40--- /dev/null+++ b/tests/v16-proxy.mjs@@ -0,0 +1,29 @@+// v16:/api/proxy 端口与协议策略单元测试(node 直跑,不经浏览器)+// node tests/v16-proxy.mjs+import { onRequest } from '../functions/api/proxy.js';+let pass = 0, fail = 0;+const ok = (n, c, d) => { console.log((c ? 'PASS ' : 'FAIL ') + n + (d ? ' :: ' + d : '')); c ? pass++ : fail++; };+const SELF = 'https://posewear.pages.dev';+async function call(target, headers = {}, withOrigin = true) {+ const h = new Headers(headers);+ if (withOrigin) h.set('origin', SELF);+ if (target) h.set('x-target-url', target);+ const req = new Request(SELF + '/api/proxy', { method: 'POST', headers: h, body: '{}' });+ const r = await onRequest({ request: req, waitUntil() {} });+ const t = await r.text().catch(() => '');+ return { status: r.status, body: t.slice(0, 120) };+}+let r = await call('https://example.com:8443/v1/images/generations', { 'x-proxy-custom': '1' });+ok('custom https 非443 端口放行', r.status !== 400 && !/标准 https|http\/https 地址/.test(r.body), r.status + ' ' + r.body);+r = await call('http://example.com:8080/v1/images/edits', { 'x-proxy-custom': '1' });+ok('custom http 非443 端口放行', r.status !== 400 && !/标准 https|http\/https 地址/.test(r.body), r.status + ' ' + r.body);+r = await call('https://api.openai.com:8443/v1/images/generations', {});+ok('官方域名带端口仍拒绝', r.status === 400, r.status + ' ' + r.body);+r = await call('http://192.168.1.5:8188/v1/images/generations', { 'x-proxy-custom': '1' });+ok('自定义内网地址仍拒绝', r.status === 403, r.status + ' ' + r.body);+r = await call('https://example.com:8443/v1/chat/completions', { 'x-proxy-custom': '1' });+ok('自定义非图片路径仍拒绝', r.status === 403, r.status + ' ' + r.body);+r = await call('https://example.com/v1/images/generations', { 'x-proxy-custom': '1' }, false);+ok('无同源来源仍拒绝', r.status === 403, r.status + ' ' + r.body);+console.log(`\n${pass} passed, ${fail} failed`);+process.exit(fail ? 1 : 0);