vite.config.ts 5.7 KB
import { defineConfig, loadEnv, type ProxyOptions } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url';
import fs from 'node:fs';
import path from 'node:path';
// 与浏览器侧共用同一份「代理/直连」推导逻辑,避免两侧默认值各自漂移导致错配
import { resolveApiMode } from './src/api/core/api-mode';

const localDevOrigins = new Set([
  'http://localhost:5173',
  'http://127.0.0.1:5173',
  'http://192.168.1.178:5173',
]);

// 密钥材料统一放在 src/api/core/keys/ 目录(与签名代码同层,内聚),不再写进 .env:
//   src/api/core/keys/client_private.pem —— 客户端私钥(请求加签)
//   src/api/core/keys/server_public.pem  —— 服务端公钥(响应验签)
// 构建期(Node 侧)读文件内容,经虚拟模块注入前端。
// 用文件而非 .env 的理由:PEM 是标准多行格式,可直接用 OpenSSL / 版本管理处理;
// 塞进 .env 既要拼字面量 \n 又极易手抄出错,两份内容还会各自漂移。
// 注意:*.pem 已在 .gitignore 忽略,切勿提交私钥。
const KEYS_DIR = path.resolve(process.cwd(), 'src/api/core/keys');

const KEY_MODULES: Record<string, { file: string; label: string }> = {
  'virtual:client-private-key': { file: 'client_private.pem', label: '客户端私钥' },
  'virtual:server-public-key': { file: 'server_public.pem', label: '服务端公钥' },
};

function readKeyFile(file: string): string {
  try {
    return fs.readFileSync(path.join(KEYS_DIR, file), 'utf8').trim();
  } catch {
    return '';
  }
}

function readKeys(): Record<string, string> {
  const out: Record<string, string> = {};
  for (const [id, { file }] of Object.entries(KEY_MODULES)) {
    out[id] = readKeyFile(file);
  }
  return out;
}

/**
 * 把 keys/ 下的 PEM 以虚拟模块形式注入前端。
 * 前端不通过 HTTP fetch .pem——避免 Vite server.fs 限制 / 本机安全软件对 .pem 的拦截。
 */
function virtualKeysPlugin(keys: Record<string, string>) {
  return {
    name: 'virtual-keys',
    resolveId(source: string) {
      return source in KEY_MODULES ? '\0' + source : null;
    },
    load(source: string) {
      const real = source.startsWith('\0') ? source.slice(1) : source;
      return real in keys ? `export default ${JSON.stringify(keys[real])};` : null;
    },
  };
}

/**
 * .env 系列文件、keys/ 下 PEM 变更后自动重启 dev server。
 * Vite 启动时才解析 .env / 读取 PEM 内容,不重启的话:
 * 切换 VITE_API_MODE 不生效(之前排查 10011 就踩过「改了 .env 但仍在跑旧配置」),
 * 换密钥也不会重新注入。
 */
function workspaceReloadPlugin(root: string, keysDir: string, keys: Record<string, string>) {
  const ENV_RE = /(^|[\\/])\.env(\.|$)/;
  const KEY_RE = /(^|[\\/])keys[\\/][^\\/]+\.pem$/i;
  return {
    name: 'workspace-reload',
    configureServer(server: any) {
      const mode = server.config.mode ?? 'development';
      const candidates = ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`].map((f) =>
        path.resolve(root, f),
      );
      server.watcher.add([...candidates, keysDir]);

      // 启动即体检:缺了密钥不会报错,只会变成登录失败 / 验签失效,很难查
      const missing = Object.entries(KEY_MODULES).filter(([id]) => !keys[id]);
      if (missing.length) {
        server.config.logger.warn(
          `\n  [keys] 缺失以下密钥文件(${keysDir}):\n` +
            missing.map(([, c]) => `         - ${c.file}(${c.label})`).join('\n') +
            `\n         登录加签或响应验签将失效\n`,
        );
      }

      server.watcher.on('change', async (file: string) => {
        if (!ENV_RE.test(file) && !KEY_RE.test(file)) return;
        server.config.logger.info(
          `\n  [reload] ${path.basename(file)} 已变更 → 重启 dev server\n`,
          { timestamp: true },
        );
        await server.restart();
      });
    },
  };
}

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const api = resolveApiMode(env);
  const KEYS = readKeys();
  return {
    plugins: [
      react(),
      virtualKeysPlugin(KEYS),
      workspaceReloadPlugin(process.cwd(), KEYS_DIR, KEYS),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        // 组件库源码直引:即使 workspace 软链未就绪(如 install 被中断),dev/构建也能解析
        '@uj/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)),
      },
    },
    server: {
      // 监听全部网卡(0.0.0.0),允许用 http://<本机IP>:5173 访问。
      // Vite 默认只绑 localhost(127.0.0.1),此时用局域网 IP 访问会连不上。
      // 注意:若公司网络/Windows 防火墙拦截 5173 入站,仍需放行该端口。
      host: '0.0.0.0',
      port: 5173,
      // 仅 proxy 模式挂载代理;direct 模式不挂,由浏览器直连后端(需后端开放 CORS)。
      // 代理转发前摘掉 /api,保证后端收到的 URI 与前端签名路径(canonical 第 2 行)一致。
      ...(api.useProxy
        ? {
            proxy: {
              '/api': {
                target: api.target,
                changeOrigin: true,
                rewrite: (p: string) => p.replace(/^\/api/, ''),
                configure(proxy) {
                  proxy.on('proxyReq', (proxyReq, req) => {
                    if (req.headers.origin && localDevOrigins.has(req.headers.origin)) {
                      proxyReq.setHeader('origin', api.target);
                    }
                  });
                },
              } satisfies ProxyOptions,
            },
          }
        : null),
    },
  };
});