目的:把 HTTP/HTTPS service 代理成本地 service,例如 localhost:10000
proxy.ts
Request
每个 localhost request,都会调用 getProxyCookie() 得到 proxyCookie,把它塞给 proxyReq。
Response
‘__Host-‘ 开头的 cookie 会触发浏览器的强制安全校验,必须满足:
- 必须有
Secure - 必须是
Path=/ - 不能有
Domain - 必须通过安全连接设置,实际部署通常就是 HTTPS
因为代理成 localhost service,所以 ‘__Host-‘ 的 cookie 不会被浏览器接收并保存,所以会有 cookie 过期的问题。
为了解决上面的问题,每个 proxyRes,都检查下是否带 set-cookie,有更新或者新增的,则调用 updateProxyCookie() 更新 cookie。
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { PORT, TARGET } from './config.ts';
import { getProxyCookie, updateProxyCookie } from './cookie-util.ts';
const app = express();
const EXTRA_COOKIE = process.env.PROXY_COOKIE || '';
app.use(
'/',
createProxyMiddleware({
target: TARGET,
changeOrigin: true,
secure: false,
xfwd: true,
cookieDomainRewrite: 'localhost',
cookiePathRewrite: '/',
onProxyReq: (proxyReq, req) => {
const incomingCookie = req.headers.cookie || '';
const mergedCookie = [incomingCookie, EXTRA_COOKIE, getProxyCookie()].filter(Boolean).join('; ');
if (mergedCookie) {
proxyReq.setHeader('cookie', mergedCookie);
}
proxyReq.setHeader('x-forwarded-host', req.headers.host || `localhost:${PORT}`);
proxyReq.setHeader('x-forwarded-proto', 'http');
},
onProxyRes: (proxyRes, req) => {
const localOrigin = `http://${req.headers.host || `localhost:${PORT}`}`;
const targetHost = new URL(TARGET).host;
const location = proxyRes.headers.location;
if (typeof location === 'string') {
if (location.startsWith('/')) {
proxyRes.headers.location = `${localOrigin}${location}`;
} else {
try {
const parsedLocation = new URL(location);
if (parsedLocation.host === targetHost) {
proxyRes.headers.location = `${localOrigin}${parsedLocation.pathname}${parsedLocation.search}${parsedLocation.hash}`;
}
} catch {
// Keep original header if it is not a valid absolute URL.
}
}
}
const setCookie = proxyRes.headers['set-cookie'];
if (Array.isArray(setCookie)) {
updateProxyCookie(setCookie);
proxyRes.headers['set-cookie'] = setCookie.map((cookie) =>
cookie
.replace(/;\s*Secure/gi, '')
.replace(/;\s*SameSite=None/gi, '; SameSite=Lax'),
);
}
},
logLevel: 'info',
}),
);
app.listen(PORT, () => {
console.log(`[api-proxy] Listening on http://localhost:${PORT}`);
console.log(`[api-proxy] Proxy target: ${TARGET}`);
});
cookie-util.ts
import fs from 'node:fs';
import path from 'node:path';
import { ROOT_DIR } from './config.ts';
const COOKIE_FILE = path.join(ROOT_DIR, 'proxy-cookie');
function loadCookieFile(cookieFilePath: string): string {
if (!fs.existsSync(cookieFilePath)) {
return '';
}
return fs
.readFileSync(cookieFilePath, 'utf8')
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#') && line.includes('='))
.join('; ');
}
let proxyCookie = loadCookieFile(COOKIE_FILE);
export function getProxyCookie(): string {
return proxyCookie;
}
function parseCookiePair(pair: string): [string, string] {
const index = pair.indexOf('=');
return [pair.slice(0, index).trim(), pair.slice(index + 1).trim()];
}
function toCookiePairs(setCookieHeaders: string[]): string[] {
return setCookieHeaders.map((cookie) => (cookie.split(';')[0] ?? '').trim()).filter((c) => c.includes('='));
}
export function updateProxyCookie(setCookieHeaders: string[]): void {
const responseCookies = toCookiePairs(setCookieHeaders);
if (responseCookies.length === 0) return;
const cookies = new Map(
proxyCookie
.split(';')
.map((pair) => pair.trim())
.filter((pair) => pair.includes('='))
.map(parseCookiePair),
);
const changedNames: string[] = [];
for (const [name, value] of responseCookies.map(parseCookiePair)) {
if (cookies.get(name) !== value) {
cookies.set(name, value);
changedNames.push(name);
}
}
if (changedNames.length === 0) return;
const cookiePairs = [...cookies].map(([name, value]) => `${name}=${value}`);
proxyCookie = cookiePairs.join('; ');
try {
fs.writeFileSync(COOKIE_FILE, `${cookiePairs.join('\n')}\n`);
console.log(`[api-proxy] Updated cookie(s) ${changedNames.join(', ')} in ${COOKIE_FILE}`);
} catch (error) {
console.error(`[api-proxy] Failed to write ${COOKIE_FILE}: ${error instanceof Error ? error.message : String(error)}`);
}
}
config.ts
在 .env 文件里填好代理 URL 需要的 cookies。
import fs from 'node:fs';
import path from 'node:path';
import { parseEnv } from 'node:util';
export const ROOT_DIR = path.join(import.meta.dirname, '..');
const ENV_FILE = path.join(ROOT_DIR, '.env');
function loadEnvFile(): Record<string, string | undefined> {
if (!fs.existsSync(ENV_FILE)) return {};
return parseEnv(fs.readFileSync(ENV_FILE, 'utf8'));
}
const env = loadEnvFile();
export const TARGET: string =
env.TARGET || 'https://prdvcp-brionlhn1-rf-k8s-edge-node-1-8080.vcp.prd.euwe.azure.asml.com';
export const PORT: number = Number(env.PORT || 8080);
export const LOGIN_USERNAME: string = env.LOGIN_USERNAME || '';
export const LOGIN_PASSWORD: string = env.LOGIN_PASSWORD || '';
export const BROWSER_PATH: string = env.BROWSER_PATH || '';