@gylautorun/dev-proxy-cookie 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +212 -236
- package/dist/index.d.mts +61 -2
- package/dist/index.d.ts +61 -2
- package/dist/index.js +105 -29
- package/dist/index.min.js +4 -4
- package/dist/index.min.mjs +4 -4
- package/dist/index.mjs +104 -29
- package/package.json +1 -1
- package/src/proxy/apply-dev-authentications.ts +40 -0
- package/src/proxy/core.ts +37 -6
- package/src/proxy/index.ts +1 -0
- package/src/proxy/vite-middleware-plugin.ts +50 -15
- package/src/proxy/vue-proxy-config.ts +53 -14
package/dist/index.min.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",s?"(has cookie)":"(empty)"),s}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=x.resolve(this.options.cookieFile),e=x.dirname(o);u.existsSync(e)||u.mkdirSync(e,{recursive:!0}),u.existsSync(o)||u.writeFileSync(o,"")}};function _(t){let o=new y({cookieFile:t});return()=>o.readCookie()}import*as A from"path";import W from"chokidar";var v=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new y({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=A.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=W.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function P(t,o,e){let r=new v({cookieFile:t,onCookieChange:o,onError:e});return r.start(),r}function E(t){return["production","prod","prd","release","staging","uat"].includes(t.toLowerCase().trim())}function H(t=[],o=!1,e="[env-detector]"){let r=process.env;if(t.length>0)for(let i of t){let a=r[i];if(a&&E(a))return o&&console.log(`${e} Detected production via custom env: ${i}=${a}`),!0}let n=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let i of n){let a=r[i];if(a&&E(a))return o&&console.log(`${e} Detected production via env: ${i}=${a}`),!0}if(r.CI==="true"||r.CI==="1"||r.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(r.npm_lifecycle_event){let i=r.npm_lifecycle_event.toLowerCase();if(i.includes("build")||i.includes("prod")||i.includes("prd")||i.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${r.npm_lifecycle_event}`),!0}let s=process.argv.join("").toLowerCase();return s.includes("build")||s.includes("production")||s.includes("--mode=production")||s.includes("--prod")||s.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function S(t,o=[],e=!1,r="[env-detector]"){return typeof t=="boolean"?(e&&!t&&console.log(`${r} Watch disabled by user setting`),t):H(o,e,r)?(e&&console.log(`${r} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${r} Auto-detected development mode - enabling watch`),!0)}function C(t,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=t.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}t.removeHeader("cookie"),t.removeHeader("Cookie"),t.setHeader("Cookie",o);let r=t.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",r?`(length: ${String(r).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}var m=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=D.resolve(this.options.restartMarkerFile);M.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,r,n)=>{if(console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),C(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onProxyReq hook error:",s.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,r)=>{let n=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers",n.join(",")),r.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onProxyRes hook error:",s.message)}};this.handleOnError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),r instanceof O.ServerResponse&&!r.headersSent&&(r.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),r.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onError hook error:",n.message)}};this.handleOnWsError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),r&&r.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onWsError hook error:",n.message)}};let r={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},...r},this.cookieReader=new y({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",r=new URL(e,"http://localhost").pathname,n=this.options.proxyMap||{},s=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",r),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(n)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",s);for(let[i,a]of Object.entries(n)){let l=r.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",i,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",i,"->",a),a}for(let i of s){let a=r.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",i,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",i,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(r=>o.startsWith(r))}log(o,...e){let r={debug:0,info:1,warn:2,error:3},n=this.options.debug?"debug":this.options.logLevel||"info",s=r[n];r[o]>=s&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:r,secure:n,followRedirects:s,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:h}=this.options;return{target:o,ws:e,changeOrigin:r,secure:n,followRedirects:s,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:{...h},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=$.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,r,n)=>{let s=e.url||"/",i=new URL(s,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",s),console.log("[AutoProxyCookie] Pathname:",i),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),n();return}this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie);let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(p=>i.startsWith(p));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let p=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${p}`);let d=this.createProxyOptions(p);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,r,d),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(c){console.error("[AutoProxyCookie] Proxy web error:",c.message),n(c)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),n()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,r,n)=>{let s=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(s)){r.destroy();return}let i=this.getProxyUrl(e);this.proxyServer?.ws(e,r,n,{target:i,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=P(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function to(t){return new m(t)}function V(t,o){return o.some(e=>t.startsWith(e))}function U(t,o){return o.some(e=>t.startsWith(e))}function L(t,o,e){for(let[r,n]of Object.entries(o))if(t.startsWith(r))return n;return e}function no(t){let{cookieFile:o,target:e,debug:r=!1,proxyMap:n={},proxyPaths:s=[],ignorePaths:i=[]}=t,a=new y({cookieFile:o},r),l=a.readCookie(),g=[...Object.keys(n),...s];return{name:"vite-middleware-proxy",apply:"serve",configureServer(h){let d=I("http-proxy").createProxyServer({});r&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),h.middlewares.use((c,f,R)=>{let k=new URL(c.url||"/","http://localhost").pathname;if(V(k,i)){r&&console.log("[ViteMiddlewareProxy] Ignoring:",k),R();return}if(!U(k,g)){R();return}let b=L(k,n,e);r&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,k,"->",b),l=a.readCookie(),l&&(r&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${l.length})`),c.headers.cookie=l,c.headers.Cookie=l),d.web(c,f,{target:b,changeOrigin:!0,secure:!1,ignorePath:!1})}),d.on("error",(c,f)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",f.url)})}}}import*as w from"path";function F(t,o={}){let{getCookie:e,debug:r=!1,headers:n={},ws:s=!1,changeOrigin:i=!0,secure:a=!1,onError:l}=o;return{ws:s,target:t,changeOrigin:i,secure:a,headers:n,onProxyReq:(h,p)=>{let d=e?e():"";if(d&&C(h,d),r){let c=p.url||"/";console.log("[Proxy Request]",c,p.method,d?"(with cookie)":"(no cookie)")}},onError:l||(h=>{console.error(`
|
|
3
|
-
[Proxy Error]`,
|
|
4
|
-
[Proxy Error]`,
|
|
1
|
+
var V=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});import*as I from"http";import*as F from"fs";import*as W from"path";import U from"http-proxy";import*as f from"fs";import*as v from"path";var k=class{constructor(o,e=!1){this.options={encoding:"utf-8",...o},this.debug=e}readCookie(){try{let o=v.resolve(this.options.cookieFile);if(this.debug&&(console.log("[CookieReader] Resolved cookie file path:",o),console.log("[CookieReader] File exists:",f.existsSync(o))),f.existsSync(o)){let e=f.readFileSync(o,this.options.encoding||"utf-8");this.debug&&console.log("[CookieReader] File content length:",e.length);let s=e.split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",s?"(has cookie)":"(empty)"),s}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=v.resolve(this.options.cookieFile),e=v.dirname(o);f.existsSync(e)||f.mkdirSync(e,{recursive:!0}),f.existsSync(o)||f.writeFileSync(o,"")}};function q(i){let o=new k({cookieFile:i});return()=>o.readCookie()}import*as O from"path";import $ from"chokidar";var R=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new k({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=O.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=$.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function w(i,o,e){let t=new R({cookieFile:i,onCookieChange:o,onError:e});return t.start(),t}function D(i){return["production","prod","prd","release","staging","uat"].includes(i.toLowerCase().trim())}function N(i=[],o=!1,e="[env-detector]"){let t=process.env;if(i.length>0)for(let r of i){let a=t[r];if(a&&D(a))return o&&console.log(`${e} Detected production via custom env: ${r}=${a}`),!0}let n=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let r of n){let a=t[r];if(a&&D(a))return o&&console.log(`${e} Detected production via env: ${r}=${a}`),!0}if(t.CI==="true"||t.CI==="1"||t.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(t.npm_lifecycle_event){let r=t.npm_lifecycle_event.toLowerCase();if(r.includes("build")||r.includes("prod")||r.includes("prd")||r.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${t.npm_lifecycle_event}`),!0}let s=process.argv.join("").toLowerCase();return s.includes("build")||s.includes("production")||s.includes("--mode=production")||s.includes("--prod")||s.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function M(i,o=[],e=!1,t="[env-detector]"){return typeof i=="boolean"?(e&&!i&&console.log(`${t} Watch disabled by user setting`),i):N(o,e,t)?(e&&console.log(`${t} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${t} Auto-detected development mode - enabling watch`),!0)}function x(i,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=i.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}i.removeHeader("cookie"),i.removeHeader("Cookie"),i.setHeader("Cookie",o);let t=i.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",t?`(length: ${String(t).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}function C(i,o){if(console.log("[applyDevAuthentications] === START ==="),!o||o.length===0){console.log("[applyDevAuthentications] Authentications is empty, returning"),console.log("[applyDevAuthentications] === END ===");return}console.log("[applyDevAuthentications] Applying authentications:",JSON.stringify(o));for(let e of o)for(let[t,n]of Object.entries(e))i.setHeader(t,n),console.log("[applyDevAuthentications] Set header:",t,"->",n);console.log("[applyDevAuthentications] === END ===")}var A=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=W.resolve(this.options.restartMarkerFile);F.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,t,n)=>{console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.options.useCookie&&this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),x(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):this.options.useCookie?console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"):console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");let s=this.options.authentications||[];if(s.length>0&&(console.log("[AutoProxyCookie] Applying authentications headers..."),C(o,s),console.log("[AutoProxyCookie] Authentications headers applied successfully")),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,t)}catch(r){this.log("error","[AutoProxyCookie] onProxyReq hook error:",r.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,t)=>{let n=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers",n.join(",")),t.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,t)}catch(s){this.log("error","[AutoProxyCookie] onProxyRes hook error:",s.message)}};this.handleOnError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),t instanceof I.ServerResponse&&!t.headersSent&&(t.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),t.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,t)}catch(n){this.log("error","[AutoProxyCookie] onError hook error:",n.message)}};this.handleOnWsError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),t&&t.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,t)}catch(n){this.log("error","[AutoProxyCookie] onWsError hook error:",n.message)}};let t={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},useCookie:!0,authentications:[],...t},this.cookieReader=new k({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",t=new URL(e,"http://localhost").pathname,n=this.options.proxyMap||{},s=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",t),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(n)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",s);for(let[r,a]of Object.entries(n)){let l=t.startsWith(r);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",r,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",r,"->",a),a}for(let r of s){let a=t.startsWith(r);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",r,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",r,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(t=>o.startsWith(t))}log(o,...e){let t={debug:0,info:1,warn:2,error:3},n=this.options.debug?"debug":this.options.logLevel||"info",s=t[n];t[o]>=s&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:t,secure:n,followRedirects:s,autoRewrite:r,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:h}=this.options;return{target:o,ws:e,changeOrigin:t,secure:n,followRedirects:s,autoRewrite:r,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:{...h},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=U.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,t,n)=>{let s=e.url||"/",r=new URL(s,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",s),console.log("[AutoProxyCookie] Pathname:",r),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(r)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),n();return}this.options.useCookie?(this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie)):console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(u=>r.startsWith(u));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let u=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${r} -> ${u}`);let g=this.createProxyOptions(u);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,t,g),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(d){console.error("[AutoProxyCookie] Proxy web error:",d.message),n(d)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),n()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,t,n)=>{let s=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(s)){t.destroy();return}let r=this.getProxyUrl(e);this.proxyServer?.ws(e,t,n,{target:r,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=w(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function lo(i){return new A(i)}function L(i,o){return o.some(e=>i.startsWith(e))}function T(i,o){return o.some(e=>i.startsWith(e))}function _(i,o,e){for(let[t,n]of Object.entries(o))if(i.startsWith(t))return n;return e}function uo(i){let{cookieFile:o,target:e,debug:t=!1,useCookie:n=!0,authentications:s=[],proxyMap:r={},proxyPaths:a=[],ignorePaths:l=[]}=i,p=new k({cookieFile:o},t),h="";n&&(h=p.readCookie());let u=[...Object.keys(r),...a];return{name:"vite-middleware-proxy",apply:"serve",configureServer(g){let y=V("http-proxy").createProxyServer({});n&&t&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),g.middlewares.use((c,m,E)=>{let P=new URL(c.url||"/","http://localhost").pathname;if(L(P,l)){t&&console.log("[ViteMiddlewareProxy] Ignoring:",P),E();return}if(!T(P,u)){E();return}let S=_(P,r,e);t&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,P,"->",S),y.web(c,m,{target:S,changeOrigin:!0,secure:!1,ignorePath:!1})}),y.on("proxyReq",(c,m)=>{n?(h=p.readCookie(),h?(t&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${h.length})`),x(c,h)):t&&console.log("[ViteMiddlewareProxy] Cookie file is empty")):t&&console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection"),s&&s.length>0&&(C(c,s),t&&console.log("[ViteMiddlewareProxy] Injecting authentications:",JSON.stringify(s)))}),y.on("error",(c,m)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",m.url)})}}}import*as b from"path";function H(i,o={}){let{getCookie:e,debug:t=!1,useCookie:n=!0,authentications:s=[],headers:r={},ws:a=!1,changeOrigin:l=!0,secure:p=!1,onError:h}=o;return{ws:a,target:i,changeOrigin:l,secure:p,headers:r,onProxyReq:(g,d)=>{let y=d.url||"/";if(n){let c=e?e():"";c&&x(g,c),t&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else t&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");s&&s.length>0&&(C(g,s),t&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))},onError:h||(g=>{console.error(`
|
|
3
|
+
[Proxy Error]`,g.message)})}}function Co(i,o={}){let{watch:e="auto",debug:t=!0,productionEnvs:n=[],isDev:s}=o,r=new k({cookieFile:b.resolve(i)},t),a;return s!==void 0?(a=s,t&&console.log(`[CookieFile] isDev=${s}, ${a?"enabling":"disabling"} watch`)):a=M(e,n,t,"[CookieFile]"),a?w(b.resolve(i),l=>{t&&console.log("[CookieFile] Updated:",l?"(has cookie)":"(empty)")},l=>{console.error("[CookieFile] Watch error:",l.message)}):t&&console.log("[CookieFile] File watch disabled"),()=>r.readCookie()}function Po(i){let{target:o,ignorePaths:e=[],includePaths:t=[],additionalProxies:n={},getCookie:s,debug:r,headers:a,useCookie:l=!0,authentications:p=[]}=i,h={};if(t.length>0)for(let u of t)h[u]=H(o,{getCookie:s,debug:r,headers:a,useCookie:l,authentications:p});else{let u={ws:!1,target:o,changeOrigin:!0,secure:!1,headers:a,onProxyReq:(g,d)=>{let y=d.url||"/";if(!e.some(c=>y.startsWith(c))){if(l){let c=s?s():"";c&&x(g,c),r&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else r&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");p&&p.length>0&&(C(g,p),r&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))}},onError:g=>{console.error(`
|
|
4
|
+
[Proxy Error]`,g.message)}};h["/"]=u}for(let[u,g]of Object.entries(n))h[u]=H(g,{getCookie:s,debug:r,headers:a,useCookie:l,authentications:p});return h}export{A as AutoProxyCookie,k as CookieReader,R as CookieWatcher,C as applyDevAuthentications,Po as createAutoProxyConfig,lo as createAutoProxyCookie,q as createCookieGetter,Co as createFileCookieGetter,H as createVueProxyConfig,N as detectProductionEnvironment,D as isProductionValue,M as shouldEnableWatch,uo as viteMiddlewareProxy,w as watchCookieFile};
|
package/dist/index.mjs
CHANGED
|
@@ -295,6 +295,24 @@ function applyDevCookieHeader(proxyReq, cookie) {
|
|
|
295
295
|
console.log("[applyDevCookieHeader] === END ===");
|
|
296
296
|
}
|
|
297
297
|
|
|
298
|
+
// src/proxy/apply-dev-authentications.ts
|
|
299
|
+
function applyDevAuthentications(proxyReq, authentications) {
|
|
300
|
+
console.log("[applyDevAuthentications] === START ===");
|
|
301
|
+
if (!authentications || authentications.length === 0) {
|
|
302
|
+
console.log("[applyDevAuthentications] Authentications is empty, returning");
|
|
303
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
console.log("[applyDevAuthentications] Applying authentications:", JSON.stringify(authentications));
|
|
307
|
+
for (const authItem of authentications) {
|
|
308
|
+
for (const [key, value] of Object.entries(authItem)) {
|
|
309
|
+
proxyReq.setHeader(key, value);
|
|
310
|
+
console.log("[applyDevAuthentications] Set header:", key, "->", value);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
314
|
+
}
|
|
315
|
+
|
|
298
316
|
// src/proxy/core.ts
|
|
299
317
|
var AutoProxyCookie = class {
|
|
300
318
|
/**
|
|
@@ -339,14 +357,23 @@ var AutoProxyCookie = class {
|
|
|
339
357
|
this.handleOnProxyReq = (proxyReq, req, res, _options) => {
|
|
340
358
|
console.log("[AutoProxyCookie] === handleOnProxyReq START ===");
|
|
341
359
|
console.log("[AutoProxyCookie] Request URL:", req.method, req.url);
|
|
360
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
342
361
|
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
343
|
-
if (this.currentCookie) {
|
|
362
|
+
if (this.options.useCookie && this.currentCookie) {
|
|
344
363
|
console.log("[AutoProxyCookie] Applying cookie header...");
|
|
345
364
|
applyDevCookieHeader(proxyReq, this.currentCookie);
|
|
346
365
|
console.log("[AutoProxyCookie] Cookie header applied successfully");
|
|
366
|
+
} else if (!this.options.useCookie) {
|
|
367
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");
|
|
347
368
|
} else {
|
|
348
369
|
console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
|
|
349
370
|
}
|
|
371
|
+
const authentications = this.options.authentications || [];
|
|
372
|
+
if (authentications.length > 0) {
|
|
373
|
+
console.log("[AutoProxyCookie] Applying authentications headers...");
|
|
374
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
375
|
+
console.log("[AutoProxyCookie] Authentications headers applied successfully");
|
|
376
|
+
}
|
|
350
377
|
this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
|
|
351
378
|
if (this.options.hooks.onProxyReq) {
|
|
352
379
|
try {
|
|
@@ -465,6 +492,8 @@ var AutoProxyCookie = class {
|
|
|
465
492
|
cookieDomainRewrite: "*",
|
|
466
493
|
cookiePathRewrite: false,
|
|
467
494
|
headers: {},
|
|
495
|
+
useCookie: true,
|
|
496
|
+
authentications: [],
|
|
468
497
|
...mergedOptions
|
|
469
498
|
};
|
|
470
499
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -602,16 +631,21 @@ var AutoProxyCookie = class {
|
|
|
602
631
|
console.log("[AutoProxyCookie] Method:", req.method);
|
|
603
632
|
console.log("[AutoProxyCookie] Full URL:", fullUrl);
|
|
604
633
|
console.log("[AutoProxyCookie] Pathname:", pathname);
|
|
634
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
605
635
|
console.log("[AutoProxyCookie] Headers:", JSON.stringify(req.headers, null, 2));
|
|
606
636
|
if (this.isIgnoredPath(pathname)) {
|
|
607
637
|
console.log("[AutoProxyCookie] Path ignored, passing to next middleware");
|
|
608
638
|
next();
|
|
609
639
|
return;
|
|
610
640
|
}
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
641
|
+
if (this.options.useCookie) {
|
|
642
|
+
this.currentCookie = this.cookieReader.readCookie();
|
|
643
|
+
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
644
|
+
if (this.currentCookie) {
|
|
645
|
+
console.log("[AutoProxyCookie] Cookie preview:", this.currentCookie);
|
|
646
|
+
}
|
|
647
|
+
} else {
|
|
648
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");
|
|
615
649
|
}
|
|
616
650
|
const proxyMapKeys = Object.keys(this.options.proxyMap || {});
|
|
617
651
|
const proxyPaths = this.options.proxyPaths || [];
|
|
@@ -737,12 +771,17 @@ function viteMiddlewareProxy(options) {
|
|
|
737
771
|
cookieFile,
|
|
738
772
|
target,
|
|
739
773
|
debug = false,
|
|
774
|
+
useCookie = true,
|
|
775
|
+
authentications = [],
|
|
740
776
|
proxyMap = {},
|
|
741
777
|
proxyPaths = [],
|
|
742
778
|
ignorePaths = []
|
|
743
779
|
} = options;
|
|
744
780
|
const cookieReader = new CookieReader({ cookieFile }, debug);
|
|
745
|
-
let currentCookie =
|
|
781
|
+
let currentCookie = "";
|
|
782
|
+
if (useCookie) {
|
|
783
|
+
currentCookie = cookieReader.readCookie();
|
|
784
|
+
}
|
|
746
785
|
const allProxyPrefixes = [
|
|
747
786
|
...Object.keys(proxyMap),
|
|
748
787
|
...proxyPaths
|
|
@@ -753,7 +792,7 @@ function viteMiddlewareProxy(options) {
|
|
|
753
792
|
configureServer(server) {
|
|
754
793
|
const httpProxy2 = __require("http-proxy");
|
|
755
794
|
const proxyServer = httpProxy2.createProxyServer({});
|
|
756
|
-
if (debug) {
|
|
795
|
+
if (useCookie && debug) {
|
|
757
796
|
console.log("[ViteMiddlewareProxy] Watching cookie file:", cookieFile);
|
|
758
797
|
}
|
|
759
798
|
server.middlewares.use((req, res, next) => {
|
|
@@ -773,14 +812,6 @@ function viteMiddlewareProxy(options) {
|
|
|
773
812
|
if (debug) {
|
|
774
813
|
console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
|
|
775
814
|
}
|
|
776
|
-
currentCookie = cookieReader.readCookie();
|
|
777
|
-
if (currentCookie) {
|
|
778
|
-
if (debug) {
|
|
779
|
-
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
780
|
-
}
|
|
781
|
-
req.headers["cookie"] = currentCookie;
|
|
782
|
-
req.headers["Cookie"] = currentCookie;
|
|
783
|
-
}
|
|
784
815
|
proxyServer.web(req, res, {
|
|
785
816
|
target: proxyTarget,
|
|
786
817
|
changeOrigin: true,
|
|
@@ -788,6 +819,27 @@ function viteMiddlewareProxy(options) {
|
|
|
788
819
|
ignorePath: false
|
|
789
820
|
});
|
|
790
821
|
});
|
|
822
|
+
proxyServer.on("proxyReq", (proxyReq, req) => {
|
|
823
|
+
if (useCookie) {
|
|
824
|
+
currentCookie = cookieReader.readCookie();
|
|
825
|
+
if (currentCookie) {
|
|
826
|
+
if (debug) {
|
|
827
|
+
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
828
|
+
}
|
|
829
|
+
applyDevCookieHeader(proxyReq, currentCookie);
|
|
830
|
+
} else if (debug) {
|
|
831
|
+
console.log("[ViteMiddlewareProxy] Cookie file is empty");
|
|
832
|
+
}
|
|
833
|
+
} else if (debug) {
|
|
834
|
+
console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection");
|
|
835
|
+
}
|
|
836
|
+
if (authentications && authentications.length > 0) {
|
|
837
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
838
|
+
if (debug) {
|
|
839
|
+
console.log("[ViteMiddlewareProxy] Injecting authentications:", JSON.stringify(authentications));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
});
|
|
791
843
|
proxyServer.on("error", (err, req) => {
|
|
792
844
|
console.error("[ViteMiddlewareProxy] Proxy error:", err.message, "for", req.url);
|
|
793
845
|
});
|
|
@@ -801,6 +853,8 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
801
853
|
const {
|
|
802
854
|
getCookie,
|
|
803
855
|
debug = false,
|
|
856
|
+
useCookie = true,
|
|
857
|
+
authentications = [],
|
|
804
858
|
headers = {},
|
|
805
859
|
ws = false,
|
|
806
860
|
changeOrigin = true,
|
|
@@ -814,13 +868,23 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
814
868
|
secure,
|
|
815
869
|
headers,
|
|
816
870
|
onProxyReq: (proxyReq, req) => {
|
|
817
|
-
const
|
|
818
|
-
if (
|
|
819
|
-
|
|
871
|
+
const reqPath = req.url || "/";
|
|
872
|
+
if (useCookie) {
|
|
873
|
+
const cookie = getCookie ? getCookie() : "";
|
|
874
|
+
if (cookie) {
|
|
875
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
876
|
+
}
|
|
877
|
+
if (debug) {
|
|
878
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
879
|
+
}
|
|
880
|
+
} else if (debug) {
|
|
881
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
820
882
|
}
|
|
821
|
-
if (
|
|
822
|
-
|
|
823
|
-
|
|
883
|
+
if (authentications && authentications.length > 0) {
|
|
884
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
885
|
+
if (debug) {
|
|
886
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
887
|
+
}
|
|
824
888
|
}
|
|
825
889
|
},
|
|
826
890
|
onError: customOnError || ((err) => {
|
|
@@ -864,11 +928,11 @@ function createFileCookieGetter(cookieFile, options = {}) {
|
|
|
864
928
|
return () => reader.readCookie();
|
|
865
929
|
}
|
|
866
930
|
function createAutoProxyConfig(options) {
|
|
867
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers } = options;
|
|
931
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true, authentications = [] } = options;
|
|
868
932
|
const result = {};
|
|
869
933
|
if (includePaths.length > 0) {
|
|
870
934
|
for (const proxyPath of includePaths) {
|
|
871
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers });
|
|
935
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie, authentications });
|
|
872
936
|
}
|
|
873
937
|
} else {
|
|
874
938
|
const defaultProxy = {
|
|
@@ -882,12 +946,22 @@ function createAutoProxyConfig(options) {
|
|
|
882
946
|
if (ignorePaths.some((p) => reqPath.startsWith(p))) {
|
|
883
947
|
return;
|
|
884
948
|
}
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
949
|
+
if (useCookie) {
|
|
950
|
+
const cookie = getCookie ? getCookie() : "";
|
|
951
|
+
if (cookie) {
|
|
952
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
953
|
+
}
|
|
954
|
+
if (debug) {
|
|
955
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
956
|
+
}
|
|
957
|
+
} else if (debug) {
|
|
958
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
888
959
|
}
|
|
889
|
-
if (
|
|
890
|
-
|
|
960
|
+
if (authentications && authentications.length > 0) {
|
|
961
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
962
|
+
if (debug) {
|
|
963
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
964
|
+
}
|
|
891
965
|
}
|
|
892
966
|
},
|
|
893
967
|
onError: (err) => {
|
|
@@ -897,7 +971,7 @@ function createAutoProxyConfig(options) {
|
|
|
897
971
|
result["/"] = defaultProxy;
|
|
898
972
|
}
|
|
899
973
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
900
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers });
|
|
974
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie, authentications });
|
|
901
975
|
}
|
|
902
976
|
return result;
|
|
903
977
|
}
|
|
@@ -905,6 +979,7 @@ export {
|
|
|
905
979
|
AutoProxyCookie,
|
|
906
980
|
CookieReader,
|
|
907
981
|
CookieWatcher,
|
|
982
|
+
applyDevAuthentications,
|
|
908
983
|
createAutoProxyConfig,
|
|
909
984
|
createAutoProxyCookie,
|
|
910
985
|
createCookieGetter,
|
package/package.json
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 应用开发环境自定义鉴权信息到代理请求头
|
|
3
|
+
*
|
|
4
|
+
* 将自定义鉴权信息数组展开为请求头键值对,注入到代理请求中。
|
|
5
|
+
* 支持多种鉴权方式,如 ticket、token、Authorization 等。
|
|
6
|
+
*
|
|
7
|
+
* @module apply-dev-authentications
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type AuthenticationItem = Record<string, string>;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 将自定义鉴权信息数组应用到代理请求头
|
|
14
|
+
*
|
|
15
|
+
* @param proxyReq - 代理请求对象
|
|
16
|
+
* @param authentications - 鉴权信息数组,每个元素是一个键值对对象
|
|
17
|
+
*/
|
|
18
|
+
export function applyDevAuthentications(
|
|
19
|
+
proxyReq: { setHeader(name: string, value: string): void; getHeader?(name: string): string | string[] | undefined },
|
|
20
|
+
authentications: AuthenticationItem[]
|
|
21
|
+
): void {
|
|
22
|
+
console.log('[applyDevAuthentications] === START ===');
|
|
23
|
+
|
|
24
|
+
if (!authentications || authentications.length === 0) {
|
|
25
|
+
console.log('[applyDevAuthentications] Authentications is empty, returning');
|
|
26
|
+
console.log('[applyDevAuthentications] === END ===');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
console.log('[applyDevAuthentications] Applying authentications:', JSON.stringify(authentications));
|
|
31
|
+
|
|
32
|
+
for (const authItem of authentications) {
|
|
33
|
+
for (const [key, value] of Object.entries(authItem)) {
|
|
34
|
+
proxyReq.setHeader(key, value);
|
|
35
|
+
console.log('[applyDevAuthentications] Set header:', key, '->', value);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
console.log('[applyDevAuthentications] === END ===');
|
|
40
|
+
}
|
package/src/proxy/core.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { ViteDevServer } from 'vite';
|
|
|
15
15
|
import httpProxy from 'http-proxy';
|
|
16
16
|
import { CookieReader, CookieWatcher, watchCookieFile } from '../utils';
|
|
17
17
|
import { applyDevCookieHeader } from './apply-dev-cookie-header';
|
|
18
|
+
import { applyDevAuthentications, type AuthenticationItem } from './apply-dev-authentications';
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* 错误回调函数类型
|
|
@@ -98,6 +99,19 @@ export interface AutoProxyCookieOptions {
|
|
|
98
99
|
* 使用示例: isDev: process.env.NODE_ENV === 'development'
|
|
99
100
|
*/
|
|
100
101
|
isDev?: boolean;
|
|
102
|
+
/**
|
|
103
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
104
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
105
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
106
|
+
*
|
|
107
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
108
|
+
*/
|
|
109
|
+
useCookie?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
112
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
113
|
+
*/
|
|
114
|
+
authentications?: AuthenticationItem[];
|
|
101
115
|
}
|
|
102
116
|
|
|
103
117
|
/**
|
|
@@ -157,6 +171,8 @@ export class AutoProxyCookie {
|
|
|
157
171
|
cookieDomainRewrite: '*',
|
|
158
172
|
cookiePathRewrite: false,
|
|
159
173
|
headers: {},
|
|
174
|
+
useCookie: true,
|
|
175
|
+
authentications: [],
|
|
160
176
|
...mergedOptions,
|
|
161
177
|
};
|
|
162
178
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -302,16 +318,26 @@ export class AutoProxyCookie {
|
|
|
302
318
|
private handleOnProxyReq = (proxyReq: any, req: IncomingMessage, res: ServerResponse, _options: ServerOptions): void => {
|
|
303
319
|
console.log('[AutoProxyCookie] === handleOnProxyReq START ===');
|
|
304
320
|
console.log('[AutoProxyCookie] Request URL:', req.method, req.url);
|
|
321
|
+
console.log('[AutoProxyCookie] useCookie:', this.options.useCookie);
|
|
305
322
|
console.log('[AutoProxyCookie] Current cookie:', this.currentCookie ? `(length: ${this.currentCookie.length})` : '(empty)');
|
|
306
323
|
|
|
307
|
-
if (this.currentCookie) {
|
|
324
|
+
if (this.options.useCookie && this.currentCookie) {
|
|
308
325
|
console.log('[AutoProxyCookie] Applying cookie header...');
|
|
309
326
|
applyDevCookieHeader(proxyReq, this.currentCookie);
|
|
310
327
|
console.log('[AutoProxyCookie] Cookie header applied successfully');
|
|
328
|
+
} else if (!this.options.useCookie) {
|
|
329
|
+
console.log('[AutoProxyCookie] useCookie is false, skipping cookie injection');
|
|
311
330
|
} else {
|
|
312
331
|
console.log('[AutoProxyCookie] No cookie to apply - currentCookie is empty!');
|
|
313
332
|
}
|
|
314
333
|
|
|
334
|
+
const authentications = this.options.authentications || [];
|
|
335
|
+
if (authentications.length > 0) {
|
|
336
|
+
console.log('[AutoProxyCookie] Applying authentications headers...');
|
|
337
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
338
|
+
console.log('[AutoProxyCookie] Authentications headers applied successfully');
|
|
339
|
+
}
|
|
340
|
+
|
|
315
341
|
this.log('debug', '[AutoProxyCookie] Proxy Request:', req.method, req.url);
|
|
316
342
|
|
|
317
343
|
if (this.options.hooks.onProxyReq) {
|
|
@@ -453,6 +479,7 @@ export class AutoProxyCookie {
|
|
|
453
479
|
console.log('[AutoProxyCookie] Method:', req.method);
|
|
454
480
|
console.log('[AutoProxyCookie] Full URL:', fullUrl);
|
|
455
481
|
console.log('[AutoProxyCookie] Pathname:', pathname);
|
|
482
|
+
console.log('[AutoProxyCookie] useCookie:', this.options.useCookie);
|
|
456
483
|
console.log('[AutoProxyCookie] Headers:', JSON.stringify(req.headers, null, 2));
|
|
457
484
|
|
|
458
485
|
if (this.isIgnoredPath(pathname)) {
|
|
@@ -461,11 +488,15 @@ export class AutoProxyCookie {
|
|
|
461
488
|
return;
|
|
462
489
|
}
|
|
463
490
|
|
|
464
|
-
//
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
491
|
+
// 如果启用 Cookie,读取 cookie 并更新 currentCookie
|
|
492
|
+
if (this.options.useCookie) {
|
|
493
|
+
this.currentCookie = this.cookieReader.readCookie();
|
|
494
|
+
console.log('[AutoProxyCookie] Current cookie:', this.currentCookie ? `(length: ${this.currentCookie.length})` : '(empty)');
|
|
495
|
+
if (this.currentCookie) {
|
|
496
|
+
console.log('[AutoProxyCookie] Cookie preview:', this.currentCookie);
|
|
497
|
+
}
|
|
498
|
+
} else {
|
|
499
|
+
console.log('[AutoProxyCookie] useCookie is false, skipping cookie reading');
|
|
469
500
|
}
|
|
470
501
|
|
|
471
502
|
// 检查是否匹配代理路径(包括 proxyMap 和 proxyPaths)
|
package/src/proxy/index.ts
CHANGED
|
@@ -8,17 +8,32 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { IncomingMessage, ServerResponse } from 'http';
|
|
10
10
|
import { CookieReader } from '../utils/cookie-reader';
|
|
11
|
+
import { applyDevCookieHeader } from './apply-dev-cookie-header';
|
|
12
|
+
import { applyDevAuthentications, type AuthenticationItem } from './apply-dev-authentications';
|
|
11
13
|
|
|
12
14
|
/**
|
|
13
15
|
* Vite 中间件代理 Cookie 插件配置选项
|
|
14
16
|
*/
|
|
15
17
|
export interface ViteMiddlewareProxyOptions {
|
|
16
|
-
/** Cookie
|
|
18
|
+
/** Cookie 文件路径, 使用文件方便监听cookie 变化,避免手动启动更新 */
|
|
17
19
|
cookieFile: string;
|
|
18
20
|
/** 默认代理目标地址 */
|
|
19
21
|
target: string;
|
|
20
22
|
/** 是否启用调试日志 */
|
|
21
23
|
debug?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
26
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
27
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
28
|
+
*
|
|
29
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
30
|
+
*/
|
|
31
|
+
useCookie?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
34
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
35
|
+
*/
|
|
36
|
+
authentications?: AuthenticationItem[];
|
|
22
37
|
/**
|
|
23
38
|
* 代理路径映射表
|
|
24
39
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -71,6 +86,8 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
71
86
|
cookieFile,
|
|
72
87
|
target,
|
|
73
88
|
debug = false,
|
|
89
|
+
useCookie = true,
|
|
90
|
+
authentications = [],
|
|
74
91
|
proxyMap = {},
|
|
75
92
|
proxyPaths = [],
|
|
76
93
|
ignorePaths = [],
|
|
@@ -78,7 +95,12 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
78
95
|
|
|
79
96
|
// 创建 Cookie 读取器
|
|
80
97
|
const cookieReader = new CookieReader({ cookieFile }, debug);
|
|
81
|
-
let currentCookie =
|
|
98
|
+
let currentCookie = '';
|
|
99
|
+
|
|
100
|
+
// 如果启用 Cookie,读取初始 Cookie
|
|
101
|
+
if (useCookie) {
|
|
102
|
+
currentCookie = cookieReader.readCookie();
|
|
103
|
+
}
|
|
82
104
|
|
|
83
105
|
// 合并所有代理路径前缀
|
|
84
106
|
const allProxyPrefixes = [
|
|
@@ -96,7 +118,7 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
96
118
|
const proxyServer = httpProxy.createProxyServer({});
|
|
97
119
|
|
|
98
120
|
// 监听 Cookie 文件变化
|
|
99
|
-
if (debug) {
|
|
121
|
+
if (useCookie && debug) {
|
|
100
122
|
console.log('[ViteMiddlewareProxy] Watching cookie file:', cookieFile);
|
|
101
123
|
}
|
|
102
124
|
|
|
@@ -126,18 +148,6 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
126
148
|
console.log('[ViteMiddlewareProxy] Proxying:', req.method, pathname, '->', proxyTarget);
|
|
127
149
|
}
|
|
128
150
|
|
|
129
|
-
// 读取最新的 Cookie
|
|
130
|
-
currentCookie = cookieReader.readCookie();
|
|
131
|
-
|
|
132
|
-
// 注入 Cookie
|
|
133
|
-
if (currentCookie) {
|
|
134
|
-
if (debug) {
|
|
135
|
-
console.log('[ViteMiddlewareProxy] Injecting cookie:', `(length: ${currentCookie.length})`);
|
|
136
|
-
}
|
|
137
|
-
(req as any).headers['cookie'] = currentCookie;
|
|
138
|
-
(req as any).headers['Cookie'] = currentCookie;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
151
|
// 代理请求
|
|
142
152
|
proxyServer.web(req, res, {
|
|
143
153
|
target: proxyTarget,
|
|
@@ -147,6 +157,31 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
147
157
|
});
|
|
148
158
|
});
|
|
149
159
|
|
|
160
|
+
// 代理请求前的回调 - 注入 Cookie 和自定义鉴权信息
|
|
161
|
+
proxyServer.on('proxyReq', (proxyReq: any, req: IncomingMessage) => {
|
|
162
|
+
if (useCookie) {
|
|
163
|
+
currentCookie = cookieReader.readCookie();
|
|
164
|
+
|
|
165
|
+
if (currentCookie) {
|
|
166
|
+
if (debug) {
|
|
167
|
+
console.log('[ViteMiddlewareProxy] Injecting cookie:', `(length: ${currentCookie.length})`);
|
|
168
|
+
}
|
|
169
|
+
applyDevCookieHeader(proxyReq, currentCookie);
|
|
170
|
+
} else if (debug) {
|
|
171
|
+
console.log('[ViteMiddlewareProxy] Cookie file is empty');
|
|
172
|
+
}
|
|
173
|
+
} else if (debug) {
|
|
174
|
+
console.log('[ViteMiddlewareProxy] useCookie is false, skipping cookie injection');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (authentications && authentications.length > 0) {
|
|
178
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
179
|
+
if (debug) {
|
|
180
|
+
console.log('[ViteMiddlewareProxy] Injecting authentications:', JSON.stringify(authentications));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
|
|
150
185
|
// 错误处理
|
|
151
186
|
proxyServer.on('error', (err: Error, req: IncomingMessage) => {
|
|
152
187
|
console.error('[ViteMiddlewareProxy] Proxy error:', err.message, 'for', req.url);
|