chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1 @@
.vitest/
+238
View File
@@ -0,0 +1,238 @@
# @langgenius/dev-proxy
Generic Hono-based development proxy for frontend projects. The package does not ship any product-specific routes, cookie names, or environment variable conventions. Every proxied path and upstream target is declared in a local config file.
## Installation
```bash
pnpm add -D @langgenius/dev-proxy
```
Add a script in your frontend project:
```json
{
"scripts": {
"dev:proxy": "dev-proxy --config ./dev-proxy.config.ts --env-file ./.env.local"
}
}
```
Run it with:
```bash
pnpm dev:proxy
```
## CLI
```bash
dev-proxy --config ./dev-proxy.config.ts
```
Supported options:
- `--config`, `-c`: config file path. Defaults to `dev-proxy.config.ts`.
- `--env-file`: load environment variables before evaluating the config file.
- `--host`: override `server.host` from config.
- `--port`: override `server.port` from config.
- `--watch`: reload config and env file changes. Enabled by default.
- `--no-watch`: disable config and env file reloads.
- `--help`, `-h`: print help.
`--target` is not supported. Put targets in the config file so routes and upstreams stay explicit.
The CLI watches the config file and the explicit `--env-file` by default. Route, CORS, target, and cookie rewrite changes are applied in the running process. If the resolved host or port changes, the proxy closes the old server and starts a new one.
## Config Shape
```ts
import { defineDevProxyConfig } from '@langgenius/dev-proxy'
export default defineDevProxyConfig({
server: {
host: '127.0.0.1',
port: 5001,
},
routes: [
{
paths: '/api',
target: 'https://example.com',
},
],
cors: {
allowedOrigins: 'local',
},
})
```
Config files can be `.ts`, `.mts`, `.js`, or `.mjs`.
`routes` are matched in declaration order. The first matching route wins. Each configured path matches both the exact path and all child paths, so `paths: '/api'` matches `/api`, `/api/apps`, and `/api/apps/123`.
By default, credentialed CORS is allowed for local development origins such as `localhost`, `127.0.0.1`, and `::1`. To restrict it to specific origins:
```
cors: {
allowedOrigins: ['http://localhost:3000'],
}
```
## Scenario 1: Proxy One Local Route Group To An Online Backend
Use this when a local frontend should call an online backend through one proxy server. For example, the frontend calls `http://127.0.0.1:5001/api/apps`, and the proxy forwards it to `https://cloud.example.com/api/apps`.
```ts
import { defineDevProxyConfig } from '@langgenius/dev-proxy'
const target = process.env.DEV_PROXY_TARGET || 'https://cloud.example.com'
export default defineDevProxyConfig({
server: {
host: process.env.DEV_PROXY_HOST || '127.0.0.1',
port: Number(process.env.DEV_PROXY_PORT || 5001),
},
routes: [
{
paths: '/api',
target,
},
],
})
```
Optional `.env`:
```env
DEV_PROXY_TARGET=https://cloud.example.com
DEV_PROXY_HOST=127.0.0.1
DEV_PROXY_PORT=5001
```
Command:
```bash
dev-proxy --config ./dev-proxy.config.ts --env-file ./.env.local
```
Edits to `./.env.local` reload the proxy automatically.
## Scenario 2: Proxy Two Route Groups To Two Local Backends
Use this when one frontend needs to talk to two different local services. For example:
- `/console/api/*` goes to a local console backend at `http://127.0.0.1:5001`
- `/api/*` goes to a local public API backend at `http://127.0.0.1:5002`
```ts
import { defineDevProxyConfig } from '@langgenius/dev-proxy'
const consoleApiTarget = process.env.DEV_PROXY_CONSOLE_API_TARGET || 'http://127.0.0.1:5001'
const publicApiTarget = process.env.DEV_PROXY_PUBLIC_API_TARGET || 'http://127.0.0.1:5002'
export default defineDevProxyConfig({
server: {
host: process.env.DEV_PROXY_HOST || '127.0.0.1',
port: Number(process.env.DEV_PROXY_PORT || 8082),
},
routes: [
{
paths: '/console/api',
target: consoleApiTarget,
},
{
paths: '/api',
target: publicApiTarget,
},
],
})
```
Optional `.env`:
```env
DEV_PROXY_CONSOLE_API_TARGET=http://127.0.0.1:5001
DEV_PROXY_PUBLIC_API_TARGET=http://127.0.0.1:5002
DEV_PROXY_HOST=127.0.0.1
DEV_PROXY_PORT=8082
```
When two route groups overlap, put the more specific one first:
```ts
routes: [
{ paths: '/api/enterprise', target: 'http://127.0.0.1:5003' },
{ paths: '/api', target: 'http://127.0.0.1:5002' },
]
```
## Cookie Rewrite
Cookie rewriting is opt-in and config-driven. The package does not know any application cookie names.
Use `cookieRewrite` when an upstream uses secure cookie prefixes such as `__Host-` or `__Secure-`, but local development needs cookies to work over `http://localhost`.
```ts
import type { CookieRewriteOptions } from '@langgenius/dev-proxy'
import { defineDevProxyConfig } from '@langgenius/dev-proxy'
const cookieRewrite: CookieRewriteOptions = {
hostPrefixCookies: ['access_token', 'refresh_token', /^passport-/],
}
export default defineDevProxyConfig({
routes: [
{
paths: '/api',
target: 'https://cloud.example.com',
cookieRewrite,
},
],
})
```
Set `cookieRewrite: false` to disable cookie rewriting for a route.
When one local proxy can point to multiple online targets, use `localCookieScope: 'target-origin'`
for auth cookies. The proxy stores configured cookies under target-specific local names,
forwards only the active target's cookies upstream, and can override a stale frontend CSRF
header from the active scoped cookie:
```ts
const cookieRewrite: CookieRewriteOptions = {
hostPrefixCookies: ['access_token', 'csrf_token', 'refresh_token'],
localCookieScope: 'target-origin',
csrfHeader: {
cookieName: 'csrf_token',
headerName: 'X-CSRF-Token',
},
}
```
## Session Import
Some upstreams cannot be signed in to from a local origin, for example when the login form is protected by a captcha bound to the upstream hostname. `sessionImport` moves an existing upstream session into the local proxy instead.
```ts
sessionImport: {
refreshPath: '/console/api/refresh-token',
cookieName: 'refresh_token',
redirectTo: 'http://localhost:3000',
}
```
The proxy serves an import page at its root, `http://localhost:<port>/`, and prints that URL on startup. Open it on the same host the frontend uses to call the proxy, because the imported cookies belong to that host.
1. Sign in on the upstream site, then in DevTools → Network right-click any API request → Copy → Copy as cURL.
2. Paste it into the import page. The proxy reads `cookieName` from the pasted text, sends it to `refreshPath` through the route that matches that path, stores the returned cookies with that route's `cookieRewrite`, and redirects to `redirectTo`.
The upstream rotates the pasted refresh token during the import, so only the local session can keep refreshing. The browser session it was copied from stops refreshing once its access token expires.
## Behavior
- The proxy preserves the matched path prefix when forwarding requests.
- WebSocket Upgrade requests use the same routes, targets, origin policy, and cookie rewriting.
- Request bodies are forwarded as streams.
- Hop-by-hop headers are removed before forwarding.
- Local credentialed CORS and preflight requests are handled by the proxy.
- Route matching is explicit and order-sensitive.
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
import '../dist/cli.mjs'
@@ -0,0 +1,45 @@
{
"name": "@langgenius/dev-proxy",
"version": "0.0.5",
"bin": {
"dev-proxy": "./bin/dev-proxy.js"
},
"files": [
"bin",
"dist",
"src"
],
"type": "module",
"types": "./dist/index.d.mts",
"exports": {
".": {
"types": "./dist/index.d.mts",
"import": "./dist/index.mjs"
}
},
"scripts": {
"build": "vp pack",
"prepare": "pnpm run build",
"test": "vp test",
"type-check": "tsrs --noEmit",
"prepublish": "pnpm run build"
},
"dependencies": {
"@hono/node-server": "catalog:",
"c12": "catalog:",
"chokidar": "catalog:",
"hono": "catalog:"
},
"devDependencies": {
"@dify/tsconfig": "workspace:*",
"@types/node": "catalog:",
"@typescript/native": "catalog:",
"tsrs": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vite-plus": "catalog:"
},
"engines": {
"node": "^24.22.1"
}
}
@@ -0,0 +1,274 @@
/**
* @vitest-environment node
*/
import type { ChildProcessByStdio } from 'node:child_process'
import type { Server } from 'node:http'
import type { Readable } from 'node:stream'
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import fs from 'node:fs/promises'
import http from 'node:http'
import net from 'node:net'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it } from 'vite-plus/test'
const tempDirs: string[] = []
type DevProxyCliProcess = ChildProcessByStdio<null, Readable, Readable>
const childProcesses: DevProxyCliProcess[] = []
const httpServers: Server[] = []
const binPath = fileURLToPath(new URL('../bin/dev-proxy.js', import.meta.url))
const createTempDir = async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'dev-proxy-cli-test-'))
tempDirs.push(tempDir)
return tempDir
}
const getFreePort = async () => {
const server = net.createServer()
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', resolve)
})
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Failed to allocate a test port.')
const { port } = address
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) reject(error)
else resolve()
})
})
return port
}
const waitForOutput = (child: DevProxyCliProcess, output: () => string, expectedOutput: string) =>
new Promise<void>((resolve, reject) => {
let timeout: ReturnType<typeof setTimeout>
function cleanup() {
clearTimeout(timeout)
child.stdout.off('data', onData)
child.stderr.off('data', onData)
child.off('exit', onExit)
}
function onData() {
if (!output().includes(expectedOutput)) return
cleanup()
resolve()
}
function onExit(code: number | null, signal: NodeJS.Signals | null) {
cleanup()
reject(
new Error(
`dev-proxy exited before writing "${expectedOutput}" with code ${code} and signal ${signal}. Output:\n${output()}`,
),
)
}
timeout = setTimeout(() => {
cleanup()
reject(new Error(`Timed out waiting for "${expectedOutput}". Output:\n${output()}`))
}, 3000)
child.stdout.on('data', onData)
child.stderr.on('data', onData)
child.once('exit', onExit)
onData()
})
const fetchTextWithRetry = async (url: string) => {
let lastError: unknown
for (let attempt = 0; attempt < 10; attempt += 1) {
try {
const response = await fetch(url)
return response.text()
} catch (error) {
lastError = error
await new Promise((resolve) => setTimeout(resolve, 50))
}
}
throw lastError instanceof Error
? lastError
: new Error('Fetching the proxy response failed with a non-Error value.', { cause: lastError })
}
const spawnCli = (args: readonly string[], cwd: string) => {
const child = spawn(process.execPath, [binPath, ...args], {
cwd,
env: {
...process.env,
FORCE_COLOR: '0',
},
stdio: ['ignore', 'pipe', 'pipe'],
})
childProcesses.push(child)
return child
}
const stopChildProcess = async (child: DevProxyCliProcess) => {
if (child.exitCode !== null || child.signalCode !== null) return
child.kill('SIGTERM')
await once(child, 'exit')
}
const closeHttpServer = async (server: Server) => {
if (!server.listening) return
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) reject(error)
else resolve()
})
})
}
const startTextServer = async (body: string) => {
const server = http.createServer((_, response) => {
response.writeHead(200, { 'content-type': 'text/plain' })
response.end(body)
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', resolve)
})
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Failed to start test server.')
httpServers.push(server)
return {
port: address.port,
}
}
describe('dev proxy CLI', () => {
afterEach(async () => {
await Promise.all(childProcesses.splice(0).map(stopChildProcess))
await Promise.all(httpServers.splice(0).map(closeHttpServer))
await Promise.all(
tempDirs.splice(0).map((tempDir) =>
fs.rm(tempDir, {
force: true,
recursive: true,
}),
),
)
})
// Scenario: help output should still be a normal short-lived command.
it('should print help and exit', async () => {
// Arrange
const tempDir = await createTempDir()
const child = spawnCli(['--help'], tempDir)
// Act
const [code] = await once(child, 'exit')
// Assert
expect(code).toBe(0)
})
// Scenario: successful server startup should keep the CLI process alive.
it('should keep running after starting the proxy server', async () => {
// Arrange
const tempDir = await createTempDir()
const port = await getFreePort()
await fs.writeFile(
path.join(tempDir, 'dev-proxy.config.ts'),
`
export default {
routes: [{ paths: '/api', target: 'https://api.example.com' }],
}
`,
)
let output = ''
const child = spawnCli(
['--config', './dev-proxy.config.ts', '--host', '127.0.0.1', '--port', String(port)],
tempDir,
)
child.stdout.on('data', (chunk) => (output += chunk.toString()))
child.stderr.on('data', (chunk) => (output += chunk.toString()))
// Act
await waitForOutput(child, () => output, `[dev-proxy] listening on http://127.0.0.1:${port}`)
await new Promise((resolve) => setTimeout(resolve, 100))
const response = await fetch(`http://127.0.0.1:${port}/not-proxied`)
// Assert
expect(child.exitCode).toBeNull()
expect(child.signalCode).toBeNull()
expect(response.status).toBe(404)
})
// Scenario: editing the configured env file should reload route targets without restarting the CLI process.
it('should reload proxy config when the env file changes', async () => {
// Arrange
const tempDir = await createTempDir()
const port = await getFreePort()
const firstTarget = await startTextServer('first target')
const secondTarget = await startTextServer('second target')
await fs.writeFile(
path.join(tempDir, '.env.proxy'),
`DEV_PROXY_TEST_TARGET=http://127.0.0.1:${firstTarget.port}\n`,
)
await fs.writeFile(
path.join(tempDir, 'dev-proxy.config.ts'),
`
export default {
routes: [{ paths: '/api', target: process.env.DEV_PROXY_TEST_TARGET }],
}
`,
)
let output = ''
const child = spawnCli(
[
'--config',
'./dev-proxy.config.ts',
'--env-file',
'./.env.proxy',
'--host',
'127.0.0.1',
'--port',
String(port),
],
tempDir,
)
child.stdout.on('data', (chunk) => (output += chunk.toString()))
child.stderr.on('data', (chunk) => (output += chunk.toString()))
const proxyUrl = `http://127.0.0.1:${port}/api/ping`
// Act
await waitForOutput(child, () => output, `[dev-proxy] listening on http://127.0.0.1:${port}`)
const firstResponse = await fetchTextWithRetry(proxyUrl)
await fs.writeFile(
path.join(tempDir, '.env.proxy'),
`DEV_PROXY_TEST_TARGET=http://127.0.0.1:${secondTarget.port}\n`,
)
await waitForOutput(child, () => output, '[dev-proxy] reloaded env file changes')
const secondResponse = await fetchTextWithRetry(proxyUrl)
// Assert
expect(firstResponse).toBe('first target')
expect(secondResponse).toBe('second target')
expect(child.exitCode).toBeNull()
expect(child.signalCode).toBeNull()
})
})
@@ -0,0 +1,184 @@
import type { ServerType } from '@hono/node-server'
import type { Duplex } from 'node:stream'
import type { DevProxyCliOptions, DevProxyConfig } from './types'
import process from 'node:process'
import { serve } from '@hono/node-server'
import { watch } from 'chokidar'
import {
assertDevProxyConfig,
loadDevProxyConfig,
parseDevProxyCliArgs,
resolveDevProxyServerOptions,
watchDevProxyConfig,
} from './config'
import { createDevProxyApp, createWebSocketUpgradeHandler } from './server'
const LOCALHOST_ALIASES = new Set(['127.0.0.1', '::1', '[::1]', '0.0.0.0', '::', '[::]'])
function printUsage() {
console.log(`Usage:
dev-proxy --config <path> [options]
Options:
--config, -c <path> Path to a dev proxy config file. Defaults to dev-proxy.config.ts.
--env-file <path> Load environment variables before evaluating the config file.
--host <host> Override the configured host.
--port <port> Override the configured port.
--watch Reload config and env file changes. Enabled by default.
--no-watch Disable config and env file reloads.
--help, -h Show this help message.`)
}
async function flushStandardStreams() {
await Promise.all([
new Promise<void>((resolve) => process.stdout.write('', () => resolve())),
new Promise<void>((resolve) => process.stderr.write('', () => resolve())),
])
}
const closeServer = (server: ServerType) =>
new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) reject(error)
else resolve()
})
})
const startDevProxyServer = (config: DevProxyConfig, cliOptions: DevProxyCliOptions) => {
let app = createDevProxyApp(config)
let handleWebSocketUpgrade = createWebSocketUpgradeHandler(config)
const upgradedSockets = new Set<Duplex>()
const { host, port } = resolveDevProxyServerOptions(config.server, cliOptions)
const server = serve({
fetch: (request, env) => app.fetch(request, env),
hostname: host,
port,
})
server.on('upgrade', (request, socket, head) => {
upgradedSockets.add(socket)
socket.once('close', () => upgradedSockets.delete(socket))
handleWebSocketUpgrade(request, socket, head)
})
return {
host,
port,
server,
close() {
upgradedSockets.forEach((socket) => socket.destroy())
upgradedSockets.clear()
return closeServer(server)
},
updateConfig(nextConfig: DevProxyConfig) {
app = createDevProxyApp(nextConfig)
handleWebSocketUpgrade = createWebSocketUpgradeHandler(nextConfig)
},
}
}
const createDevProxyRuntime = (initialConfig: DevProxyConfig, cliOptions: DevProxyCliOptions) => {
let runtime = startDevProxyServer(initialConfig, cliOptions)
let reloadTask = Promise.resolve()
console.log(`[dev-proxy] listening on http://${runtime.host}:${runtime.port}`)
if (initialConfig.sessionImport) {
const sessionImportHost = LOCALHOST_ALIASES.has(runtime.host) ? 'localhost' : runtime.host
console.log(`[dev-proxy] import session at http://${sessionImportHost}:${runtime.port}/`)
}
const reload = async (nextConfig: unknown, reason: string) => {
assertDevProxyConfig(nextConfig)
const nextServerOptions = resolveDevProxyServerOptions(nextConfig.server, cliOptions)
if (runtime.host === nextServerOptions.host && runtime.port === nextServerOptions.port) {
runtime.updateConfig(nextConfig)
console.log(`[dev-proxy] reloaded ${reason}`)
return
}
await runtime.close()
runtime = startDevProxyServer(nextConfig, cliOptions)
console.log(`[dev-proxy] restarted on http://${runtime.host}:${runtime.port} after ${reason}`)
}
const enqueueReload = (loadConfig: () => Promise<unknown> | unknown, reason: string) => {
reloadTask = reloadTask.then(async () => {
try {
await reload(await loadConfig(), reason)
} catch (error) {
console.error(`[dev-proxy] failed to reload ${reason}`)
console.error(error instanceof Error ? error.message : error)
}
})
return reloadTask
}
return {
enqueueReload,
close: async () => {
await reloadTask
await runtime.close()
},
}
}
async function main() {
const cliOptions = parseDevProxyCliArgs(process.argv.slice(2))
if (cliOptions.help) {
printUsage()
return
}
const config = await loadDevProxyConfig(cliOptions.config, process.cwd(), {
envFile: cliOptions.envFile,
})
const runtime = createDevProxyRuntime(config, cliOptions)
if (cliOptions.watch === false) return
const configWatcher = await watchDevProxyConfig(cliOptions.config, process.cwd(), {
envFile: cliOptions.envFile,
onUpdate: ({ newConfig }) => runtime.enqueueReload(() => newConfig.config, 'config changes'),
})
const envWatcher = cliOptions.envFile
? watch(cliOptions.envFile, {
cwd: process.cwd(),
ignoreInitial: true,
})
: undefined
envWatcher?.on('all', () => {
void runtime.enqueueReload(
() =>
loadDevProxyConfig(cliOptions.config, process.cwd(), {
envFile: cliOptions.envFile,
}),
'env file changes',
)
})
const cleanup = async () => {
await envWatcher?.close()
await configWatcher.unwatch()
await runtime.close()
}
process.once('SIGINT', () => {
void cleanup().finally(() => process.exit(0))
})
process.once('SIGTERM', () => {
void cleanup().finally(() => process.exit(0))
})
}
try {
await main()
await flushStandardStreams()
} catch (error) {
console.error(error instanceof Error ? error.message : error)
await flushStandardStreams()
process.exit(1)
}
@@ -0,0 +1,162 @@
/**
* @vitest-environment node
*/
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vite-plus/test'
import { loadDevProxyConfig, parseDevProxyCliArgs, resolveDevProxyServerOptions } from './config'
const tempDirs: string[] = []
const createTempDir = async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'dev-proxy-test-'))
tempDirs.push(tempDir)
return tempDir
}
describe('dev proxy config', () => {
afterEach(async () => {
delete process.env.DEV_PROXY_TEST_PORT
delete process.env.DEV_PROXY_TEST_TARGET
await Promise.all(
tempDirs.splice(0).map((tempDir) =>
fs.rm(tempDir, {
force: true,
recursive: true,
}),
),
)
})
// Scenario: CLI options should support both inline and separated values.
it('should parse proxy CLI options', () => {
// Act
const options = parseDevProxyCliArgs([
'--config=./dev-proxy.config.ts',
'--env-file',
'./.env.proxy',
'--host',
'0.0.0.0',
'--port',
'8083',
'--no-watch',
])
// Assert
expect(options).toEqual({
config: './dev-proxy.config.ts',
envFile: './.env.proxy',
host: '0.0.0.0',
port: '8083',
watch: false,
})
})
// Scenario: removed target shortcuts should fail instead of silently doing the wrong thing.
it('should reject unsupported target shortcuts', () => {
// Assert
expect(() => parseDevProxyCliArgs(['--target', 'enterprise'])).toThrow(
'Unsupported dev proxy option',
)
})
// Scenario: package manager argument separators should not be treated as proxy options.
it('should ignore package manager argument separators', () => {
// Act
const options = parseDevProxyCliArgs(['--config', './dev-proxy.config.ts', '--', '--help'])
// Assert
expect(options).toEqual({
config: './dev-proxy.config.ts',
help: true,
})
})
// Scenario: CLI host and port should override config defaults.
it('should resolve server options with CLI overrides', () => {
// Act
const options = resolveDevProxyServerOptions(
{
host: '127.0.0.1',
port: 5001,
},
{
host: '0.0.0.0',
port: '9002',
},
)
// Assert
expect(options).toEqual({
host: '0.0.0.0',
port: 9002,
})
})
// Scenario: TS config files should load through c12.
it('should load a TypeScript config file', async () => {
// Arrange
const tempDir = await createTempDir()
await fs.writeFile(
path.join(tempDir, 'dev-proxy.config.ts'),
`
export default {
server: { host: '127.0.0.1', port: 7777 },
routes: [{ paths: ['/api', '/files'], target: 'https://api.example.com' }],
}
`,
)
// Act
const config = await loadDevProxyConfig('dev-proxy.config.ts', tempDir)
// Assert
expect(config.server).toEqual({
host: '127.0.0.1',
port: 7777,
})
expect(config.routes).toEqual([
{
paths: ['/api', '/files'],
target: 'https://api.example.com',
},
])
})
// Scenario: env files should be loaded before the TypeScript config is evaluated.
it('should load a TypeScript config file with env file values', async () => {
// Arrange
const tempDir = await createTempDir()
await fs.writeFile(
path.join(tempDir, '.env.proxy'),
['DEV_PROXY_TEST_PORT=7788', 'DEV_PROXY_TEST_TARGET=https://env.example.com'].join('\n'),
)
await fs.writeFile(
path.join(tempDir, 'dev-proxy.config.ts'),
`
export default {
server: { port: Number(process.env.DEV_PROXY_TEST_PORT) },
routes: [{ paths: '/api', target: process.env.DEV_PROXY_TEST_TARGET }],
}
`,
)
// Act
const config = await loadDevProxyConfig('dev-proxy.config.ts', tempDir, {
envFile: '.env.proxy',
})
// Assert
expect(config.server).toEqual({
port: 7788,
})
expect(config.routes).toEqual([
{
paths: '/api',
target: 'https://env.example.com',
},
])
})
})
@@ -0,0 +1,163 @@
import type { DotenvOptions, LoadConfigOptions, WatchConfigOptions } from 'c12'
import type {
DevProxyCliOptions,
DevProxyConfig,
DevProxyConfigLoadOptions,
DevProxyServerConfig,
ResolvedDevProxyServerOptions,
} from './types'
import path from 'node:path'
import { loadConfig, watchConfig } from 'c12'
const DEFAULT_CONFIG_FILE = 'dev-proxy.config.ts'
const DEFAULT_PROXY_HOST = '127.0.0.1'
const DEFAULT_PROXY_PORT = 5001
const OPTION_NAME_TO_KEY = {
'--config': 'config',
'-c': 'config',
'--env-file': 'envFile',
'--host': 'host',
'--port': 'port',
} as const
type OptionName = keyof typeof OPTION_NAME_TO_KEY
const isOptionName = (value: string): value is OptionName => value in OPTION_NAME_TO_KEY
const requireOptionValue = (name: string, value?: string) => {
if (!value || value.startsWith('-')) throw new Error(`Missing value for ${name}.`)
return value
}
export const parseDevProxyCliArgs = (argv: readonly string[]): DevProxyCliOptions => {
const options: DevProxyCliOptions = {}
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index]!
if (arg === '--') continue
if (arg === '--help' || arg === '-h') {
options.help = true
continue
}
if (arg === '--watch') {
options.watch = true
continue
}
if (arg === '--no-watch') {
options.watch = false
continue
}
const [rawName, inlineValue] = arg.split('=', 2)
const name = rawName ?? ''
if (!name.startsWith('-')) continue
if (!isOptionName(name)) throw new Error(`Unsupported dev proxy option "${name}".`)
const key = OPTION_NAME_TO_KEY[name]
options[key] = inlineValue ?? requireOptionValue(name, argv[index + 1])
if (inlineValue === undefined) index += 1
}
return options
}
const resolvePort = (rawPort: string | number) => {
const port = Number(rawPort)
if (!Number.isInteger(port) || port < 1 || port > 65535)
throw new Error(`Invalid proxy port "${rawPort}". Expected an integer between 1 and 65535.`)
return port
}
export const resolveDevProxyServerOptions = (
serverConfig: DevProxyServerConfig = {},
cliOptions: DevProxyCliOptions = {},
): ResolvedDevProxyServerOptions => {
const configuredPort = cliOptions.port ?? serverConfig.port ?? DEFAULT_PROXY_PORT
return {
host: cliOptions.host || serverConfig.host || DEFAULT_PROXY_HOST,
port: resolvePort(configuredPort),
}
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
export function assertDevProxyConfig(config: unknown): asserts config is DevProxyConfig {
if (!isRecord(config)) throw new Error('Dev proxy config must export an object.')
if (!Array.isArray(config.routes))
throw new Error('Dev proxy config must include a routes array.')
}
const resolveDotenvOptions = (
envFile: DevProxyConfigLoadOptions['envFile'],
cwd: string,
): DotenvOptions | false => {
if (!envFile) return false
const resolvedEnvFilePath = path.resolve(cwd, envFile)
return {
cwd: path.dirname(resolvedEnvFilePath),
fileName: path.basename(resolvedEnvFilePath),
interpolate: true,
}
}
const createC12ConfigOptions = (
configPath = DEFAULT_CONFIG_FILE,
cwd = process.cwd(),
options: DevProxyConfigLoadOptions = {},
): LoadConfigOptions<DevProxyConfig> => {
const resolvedConfigPath = path.resolve(cwd, configPath)
const parsedPath = path.parse(resolvedConfigPath)
return {
configFile: parsedPath.name,
cwd: parsedPath.dir,
dotenv: resolveDotenvOptions(options.envFile, cwd),
envName: false,
globalRc: false,
packageJson: false,
rcFile: false,
}
}
export const loadDevProxyConfig = async (
configPath = DEFAULT_CONFIG_FILE,
cwd = process.cwd(),
options: DevProxyConfigLoadOptions = {},
): Promise<DevProxyConfig> => {
const { config: loadedConfig } = await loadConfig({
...createC12ConfigOptions(configPath, cwd, options),
})
assertDevProxyConfig(loadedConfig)
return loadedConfig
}
export const watchDevProxyConfig = async (
configPath = DEFAULT_CONFIG_FILE,
cwd = process.cwd(),
options: DevProxyConfigLoadOptions & Pick<WatchConfigOptions<DevProxyConfig>, 'onUpdate'> = {},
) => {
const watcher = await watchConfig<DevProxyConfig>({
...createC12ConfigOptions(configPath, cwd, options),
onUpdate: options.onUpdate,
})
assertDevProxyConfig(watcher.config)
return watcher
}
export const defineDevProxyConfig = (config: DevProxyConfig) => config
@@ -0,0 +1,110 @@
/**
* @vitest-environment node
*/
import { describe, expect, it } from 'vite-plus/test'
import {
getCookieHeaderValue,
rewriteCookieHeaderForUpstream,
rewriteSetCookieHeadersForLocal,
toScopedLocalCookieName,
} from './cookies'
describe('dev proxy cookies', () => {
// Scenario: cookie names should only receive secure host prefixes when configured.
it('should rewrite configured cookie names for HTTPS upstream requests', () => {
// Act
const cookieHeader = rewriteCookieHeaderForUpstream(
'access_token=abc; theme=dark; passport-app=def',
{
hostPrefixCookies: ['access_token', /^passport-/],
useHostPrefix: true,
},
)
// Assert
expect(cookieHeader).toBe('__Host-access_token=abc; theme=dark; __Host-passport-app=def')
})
// Scenario: HTTP upstreams should keep local cookie names even when rewrite config exists.
it('should keep local cookie names for HTTP upstream requests', () => {
// Act
const cookieHeader = rewriteCookieHeaderForUpstream('access_token=abc; refresh_token=def', {
hostPrefixCookies: ['access_token', 'refresh_token'],
useHostPrefix: false,
})
// Assert
expect(cookieHeader).toBe('access_token=abc; refresh_token=def')
})
// Scenario: upstream set-cookie headers should be converted into localhost-safe cookies.
it('should rewrite upstream set-cookie headers for local development', () => {
// Act
const cookies = rewriteSetCookieHeadersForLocal([
'__Host-access_token=abc; Path=/console/api; Domain=cloud.example.com; Secure; SameSite=None; Partitioned',
])
// Assert
expect(cookies).toEqual(['access_token=abc; Path=/; SameSite=Lax'])
})
// Scenario: target-scoped cookies should isolate authentication state between upstream targets.
it('should only forward auth cookies from the active local scope', () => {
// Arrange
const activeAccessTokenName = toScopedLocalCookieName('access_token', 'active')
const otherAccessTokenName = toScopedLocalCookieName('access_token', 'other')
// Act
const cookieHeader = rewriteCookieHeaderForUpstream(
[
`${activeAccessTokenName}=active-token`,
'access_token=legacy-token',
`${otherAccessTokenName}=other-token`,
'theme=dark',
].join('; '),
{
hostPrefixCookies: ['access_token'],
localScopeKey: 'active',
useHostPrefix: true,
},
)
// Assert
expect(cookieHeader).toBe('__Host-access_token=active-token; theme=dark')
})
// Scenario: upstream auth set-cookie headers should be stored under scoped local names.
it('should rewrite upstream set-cookie headers into target-scoped local cookies', () => {
// Arrange
const scopedAccessTokenName = toScopedLocalCookieName('access_token', 'cloud')
// Act
const cookies = rewriteSetCookieHeadersForLocal(
[
'__Host-access_token=abc; Path=/console/api; Domain=cloud.example.com; Secure; SameSite=None; Partitioned',
],
{
hostPrefixCookies: ['access_token'],
localScopeKey: 'cloud',
},
)
// Assert
expect(cookies).toEqual([`${scopedAccessTokenName}=abc; Path=/; SameSite=Lax`])
})
// Scenario: request header helpers should read scoped CSRF cookies without exposing scope logic to callers.
it('should read scoped cookie values from cookie headers', () => {
// Arrange
const scopedCsrfCookieName = toScopedLocalCookieName('csrf_token', 'cloud')
// Act
const csrfToken = getCookieHeaderValue(
`${scopedCsrfCookieName}=csrf; csrf_token=legacy`,
scopedCsrfCookieName,
)
// Assert
expect(csrfToken).toBe('csrf')
})
})
@@ -0,0 +1,173 @@
import type { CookieRewriteOptions } from './types'
const SECURE_COOKIE_PREFIX_PATTERN = /^__(Host|Secure)-/
const LOCAL_SCOPED_COOKIE_PREFIX = 'dev_proxy'
const SAME_SITE_NONE_PATTERN = /^samesite=none$/i
const COOKIE_PATH_PATTERN = /^path=/i
const COOKIE_DOMAIN_PATTERN = /^domain=/i
const COOKIE_SECURE_PATTERN = /^secure$/i
const COOKIE_PARTITIONED_PATTERN = /^partitioned$/i
const stripSecureCookiePrefix = (cookieName: string) =>
cookieName.replace(SECURE_COOKIE_PREFIX_PATTERN, '')
const matchesCookieName = (cookieName: string, matcher: string | RegExp) =>
typeof matcher === 'string' ? matcher === cookieName : matcher.test(cookieName)
const hashScope = (scope: string) => {
let hash = 0x811c9dc5
for (let index = 0; index < scope.length; index += 1) {
hash ^= scope.charCodeAt(index)
hash = Math.imul(hash, 0x01000193)
}
return (hash >>> 0).toString(36)
}
const shouldUseHostPrefix = (cookieName: string, options: CookieRewriteOptions) => {
const normalizedCookieName = stripSecureCookiePrefix(cookieName)
return (
options.hostPrefixCookies?.some((matcher) =>
matchesCookieName(normalizedCookieName, matcher),
) || false
)
}
const toUpstreamCookieName = (cookieName: string, options: CookieRewriteOptions) => {
if (cookieName.startsWith('__Host-')) return cookieName
if (cookieName.startsWith('__Secure-')) return `__Host-${stripSecureCookiePrefix(cookieName)}`
if (!shouldUseHostPrefix(cookieName, options)) return cookieName
return `__Host-${cookieName}`
}
export const toLocalCookieName = (cookieName: string) => stripSecureCookiePrefix(cookieName)
export const resolveCookieRewriteLocalScopeKey = (
options: CookieRewriteOptions,
targetUrl: URL,
) => {
if (options.localCookieScope === 'target-origin') return hashScope(targetUrl.origin)
return undefined
}
export const toScopedLocalCookieName = (cookieName: string, localScopeKey: string) =>
`${LOCAL_SCOPED_COOKIE_PREFIX}_${localScopeKey}_${toLocalCookieName(cookieName)}`
const fromScopedLocalCookieName = (cookieName: string, localScopeKey: string) => {
const scopedPrefix = `${LOCAL_SCOPED_COOKIE_PREFIX}_${localScopeKey}_`
if (!cookieName.startsWith(scopedPrefix)) return undefined
return cookieName.slice(scopedPrefix.length)
}
const isScopedLocalCookieName = (cookieName: string) =>
cookieName.startsWith(`${LOCAL_SCOPED_COOKIE_PREFIX}_`)
const parseCookieHeader = (cookieHeader: string | undefined) => {
if (!cookieHeader) return []
return cookieHeader
.split(/;\s*/)
.filter(Boolean)
.map((cookie) => {
const separatorIndex = cookie.indexOf('=')
if (separatorIndex === -1) return { name: cookie, value: undefined }
return {
name: cookie.slice(0, separatorIndex).trim(),
value: cookie.slice(separatorIndex + 1),
}
})
}
export const getCookieHeaderValue = (cookieHeader: string | undefined, cookieName: string) => {
const cookie = parseCookieHeader(cookieHeader).find((cookie) => cookie.name === cookieName)
return cookie?.value
}
export const rewriteCookieHeaderForUpstream = (
cookieHeader: string | undefined,
options: CookieRewriteOptions & { useHostPrefix?: boolean; localScopeKey?: string },
) => {
if (!cookieHeader) return cookieHeader
const { useHostPrefix = true } = options
return parseCookieHeader(cookieHeader)
.map((cookie) => {
if (cookie.value === undefined) return cookie.name
const scopedCookieName = options.localScopeKey
? fromScopedLocalCookieName(cookie.name, options.localScopeKey)
: undefined
if (scopedCookieName) {
const upstreamCookieName = useHostPrefix
? toUpstreamCookieName(scopedCookieName, options)
: scopedCookieName
return `${upstreamCookieName}=${cookie.value}`
}
if (
options.localScopeKey &&
(isScopedLocalCookieName(cookie.name) || shouldUseHostPrefix(cookie.name, options))
)
return undefined
const upstreamCookieName = useHostPrefix
? toUpstreamCookieName(cookie.name, options)
: cookie.name
return `${upstreamCookieName}=${cookie.value}`
})
.filter((cookie): cookie is string => Boolean(cookie))
.join('; ')
}
const rewriteSetCookieValueForLocal = (
setCookieValue: string,
options?: CookieRewriteOptions & { localScopeKey?: string },
) => {
const [rawCookiePair, ...rawAttributes] = setCookieValue.split(';')
const separatorIndex = rawCookiePair!.indexOf('=')
if (separatorIndex === -1) return setCookieValue
const cookieName = rawCookiePair!.slice(0, separatorIndex).trim()
const cookieValue = rawCookiePair!.slice(separatorIndex + 1)
const localCookieName = toLocalCookieName(cookieName)
const shouldScopeCookie = Boolean(
options?.localScopeKey && shouldUseHostPrefix(cookieName, options),
)
const rewrittenCookieName = shouldScopeCookie
? toScopedLocalCookieName(cookieName, options!.localScopeKey!)
: localCookieName
const rewrittenAttributes = rawAttributes
.map((attribute) => attribute.trim())
.filter(
(attribute) =>
!COOKIE_DOMAIN_PATTERN.test(attribute) &&
!COOKIE_SECURE_PATTERN.test(attribute) &&
!COOKIE_PARTITIONED_PATTERN.test(attribute),
)
.map((attribute) => {
if (SAME_SITE_NONE_PATTERN.test(attribute)) return 'SameSite=Lax'
if (COOKIE_PATH_PATTERN.test(attribute)) return 'Path=/'
return attribute
})
return [`${rewrittenCookieName}=${cookieValue}`, ...rewrittenAttributes].join('; ')
}
export const rewriteSetCookieHeadersForLocal = (
setCookieHeaders: readonly string[],
options?: CookieRewriteOptions & { localScopeKey?: string },
) => setCookieHeaders.map((cookie) => rewriteSetCookieValueForLocal(cookie, options))
@@ -0,0 +1,32 @@
export {
assertDevProxyConfig,
defineDevProxyConfig,
loadDevProxyConfig,
parseDevProxyCliArgs,
resolveDevProxyServerOptions,
} from './config'
export {
rewriteCookieHeaderForUpstream,
rewriteSetCookieHeadersForLocal,
toLocalCookieName,
} from './cookies'
export {
buildUpstreamUrl,
createDevProxyApp,
isAllowedDevOrigin,
isAllowedLocalDevOrigin,
} from './server'
export type {
CookieNameMatcher,
CookieRewriteOptions,
CreateDevProxyAppOptions,
DevProxyCliOptions,
DevProxyConfig,
DevProxyConfigLoadOptions,
DevProxyCorsAllowedOrigins,
DevProxyCorsConfig,
DevProxyRoute,
DevProxyServerConfig,
DevProxySessionImportConfig,
ResolvedDevProxyServerOptions,
} from './types'
@@ -0,0 +1,595 @@
/**
* @vitest-environment node
*/
import { Buffer } from 'node:buffer'
import http from 'node:http'
import net from 'node:net'
import { PassThrough } from 'node:stream'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { resolveCookieRewriteLocalScopeKey, toScopedLocalCookieName } from './cookies'
import {
buildUpstreamUrl,
createDevProxyApp,
createWebSocketUpgradeHandler,
isAllowedDevOrigin,
} from './server'
const listen = (server: http.Server) =>
new Promise<number>((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', () => {
const address = server.address()
if (!address || typeof address === 'string') {
reject(new Error('Failed to start test server.'))
return
}
resolve(address.port)
})
})
const close = (server: http.Server) =>
new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) reject(error)
else resolve()
})
})
describe('dev proxy server', () => {
beforeEach(() => {
vi.clearAllMocks()
})
// Scenario: target paths should not be duplicated when the incoming route already includes them.
it('should preserve prefixed targets when building upstream URLs', () => {
// Act
const url = buildUpstreamUrl(
'https://api.example.com/console/api',
'/console/api/apps',
'?page=1',
)
// Assert
expect(url.href).toBe('https://api.example.com/console/api/apps?page=1')
})
// Scenario: only localhost dev origins should be reflected for credentialed CORS by default.
it('should only allow local development origins by default', () => {
// Assert
expect(isAllowedDevOrigin('http://localhost:3000')).toBe(true)
expect(isAllowedDevOrigin('http://127.0.0.1:3000')).toBe(true)
expect(isAllowedDevOrigin('https://example.com')).toBe(false)
})
// Scenario: explicit CORS origins should support non-local development hosts.
it('should allow explicitly configured origins', () => {
// Assert
expect(isAllowedDevOrigin('https://app.example.com', ['https://app.example.com'])).toBe(true)
expect(isAllowedDevOrigin('https://other.example.com', ['https://app.example.com'])).toBe(false)
})
// Scenario: proxy requests should rewrite cookies and surface credentialed CORS headers when configured.
it('should proxy api requests with configured local cookie rewriting', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(
new Response('ok', {
status: 200,
headers: [
['content-encoding', 'br'],
['content-length', '123'],
[
'set-cookie',
'__Host-access_token=abc; Path=/console/api; Domain=cloud.example.com; Secure; SameSite=None',
],
['transfer-encoding', 'chunked'],
],
}),
)
const app = createDevProxyApp({
routes: [
{
paths: '/console/api',
target: 'https://cloud.example.com',
cookieRewrite: {
hostPrefixCookies: ['access_token'],
},
},
],
fetchImpl,
})
// Act
const response = await app.request('http://127.0.0.1:5001/console/api/apps?page=1', {
headers: {
Origin: 'http://localhost:3000',
Cookie: 'access_token=abc; theme=dark',
'Accept-Encoding': 'zstd, br, gzip',
},
})
// Assert
expect(fetchImpl).toHaveBeenCalledTimes(1)
expect(fetchImpl).toHaveBeenCalledWith(
new URL('https://cloud.example.com/console/api/apps?page=1'),
expect.objectContaining({
method: 'GET',
headers: expect.any(Headers),
}),
)
const requestHeaders = fetchImpl.mock.calls[0]?.[1]?.headers
if (!(requestHeaders instanceof Headers))
throw new Error('Expected proxy request headers to be Headers')
expect(requestHeaders.get('cookie')).toBe('__Host-access_token=abc; theme=dark')
expect(requestHeaders.get('origin')).toBe('https://cloud.example.com')
expect(requestHeaders.get('accept-encoding')).toBe('identity')
expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:3000')
expect(response.headers.get('access-control-allow-credentials')).toBe('true')
expect(response.headers.get('content-encoding')).toBeNull()
expect(response.headers.get('content-length')).toBeNull()
expect(response.headers.get('transfer-encoding')).toBeNull()
expect(response.headers.getSetCookie()).toEqual(['access_token=abc; Path=/; SameSite=Lax'])
})
// Scenario: generic proxy routes should not know Dify cookie names by default.
it('should not rewrite cookie names when cookie rewriting is not configured', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(new Response('ok'))
const app = createDevProxyApp({
routes: [
{
paths: '/api',
target: 'https://api.example.com',
},
],
fetchImpl,
})
// Act
await app.request('http://127.0.0.1:5001/api/messages', {
headers: {
Cookie: 'access_token=abc; refresh_token=def',
},
})
// Assert
const requestHeaders = fetchImpl.mock.calls[0]?.[1]?.headers
if (!(requestHeaders instanceof Headers))
throw new Error('Expected proxy request headers to be Headers')
expect(requestHeaders.get('cookie')).toBe('access_token=abc; refresh_token=def')
})
// Scenario: local HTTP upstreams expect local cookie names even when cookie rewriting is configured.
it('should keep local cookie names for HTTP upstream targets', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(new Response('ok'))
const app = createDevProxyApp({
routes: [
{
paths: '/console/api',
target: 'http://127.0.0.1:5001',
cookieRewrite: {
hostPrefixCookies: ['access_token', 'refresh_token'],
},
},
],
fetchImpl,
})
// Act
await app.request('http://127.0.0.1:5010/console/api/account/profile', {
headers: {
Cookie: 'access_token=abc; refresh_token=def',
},
})
// Assert
const requestHeaders = fetchImpl.mock.calls[0]?.[1]?.headers
if (!(requestHeaders instanceof Headers))
throw new Error('Expected proxy request headers to be Headers')
expect(requestHeaders.get('cookie')).toBe('access_token=abc; refresh_token=def')
})
// Scenario: scoped Dify auth cookies should prevent stale local cookies from leaking across targets.
it('should proxy target-scoped auth cookies and override stale CSRF headers', async () => {
// Arrange
const cookieRewrite = {
hostPrefixCookies: ['access_token', 'csrf_token', 'refresh_token'],
localCookieScope: 'target-origin' as const,
csrfHeader: {
cookieName: 'csrf_token',
headerName: 'X-CSRF-Token',
},
}
const targetUrl = new URL('https://cloud.example.com')
const localScopeKey = resolveCookieRewriteLocalScopeKey(cookieRewrite, targetUrl)!
const accessTokenCookieName = toScopedLocalCookieName('access_token', localScopeKey)
const csrfTokenCookieName = toScopedLocalCookieName('csrf_token', localScopeKey)
const otherScopeAccessTokenCookieName = toScopedLocalCookieName('access_token', 'other')
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(
new Response('ok', {
status: 200,
headers: [
[
'set-cookie',
'__Host-access_token=next; Path=/console/api; Domain=cloud.example.com; Secure; SameSite=None',
],
],
}),
)
const app = createDevProxyApp({
routes: [
{
paths: '/console/api',
target: targetUrl.origin,
cookieRewrite,
},
],
fetchImpl,
})
// Act
const response = await app.request('http://127.0.0.1:5001/console/api/apps', {
headers: {
Cookie: [
`${accessTokenCookieName}=current-access`,
`${csrfTokenCookieName}=current-csrf`,
'access_token=legacy-access',
'csrf_token=legacy-csrf',
`${otherScopeAccessTokenCookieName}=other-access`,
'theme=dark',
].join('; '),
'X-CSRF-Token': 'legacy-csrf',
},
})
// Assert
const requestHeaders = fetchImpl.mock.calls[0]?.[1]?.headers
if (!(requestHeaders instanceof Headers))
throw new Error('Expected proxy request headers to be Headers')
expect(requestHeaders.get('cookie')).toBe(
'__Host-access_token=current-access; __Host-csrf_token=current-csrf; theme=dark',
)
expect(requestHeaders.get('x-csrf-token')).toBe('current-csrf')
expect(response.headers.getSetCookie()).toEqual([
`${accessTokenCookieName}=next; Path=/; SameSite=Lax`,
])
})
// Scenario: custom route paths should support independent upstream targets.
it('should proxy custom route paths to their configured targets', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(new Response('ok'))
const app = createDevProxyApp({
routes: [
{
paths: '/api',
target: 'https://api.example.com',
},
{
paths: '/files',
target: 'https://files.example.com/assets',
},
],
fetchImpl,
})
// Act
await app.request('http://127.0.0.1:5001/api/messages')
await app.request('http://127.0.0.1:5001/files/logo.png?size=small')
// Assert
expect(fetchImpl.mock.calls.map(([url]) => url.toString())).toEqual([
'https://api.example.com/api/messages',
'https://files.example.com/assets/files/logo.png?size=small',
])
})
// Scenario: Socket.IO collaboration must reuse the auth cookies stored by the local dev proxy.
it('should proxy WebSocket upgrades with the configured cookie rewriting', async () => {
// Arrange
const sockets = new Set<net.Socket>()
let upstreamRequest:
| {
connection: string | undefined
cookie: string | undefined
keepAlive: string | string[] | undefined
origin: string | undefined
proxyAuthorization: string | undefined
te: string | string[] | undefined
upgrade: string | undefined
url: string | undefined
xHop: string | string[] | undefined
}
| undefined
const upstreamServer = http.createServer()
upstreamServer.on('connection', (socket) => sockets.add(socket))
upstreamServer.on('upgrade', (request, socket) => {
upstreamRequest = {
connection: request.headers.connection,
cookie: request.headers.cookie,
keepAlive: request.headers['keep-alive'],
origin: request.headers.origin,
proxyAuthorization: request.headers['proxy-authorization'],
te: request.headers.te,
upgrade: request.headers.upgrade,
url: request.url,
xHop: request.headers['x-hop'],
}
socket.write(
[
'HTTP/1.1 101 Switching Protocols',
'Connection: Upgrade, X-Upstream-Hop',
'Upgrade: websocket',
'X-Upstream-Hop: upstream-only',
'Keep-Alive: timeout=5',
'Proxy-Authenticate: Basic realm="proxy"',
'Set-Cookie: __Host-access_token=next; Path=/socket.io; Domain=cloud.example.com; Secure; SameSite=None',
'Set-Cookie: __Secure-refresh_token=renewed; Path=/socket.io; Domain=cloud.example.com; Secure; HttpOnly',
'',
'proxied websocket',
].join('\r\n'),
)
})
const upstreamPort = await listen(upstreamServer)
const upstreamOrigin = `http://127.0.0.1:${upstreamPort}`
const cookieRewrite = {
hostPrefixCookies: ['access_token', 'refresh_token'],
localCookieScope: 'target-origin' as const,
}
const localScopeKey = resolveCookieRewriteLocalScopeKey(cookieRewrite, new URL(upstreamOrigin))!
const accessTokenCookieName = toScopedLocalCookieName('access_token', localScopeKey)
const refreshTokenCookieName = toScopedLocalCookieName('refresh_token', localScopeKey)
const proxyServer = http.createServer()
proxyServer.on(
'upgrade',
createWebSocketUpgradeHandler({
routes: [{ paths: '/socket.io', target: upstreamOrigin, cookieRewrite }],
}),
)
const proxyPort = await listen(proxyServer)
const client = net.connect(proxyPort, '127.0.0.1')
sockets.add(client)
try {
// Act
const response = await new Promise<string>((resolve, reject) => {
let value = ''
const timeout = setTimeout(
() => reject(new Error('Timed out waiting for WebSocket upgrade response.')),
3000,
)
client.setEncoding('utf8')
client.on('connect', () => {
client.write(
[
'GET /socket.io/?EIO=4&transport=websocket HTTP/1.1',
`Host: 127.0.0.1:${proxyPort}`,
'Connection: Upgrade, X-Hop',
'Upgrade: websocket',
'X-Hop: client-only',
'Keep-Alive: timeout=5',
'Proxy-Authorization: Basic secret',
'TE: trailers',
'Origin: http://localhost:3000',
`Cookie: ${accessTokenCookieName}=secret`,
'',
'',
].join('\r\n'),
)
})
client.on('data', (chunk) => {
value += chunk
if (!value.includes('proxied websocket')) return
clearTimeout(timeout)
resolve(value)
})
client.on('error', (error) => {
clearTimeout(timeout)
reject(error)
})
})
// Assert
expect(response).toContain('101 Switching Protocols')
expect(response).toContain('proxied websocket')
expect(response).toContain('Connection: Upgrade\r\n')
expect(response).toContain('Upgrade: websocket\r\n')
expect(response).not.toMatch(/X-Upstream-Hop:/i)
expect(response).not.toMatch(/Keep-Alive:/i)
expect(response).not.toMatch(/Proxy-Authenticate:/i)
expect(response).toContain(`Set-Cookie: ${accessTokenCookieName}=next; Path=/; SameSite=Lax`)
expect(response).toContain(`Set-Cookie: ${refreshTokenCookieName}=renewed; Path=/; HttpOnly`)
expect(response).not.toContain('__Host-access_token')
expect(response).not.toContain('__Secure-refresh_token')
expect(upstreamRequest).toEqual({
connection: 'Upgrade',
cookie: 'access_token=secret',
keepAlive: undefined,
origin: upstreamOrigin,
proxyAuthorization: undefined,
te: undefined,
upgrade: 'websocket',
url: '/socket.io/?EIO=4&transport=websocket',
xHop: undefined,
})
} finally {
sockets.forEach((socket) => socket.destroy())
await Promise.all([close(proxyServer), close(upstreamServer)])
}
})
// Scenario: invalid route targets should fail the individual Upgrade request, not the proxy process.
it('should return a bad gateway response when a WebSocket target is invalid', async () => {
// Arrange
const logger = { error: vi.fn() }
const clientSocket = new PassThrough()
const request = {
headers: {},
method: 'GET',
url: '/socket.io/?EIO=4&transport=websocket',
} as http.IncomingMessage
let response = ''
clientSocket.setEncoding('utf8')
clientSocket.on('data', (chunk) => {
response += chunk
})
const handleUpgrade = createWebSocketUpgradeHandler({
routes: [{ paths: '/socket.io', target: 'not a URL' }],
logger,
})
// Act
expect(() => handleUpgrade(request, clientSocket, Buffer.alloc(0))).not.toThrow()
await new Promise<void>((resolve) => clientSocket.once('finish', resolve))
// Assert
expect(response).toContain('502 Bad Gateway')
expect(logger.error).toHaveBeenCalledOnce()
})
// Scenario: parsed chunked bodies need close-delimited framing when an Upgrade is rejected upstream.
it('should safely forward chunked non-upgrade responses', async () => {
// Arrange
const sockets = new Set<net.Socket>()
const upstreamServer = http.createServer()
upstreamServer.on('connection', (socket) => sockets.add(socket))
upstreamServer.on('upgrade', (_request, socket) => {
socket.end(
[
'HTTP/1.1 401 Unauthorized',
'Connection: keep-alive',
'Transfer-Encoding: chunked',
'Content-Type: text/plain',
'',
'6',
'denied',
'0',
'',
'',
].join('\r\n'),
)
})
const upstreamPort = await listen(upstreamServer)
const proxyServer = http.createServer()
proxyServer.on(
'upgrade',
createWebSocketUpgradeHandler({
routes: [{ paths: '/socket.io', target: `http://127.0.0.1:${upstreamPort}` }],
}),
)
const proxyPort = await listen(proxyServer)
const client = net.connect(proxyPort, '127.0.0.1')
sockets.add(client)
try {
// Act
const response = await new Promise<string>((resolve, reject) => {
let value = ''
const timeout = setTimeout(
() => reject(new Error('Timed out waiting for rejected Upgrade response.')),
3000,
)
client.setEncoding('utf8')
client.on('connect', () => {
client.write(
[
'GET /socket.io/?EIO=4&transport=websocket HTTP/1.1',
`Host: 127.0.0.1:${proxyPort}`,
'Connection: Upgrade',
'Upgrade: websocket',
'',
'',
].join('\r\n'),
)
})
client.on('data', (chunk) => {
value += chunk
})
client.on('end', () => {
clearTimeout(timeout)
resolve(value)
})
client.on('error', (error) => {
clearTimeout(timeout)
reject(error)
})
})
// Assert
expect(response).toContain('401 Unauthorized')
expect(response).toContain('Connection: close')
expect(response).not.toMatch(/Transfer-Encoding:/i)
expect(response.endsWith('\r\n\r\ndenied')).toBe(true)
} finally {
sockets.forEach((socket) => socket.destroy())
await Promise.all([close(proxyServer), close(upstreamServer)])
}
})
// Scenario: routes are matched in config order so callers can put specific routes first.
it('should prefer earlier route entries', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(new Response('ok'))
const app = createDevProxyApp({
routes: [
{
paths: '/api/enterprise',
target: 'https://enterprise.example.com',
},
{
paths: '/api',
target: 'https://api.example.com',
},
],
fetchImpl,
})
// Act
await app.request('http://127.0.0.1:5001/api/enterprise/sso/login')
// Assert
expect(fetchImpl.mock.calls.map(([url]) => url.toString())).toEqual([
'https://enterprise.example.com/api/enterprise/sso/login',
])
})
// Scenario: preflight requests should advertise allowed headers for credentialed cross-origin calls.
it('should answer CORS preflight requests', async () => {
// Arrange
const app = createDevProxyApp({
routes: [
{
paths: '/api',
target: 'https://api.example.com',
},
],
fetchImpl: vi.fn<typeof fetch>(),
})
// Act
const response = await app.request('http://127.0.0.1:5001/api/messages', {
method: 'OPTIONS',
headers: {
Origin: 'http://localhost:3000',
'Access-Control-Request-Headers': 'authorization,content-type,x-csrf-token',
},
})
// Assert
expect(response.status).toBe(204)
expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:3000')
expect(response.headers.get('access-control-allow-credentials')).toBe('true')
expect(response.headers.get('access-control-allow-headers')).toBe(
'authorization,content-type,x-csrf-token',
)
})
})
@@ -0,0 +1,572 @@
import type { Context, Hono } from 'hono'
import type { Buffer } from 'node:buffer'
import type { IncomingMessage } from 'node:http'
import type { Duplex } from 'node:stream'
import type {
CookieRewriteOptions,
CreateDevProxyAppOptions,
DevProxyCorsAllowedOrigins,
DevProxyRoute,
DevProxySessionImportConfig,
} from './types'
import { request as httpRequest } from 'node:http'
import { request as httpsRequest } from 'node:https'
import { Hono as HonoApp } from 'hono'
import {
getCookieHeaderValue,
resolveCookieRewriteLocalScopeKey,
rewriteCookieHeaderForUpstream,
rewriteSetCookieHeadersForLocal,
toScopedLocalCookieName,
} from './cookies'
import { extractSessionCookieValue, sessionImportPageResponse } from './session-import'
const LOCAL_DEV_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])
const ALLOW_METHODS = 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS'
const DEFAULT_ALLOW_HEADERS = 'Authorization, Content-Type, X-CSRF-Token'
const UPSTREAM_ACCEPT_ENCODING = 'identity'
const HOP_BY_HOP_HEADERS = [
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailer',
'transfer-encoding',
'upgrade',
] as const
const DECODED_RESPONSE_HEADERS_TO_DROP = ['content-encoding', 'content-length'] as const
const createHopByHopHeaderNames = (connectionHeader?: string | null) =>
new Set([
...HOP_BY_HOP_HEADERS,
...(connectionHeader
?.split(',')
.map((header) => header.trim().toLowerCase())
.filter(Boolean) || []),
])
const removeHopByHopHeaders = (headers: Headers) => {
createHopByHopHeaderNames(headers.get('connection')).forEach((header) => headers.delete(header))
}
const appendHeaderValue = (headers: Headers, name: string, value: string) => {
const currentValue = headers.get(name)
if (!currentValue) {
headers.set(name, value)
return
}
if (
currentValue
.split(',')
.map((item) => item.trim())
.includes(value)
)
return
headers.set(name, `${currentValue}, ${value}`)
}
export const isAllowedLocalDevOrigin = (origin?: string | null) => {
if (!origin) return false
try {
const url = new URL(origin)
return LOCAL_DEV_HOSTS.has(url.hostname)
} catch {
return false
}
}
export const isAllowedDevOrigin = (
origin?: string | null,
allowedOrigins: DevProxyCorsAllowedOrigins = 'local',
) => {
if (!origin) return false
if (allowedOrigins === 'local') return isAllowedLocalDevOrigin(origin)
return allowedOrigins.includes(origin)
}
const applyCorsHeaders = (
headers: Headers,
origin: string | undefined | null,
allowedOrigins: DevProxyCorsAllowedOrigins = 'local',
) => {
if (!isAllowedDevOrigin(origin, allowedOrigins)) return
headers.set('Access-Control-Allow-Origin', origin!)
headers.set('Access-Control-Allow-Credentials', 'true')
appendHeaderValue(headers, 'Vary', 'Origin')
}
export const buildUpstreamUrl = (target: string, requestPath: string, search = '') => {
const targetUrl = new URL(target)
const normalizedTargetPath =
targetUrl.pathname === '/' ? '' : targetUrl.pathname.replace(/\/$/, '')
const normalizedRequestPath = requestPath.startsWith('/') ? requestPath : `/${requestPath}`
const hasTargetPrefix =
normalizedTargetPath &&
(normalizedRequestPath === normalizedTargetPath ||
normalizedRequestPath.startsWith(`${normalizedTargetPath}/`))
targetUrl.pathname = hasTargetPrefix
? normalizedRequestPath
: `${normalizedTargetPath}${normalizedRequestPath}`
targetUrl.search = search
return targetUrl
}
const createProxyRequestHeaders = (
headers: Headers,
targetUrl: URL,
cookieRewrite: CookieRewriteOptions | false | undefined,
) => {
const upstreamHeaders = new Headers(headers)
removeHopByHopHeaders(upstreamHeaders)
upstreamHeaders.delete('host')
upstreamHeaders.set('accept-encoding', UPSTREAM_ACCEPT_ENCODING)
if (upstreamHeaders.has('origin')) upstreamHeaders.set('origin', targetUrl.origin)
if (cookieRewrite) {
const originalCookieHeader = upstreamHeaders.get('cookie') || undefined
const localScopeKey = resolveCookieRewriteLocalScopeKey(cookieRewrite, targetUrl)
const rewrittenCookieHeader = rewriteCookieHeaderForUpstream(
upstreamHeaders.get('cookie') || undefined,
{
...cookieRewrite,
localScopeKey,
useHostPrefix: targetUrl.protocol === 'https:',
},
)
if (rewrittenCookieHeader) upstreamHeaders.set('cookie', rewrittenCookieHeader)
else upstreamHeaders.delete('cookie')
if (localScopeKey && cookieRewrite.csrfHeader) {
const scopedCsrfCookieName = toScopedLocalCookieName(
cookieRewrite.csrfHeader.cookieName,
localScopeKey,
)
const scopedCsrfToken = getCookieHeaderValue(originalCookieHeader, scopedCsrfCookieName)
if (scopedCsrfToken) upstreamHeaders.set(cookieRewrite.csrfHeader.headerName, scopedCsrfToken)
else upstreamHeaders.delete(cookieRewrite.csrfHeader.headerName)
}
}
return upstreamHeaders
}
const getSetCookieHeaders = (headers: Headers) => {
const headersWithGetSetCookie = headers as Headers & { getSetCookie?: () => string[] }
const setCookieHeaders = headersWithGetSetCookie.getSetCookie?.()
if (setCookieHeaders?.length) return setCookieHeaders
const setCookie = headers.get('set-cookie')
return setCookie ? [setCookie] : []
}
const createUpstreamResponseHeaders = (
response: Response,
targetUrl: URL,
requestOrigin: string | undefined | null,
allowedOrigins: DevProxyCorsAllowedOrigins,
cookieRewrite: CookieRewriteOptions | false | undefined,
) => {
const headers = new Headers(response.headers)
removeHopByHopHeaders(headers)
DECODED_RESPONSE_HEADERS_TO_DROP.forEach((header) => headers.delete(header))
headers.delete('set-cookie')
const localScopeKey = cookieRewrite
? resolveCookieRewriteLocalScopeKey(cookieRewrite, targetUrl)
: undefined
const setCookieHeaders = getSetCookieHeaders(response.headers)
const responseSetCookieHeaders = cookieRewrite
? rewriteSetCookieHeadersForLocal(setCookieHeaders, {
...cookieRewrite,
localScopeKey,
})
: setCookieHeaders
responseSetCookieHeaders.forEach((cookie) => {
headers.append('set-cookie', cookie)
})
applyCorsHeaders(headers, requestOrigin, allowedOrigins)
return headers
}
const proxyRequest = async (
context: Context,
route: DevProxyRoute,
fetchImpl: typeof globalThis.fetch,
allowedOrigins: DevProxyCorsAllowedOrigins,
) => {
const requestUrl = new URL(context.req.url)
const targetUrl = buildUpstreamUrl(route.target, requestUrl.pathname, requestUrl.search)
const requestHeaders = createProxyRequestHeaders(
context.req.raw.headers,
targetUrl,
route.cookieRewrite,
)
const requestInit: RequestInit & { duplex?: 'half' } = {
method: context.req.method,
headers: requestHeaders,
redirect: 'manual',
}
if (context.req.method !== 'GET' && context.req.method !== 'HEAD') {
requestInit.body = context.req.raw.body
requestInit.duplex = 'half'
}
const upstreamResponse = await fetchImpl(targetUrl, requestInit)
const responseHeaders = createUpstreamResponseHeaders(
upstreamResponse,
targetUrl,
context.req.header('origin'),
allowedOrigins,
route.cookieRewrite,
)
return new Response(upstreamResponse.body, {
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
headers: responseHeaders,
})
}
const normalizeRoutePaths = (paths: DevProxyRoute['paths']) =>
Array.isArray(paths) ? paths : [paths]
const findProxyRoute = (routes: readonly DevProxyRoute[], requestPath: string) =>
routes.find((route) =>
normalizeRoutePaths(route.paths).some(
(routePath) => requestPath === routePath || requestPath.startsWith(`${routePath}/`),
),
)
const createHeadersFromIncomingMessage = (request: IncomingMessage) => {
const headers = new Headers()
Object.entries(request.headers).forEach(([name, value]) => {
if (Array.isArray(value)) value.forEach((item) => headers.append(name, item))
else if (value !== undefined) headers.set(name, value)
})
return headers
}
type ResponseHeader = readonly [name: string, value: string]
const createIncomingResponseHeaders = (
response: IncomingMessage,
targetUrl: URL,
cookieRewrite: CookieRewriteOptions | false | undefined,
connectionMode: 'close' | 'upgrade',
) => {
const headers: ResponseHeader[] = []
const setCookieHeaders: string[] = []
const headersToDrop = createHopByHopHeaderNames(response.headers.connection)
for (let index = 0; index < response.rawHeaders.length; index += 2) {
const name = response.rawHeaders[index]
const value = response.rawHeaders[index + 1]
if (!name || value === undefined) continue
const normalizedName = name.toLowerCase()
if (normalizedName === 'set-cookie') setCookieHeaders.push(value)
else if (!headersToDrop.has(normalizedName)) headers.push([name, value])
}
const localScopeKey = cookieRewrite
? resolveCookieRewriteLocalScopeKey(cookieRewrite, targetUrl)
: undefined
const responseSetCookieHeaders = cookieRewrite
? rewriteSetCookieHeadersForLocal(setCookieHeaders, {
...cookieRewrite,
localScopeKey,
})
: setCookieHeaders
responseSetCookieHeaders.forEach((cookie) => headers.push(['Set-Cookie', cookie]))
if (connectionMode === 'upgrade') {
headers.push(['Connection', 'Upgrade'])
headers.push(['Upgrade', response.headers.upgrade || 'websocket'])
} else {
headers.push(['Connection', 'close'])
}
return headers
}
const writeIncomingResponseHead = (
socket: Duplex,
response: IncomingMessage,
headers: readonly ResponseHeader[],
) => {
const statusCode = response.statusCode || 502
const statusMessage = response.statusMessage || 'Bad Gateway'
socket.write(`HTTP/1.1 ${statusCode} ${statusMessage}\r\n`)
headers.forEach(([name, value]) => socket.write(`${name}: ${value}\r\n`))
socket.write('\r\n')
}
const closeUpgradeRequest = (socket: Duplex, statusCode: number, statusMessage: string) => {
socket.end(
`HTTP/1.1 ${statusCode} ${statusMessage}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`,
)
}
export const createWebSocketUpgradeHandler = (
options: Pick<CreateDevProxyAppOptions, 'routes' | 'cors' | 'logger'>,
) => {
const logger = options.logger || console
const allowedOrigins = options.cors?.allowedOrigins || 'local'
const handleUpgrade = (request: IncomingMessage, clientSocket: Duplex, head: Buffer) => {
const requestOrigin = request.headers.origin
if (requestOrigin && !isAllowedDevOrigin(requestOrigin, allowedOrigins)) {
closeUpgradeRequest(clientSocket, 403, 'Forbidden')
return
}
const requestUrl = new URL(request.url || '/', 'http://localhost')
const route = findProxyRoute(options.routes, requestUrl.pathname)
if (!route) {
closeUpgradeRequest(clientSocket, 404, 'Not Found')
return
}
const targetUrl = buildUpstreamUrl(route.target, requestUrl.pathname, requestUrl.search)
const upgradeProtocol = request.headers.upgrade || 'websocket'
const requestHeaders = createProxyRequestHeaders(
createHeadersFromIncomingMessage(request),
targetUrl,
route.cookieRewrite,
)
requestHeaders.set('connection', 'Upgrade')
requestHeaders.set('upgrade', upgradeProtocol)
const requestImpl =
targetUrl.protocol === 'https:'
? httpsRequest
: targetUrl.protocol === 'http:'
? httpRequest
: undefined
if (!requestImpl) {
logger.error(
'[dev-proxy]',
new Error(`Unsupported proxy target protocol: ${targetUrl.protocol}`),
)
closeUpgradeRequest(clientSocket, 502, 'Bad Gateway')
return
}
const upstreamRequest = requestImpl(targetUrl, {
headers: Object.fromEntries(requestHeaders.entries()),
method: request.method,
})
let upstreamSocket: Duplex | undefined
const closeUpstream = () => {
if (upstreamSocket) upstreamSocket.destroy()
else upstreamRequest.destroy()
}
clientSocket.once('close', closeUpstream)
clientSocket.once('error', closeUpstream)
upstreamRequest.on('upgrade', (response, socket, upstreamHead) => {
upstreamSocket = socket
if (clientSocket.destroyed) {
socket.destroy()
return
}
const responseHeaders = createIncomingResponseHeaders(
response,
targetUrl,
route.cookieRewrite,
'upgrade',
)
writeIncomingResponseHead(clientSocket, response, responseHeaders)
if (upstreamHead.length) clientSocket.write(upstreamHead)
if (head.length) socket.write(head)
socket.once('error', () => clientSocket.destroy())
socket.once('close', () => clientSocket.destroy())
clientSocket.pipe(socket)
socket.pipe(clientSocket)
})
upstreamRequest.on('response', (response) => {
const responseHeaders = createIncomingResponseHeaders(
response,
targetUrl,
route.cookieRewrite,
'close',
)
writeIncomingResponseHead(clientSocket, response, responseHeaders)
response.once('error', () => clientSocket.destroy())
response.pipe(clientSocket)
})
upstreamRequest.on('error', (error) => {
logger.error('[dev-proxy]', error)
if (!clientSocket.destroyed) closeUpgradeRequest(clientSocket, 502, 'Bad Gateway')
})
upstreamRequest.end()
}
return (request: IncomingMessage, clientSocket: Duplex, head: Buffer) => {
try {
handleUpgrade(request, clientSocket, head)
} catch (error) {
logger.error('[dev-proxy]', error)
if (!clientSocket.destroyed) closeUpgradeRequest(clientSocket, 502, 'Bad Gateway')
}
}
}
const registerProxyRoute = (
app: Hono,
route: DevProxyRoute,
path: string,
fetchImpl: typeof globalThis.fetch,
allowedOrigins: DevProxyCorsAllowedOrigins,
) => {
if (!path.startsWith('/'))
throw new Error(`Invalid dev proxy route path "${path}". Paths must start with "/".`)
app.all(path, (context) => proxyRequest(context, route, fetchImpl, allowedOrigins))
app.all(`${path}/*`, (context) => proxyRequest(context, route, fetchImpl, allowedOrigins))
}
const registerProxyRoutes = (
app: Hono,
routes: readonly DevProxyRoute[],
fetchImpl: typeof globalThis.fetch,
allowedOrigins: DevProxyCorsAllowedOrigins,
) => {
routes.forEach((route) => {
normalizeRoutePaths(route.paths).forEach((path) => {
registerProxyRoute(app, route, path, fetchImpl, allowedOrigins)
})
})
}
const registerSessionImportRoute = (
app: Hono,
routes: readonly DevProxyRoute[],
config: DevProxySessionImportConfig,
fetchImpl: typeof globalThis.fetch,
) => {
const route = findProxyRoute(routes, config.refreshPath)
if (!route)
throw new Error(`No dev proxy route matches session import path "${config.refreshPath}".`)
const refreshUrl = buildUpstreamUrl(route.target, config.refreshPath)
app.get('/', () => sessionImportPageResponse(refreshUrl.origin))
app.post('/', async (context) => {
const requestOrigin = context.req.header('origin')
if (requestOrigin && requestOrigin !== new URL(context.req.url).origin)
return new Response('Cross-origin session import is not allowed.', { status: 403 })
const input = (await context.req.formData()).get('input')
const sessionCookieValue =
typeof input === 'string' ? extractSessionCookieValue(input, config.cookieName) : undefined
if (!sessionCookieValue)
return sessionImportPageResponse(
refreshUrl.origin,
`No ${config.cookieName} cookie found in the pasted text.`,
400,
)
const localScopeKey = route.cookieRewrite
? resolveCookieRewriteLocalScopeKey(route.cookieRewrite, refreshUrl)
: undefined
const localCookieName = localScopeKey
? toScopedLocalCookieName(config.cookieName, localScopeKey)
: config.cookieName
const localHeaders = new Headers({ cookie: `${localCookieName}=${sessionCookieValue}` })
const userAgent = context.req.header('user-agent')
if (userAgent) localHeaders.set('user-agent', userAgent)
const upstreamResponse = await fetchImpl(refreshUrl, {
method: 'POST',
headers: createProxyRequestHeaders(localHeaders, refreshUrl, route.cookieRewrite),
redirect: 'manual',
})
if (!upstreamResponse.ok)
return sessionImportPageResponse(
refreshUrl.origin,
`Refresh failed with ${upstreamResponse.status}: ${(await upstreamResponse.text()).slice(0, 300)}`,
502,
)
const setCookieHeaders = getSetCookieHeaders(upstreamResponse.headers)
if (!setCookieHeaders.length)
return sessionImportPageResponse(
refreshUrl.origin,
'Refresh succeeded but returned no cookies.',
502,
)
const headers = new Headers({ Location: config.redirectTo, 'Cache-Control': 'no-store' })
const localSetCookieHeaders = route.cookieRewrite
? rewriteSetCookieHeadersForLocal(setCookieHeaders, { ...route.cookieRewrite, localScopeKey })
: setCookieHeaders
localSetCookieHeaders.forEach((cookie) => headers.append('Set-Cookie', cookie))
return new Response(null, { status: 303, headers })
})
}
export const createDevProxyApp = (options: CreateDevProxyAppOptions) => {
const app = new HonoApp()
const fetchImpl = options.fetchImpl || globalThis.fetch
const logger = options.logger || console
const allowedOrigins = options.cors?.allowedOrigins || 'local'
app.onError((error, context) => {
logger.error('[dev-proxy]', error)
const headers = new Headers()
applyCorsHeaders(headers, context.req.header('origin'), allowedOrigins)
return new Response('Upstream proxy request failed.', {
status: 502,
headers,
})
})
app.use('*', async (context, next) => {
if (context.req.method === 'OPTIONS') {
const headers = new Headers()
applyCorsHeaders(headers, context.req.header('origin'), allowedOrigins)
headers.set('Access-Control-Allow-Methods', ALLOW_METHODS)
headers.set(
'Access-Control-Allow-Headers',
context.req.header('Access-Control-Request-Headers') || DEFAULT_ALLOW_HEADERS,
)
if (context.req.header('Access-Control-Request-Private-Network') === 'true')
headers.set('Access-Control-Allow-Private-Network', 'true')
return new Response(null, {
status: 204,
headers,
})
}
await next()
applyCorsHeaders(context.res.headers, context.req.header('origin'), allowedOrigins)
})
if (options.sessionImport)
registerSessionImportRoute(app, options.routes, options.sessionImport, fetchImpl)
registerProxyRoutes(app, options.routes, fetchImpl, allowedOrigins)
return app
}
@@ -0,0 +1,178 @@
/**
* @vitest-environment node
*/
import type { CookieRewriteOptions } from './types'
import { describe, expect, it, vi } from 'vite-plus/test'
import { resolveCookieRewriteLocalScopeKey, toScopedLocalCookieName } from './cookies'
import { createDevProxyApp } from './server'
import { extractSessionCookieValue } from './session-import'
const cookieRewrite: CookieRewriteOptions = {
hostPrefixCookies: ['access_token', 'refresh_token'],
localCookieScope: 'target-origin',
}
const createApp = (fetchImpl: typeof fetch) =>
createDevProxyApp({
routes: [{ paths: '/console/api', target: 'https://cloud.example.com', cookieRewrite }],
sessionImport: {
refreshPath: '/console/api/refresh-token',
cookieName: 'refresh_token',
redirectTo: 'http://localhost:3000',
},
fetchImpl,
})
const postInput = (input: string, headers: Record<string, string> = {}) =>
new Request('http://localhost:5001/', {
method: 'POST',
headers,
body: new URLSearchParams({ input }),
})
describe('session import', () => {
// Scenario: DevTools copies should yield the session cookie without manual trimming.
it('should extract the cookie value from pasted requests', () => {
// Assert
expect(
extractSessionCookieValue(
"curl 'https://cloud.example.com/console/api/apps' -b 'theme=dark; __Host-refresh_token=abc123; __Host-access_token=xyz'",
'refresh_token',
),
).toBe('abc123')
expect(extractSessionCookieValue('cookie: refresh_token=abc123', 'refresh_token')).toBe(
'abc123',
)
expect(extractSessionCookieValue(' abc123\n', 'refresh_token')).toBe('abc123')
expect(
extractSessionCookieValue('Cookie: webapp_refresh_token=nope; theme=dark', 'refresh_token'),
).toBeUndefined()
})
// Scenario: importing should rotate the pasted token upstream and store the new session locally.
it('should refresh upstream and set scoped local cookies', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(
new Response('{"result":"success"}', {
status: 200,
headers: [
['set-cookie', '__Host-access_token=new-access; Path=/; Secure; HttpOnly; SameSite=Lax'],
[
'set-cookie',
'__Host-refresh_token=new-refresh; Path=/; Secure; HttpOnly; SameSite=Lax',
],
],
}),
)
const scopeKey = resolveCookieRewriteLocalScopeKey(
cookieRewrite,
new URL('https://cloud.example.com'),
)!
// Act
const response = await createApp(fetchImpl).request(
postInput("curl 'x' -b '__Host-refresh_token=old-refresh'", {
origin: 'http://localhost:5001',
'user-agent': 'test-browser',
}),
)
// Assert
const [url, init] = fetchImpl.mock.calls[0]!
const upstreamHeaders = new Headers(init?.headers)
expect(String(url)).toBe('https://cloud.example.com/console/api/refresh-token')
expect(init?.method).toBe('POST')
expect(upstreamHeaders.get('cookie')).toBe('__Host-refresh_token=old-refresh')
expect(upstreamHeaders.get('user-agent')).toBe('test-browser')
expect(response.status).toBe(303)
expect(response.headers.get('location')).toBe('http://localhost:3000')
expect(response.headers.getSetCookie()).toEqual([
`${toScopedLocalCookieName('access_token', scopeKey)}=new-access; Path=/; HttpOnly; SameSite=Lax`,
`${toScopedLocalCookieName('refresh_token', scopeKey)}=new-refresh; Path=/; HttpOnly; SameSite=Lax`,
])
})
// Scenario: an expired or already-rotated token should be reported instead of redirecting.
it('should show the upstream error when refresh fails', async () => {
// Arrange
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response('Invalid refresh token', { status: 401 }))
// Act
const response = await createApp(fetchImpl).request(postInput('stale-token'))
// Assert
expect(response.status).toBe(502)
expect(response.headers.getSetCookie()).toEqual([])
expect(await response.text()).toContain('Refresh failed with 401: Invalid refresh token')
})
// Scenario: a successful refresh without cookies must not look like a completed import.
it('should show an error when refresh returns no cookies', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(new Response('{}', { status: 200 }))
// Act
const response = await createApp(fetchImpl).request(postInput('token'))
// Assert
expect(response.status).toBe(502)
expect(response.headers.get('location')).toBeNull()
expect(await response.text()).toContain('Refresh succeeded but returned no cookies.')
})
// Scenario: pasted text without the session cookie should be rejected before calling upstream.
it('should reject pasted text without the session cookie', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>()
// Act
const response = await createApp(fetchImpl).request(postInput('cookie: theme=dark'))
// Assert
expect(response.status).toBe(400)
expect(fetchImpl).not.toHaveBeenCalled()
expect(await response.text()).toContain('No refresh_token cookie found in the pasted text.')
})
// Scenario: the import page should link to the upstream that the refresh route targets.
it('should serve the import page at the proxy root', async () => {
// Act
const response = await createApp(vi.fn<typeof fetch>()).request('http://localhost:5001/')
// Assert
expect(response.status).toBe(200)
expect(await response.text()).toContain('href="https://cloud.example.com"')
})
// Scenario: a refresh path outside every route is a config error.
it('should throw when no route matches the refresh path', () => {
// Assert
expect(() =>
createDevProxyApp({
routes: [{ paths: '/api', target: 'https://cloud.example.com' }],
sessionImport: {
refreshPath: '/console/api/refresh-token',
cookieName: 'refresh_token',
redirectTo: 'http://localhost:3000',
},
}),
).toThrow('No dev proxy route matches session import path "/console/api/refresh-token".')
})
// Scenario: other sites must not be able to plant a session through the local proxy.
it('should reject cross-origin imports', async () => {
// Arrange
const fetchImpl = vi.fn<typeof fetch>()
// Act
const response = await createApp(fetchImpl).request(
postInput('token', { origin: 'https://evil.example.com' }),
)
// Assert
expect(response.status).toBe(403)
expect(fetchImpl).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,57 @@
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const escapeHtml = (value: string) =>
value.replace(
/[&<>"']/g,
(character) =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]!,
)
/**
* Accepts a whole request copied from DevTools ("Copy as cURL"), a Cookie header,
* or a bare cookie value, and returns the session cookie value.
*/
export const extractSessionCookieValue = (input: string, cookieName: string) => {
const text = input.trim()
const match = new RegExp(
`(?<![\\w-])(?:__Host-|__Secure-)?${escapeRegExp(cookieName)}=([^;\\s'"&^]+)`,
).exec(text)
if (match) return match[1]
return /^[^\s;=]+$/.test(text) ? text : undefined
}
export const sessionImportPageResponse = (targetOrigin: string, error?: string, status = 200) =>
new Response(
`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Import session</title>
<style>
body { font: 14px/1.5 system-ui, sans-serif; max-width: 640px; margin: 48px auto; padding: 0 16px; }
textarea { box-sizing: border-box; width: 100%; height: 160px; font: 12px ui-monospace, monospace; }
button { margin-top: 12px; padding: 6px 16px; }
p[role="alert"] { color: #b42318; }
</style>
</head>
<body>
<h1>Import session</h1>
<ol>
<li>Sign in on <a href="${escapeHtml(targetOrigin)}" target="_blank" rel="noreferrer">${escapeHtml(targetOrigin)}</a>.</li>
<li>In DevTools → Network, right-click any API request → Copy → Copy as cURL.</li>
<li>Paste it below. The session is rotated on import, so the copied browser session stops refreshing.</li>
</ol>
${error ? `<p role="alert">${escapeHtml(error)}</p>` : ''}
<form method="post">
<textarea name="input" autofocus required placeholder="curl '${escapeHtml(targetOrigin)}/…' -b '…'"></textarea>
<button type="submit">Import</button>
</form>
</body>
</html>`,
{
status,
headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' },
},
)
@@ -0,0 +1,65 @@
export type DevProxyServerConfig = {
host?: string
port?: number
}
export type DevProxyCorsAllowedOrigins = 'local' | readonly string[]
export type DevProxyCorsConfig = {
allowedOrigins?: DevProxyCorsAllowedOrigins
}
export type CookieNameMatcher = string | RegExp
export type CookieRewriteLocalScope = 'target-origin'
export type CookieRewriteOptions = {
hostPrefixCookies?: readonly CookieNameMatcher[]
localCookieScope?: CookieRewriteLocalScope
csrfHeader?: {
cookieName: string
headerName: string
}
}
export type DevProxyRoute = {
paths: string | readonly string[]
target: string
cookieRewrite?: CookieRewriteOptions | false
}
export type DevProxySessionImportConfig = {
refreshPath: string
cookieName: string
redirectTo: string
}
export type DevProxyConfig = {
server?: DevProxyServerConfig
routes: readonly DevProxyRoute[]
cors?: DevProxyCorsConfig
sessionImport?: DevProxySessionImportConfig
}
export type DevProxyCliOptions = {
config?: string
envFile?: string
host?: string
port?: string
watch?: boolean
help?: boolean
}
export type DevProxyConfigLoadOptions = {
envFile?: string | false
}
export type ResolvedDevProxyServerOptions = {
host: string
port: number
}
export type CreateDevProxyAppOptions = Pick<DevProxyConfig, 'routes' | 'cors' | 'sessionImport'> & {
fetchImpl?: typeof globalThis.fetch
logger?: Pick<Console, 'error'>
}
@@ -0,0 +1,8 @@
{
"extends": "@dify/tsconfig/node.json",
"compilerOptions": {
"types": ["node", "vite-plus/test/globals"]
},
"include": ["src/**/*.ts", "vite.config.ts"],
"exclude": ["node_modules", "dist"]
}
@@ -0,0 +1,18 @@
import { defineConfig } from 'vite-plus'
export default defineConfig({
pack: {
clean: true,
deps: { resolveDepSubpath: true, neverBundle: ['@hono/node-server', 'c12', 'hono'] },
entry: ['src/index.ts', 'src/cli.ts'],
format: ['esm'],
outDir: 'dist',
platform: 'node',
sourcemap: true,
target: 'node24',
treeshake: true,
},
test: {
environment: 'node',
},
})