使用 Claude Code 的 CORS 配置:来源控制与预检优化

发布: (2026年3月11日 GMT+8 12:56)
4 分钟阅读
原文: Dev.to

Source: Dev.to

请提供您希望翻译的具体内容(文本、段落或代码块),我将按照要求保留源链接并进行简体中文翻译。

CORS 配置规则

安全(必需)

  • 在生产环境中绝不能使用 Access-Control-Allow-Origin: *
  • 从环境变量加载允许的来源(不要硬编码)。
  • 使用凭证时,只允许特定来源(与 * 不兼容)。
  • 只允许明确需要的 HTTP 方法;例如,DELETE 必须显式列出。

预检

  • 在所有路由之前注册 CORS 中间件。
  • OPTIONS 请求返回 204(无响应体)。
  • 将预检响应缓存 24 小时max‑age=86400)。

头部

  • 允许的 请求头Content-TypeAuthorizationX-Request-ID
  • 需要暴露的 响应头X-Total-CountX-Request-ID

生成的 CORS 配置

src/middleware/cors.ts

// src/middleware/cors.ts
import cors from 'cors';

const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS?.split(',').map(o => o.trim()) ?? [];

export const corsMiddleware = cors({
  origin: (origin, callback) => {
    // Same‑origin or server‑to‑server requests have undefined origin
    if (!origin) return callback(null, true);

    if (ALLOWED_ORIGINS.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error(`CORS: origin ${origin} not allowed`));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID'],
  exposedHeaders: ['X-Total-Count', 'X-Request-ID'],
  maxAge: 86400,
});

src/app.ts

// src/app.ts
import express from 'express';
import { corsMiddleware } from './middleware/cors';

const app = express();

// CORS must be registered before all routes
app.use(corsMiddleware);

// Return 204 for OPTIONS preflight
app.options('*', corsMiddleware, (req, res) => {
  res.status(204).end();
});

app.use(express.json());

// ...other route handlers

多租户 CORS

src/middleware/dynamicCors.ts

// src/middleware/dynamicCors.ts
import { Request, Response, NextFunction } from 'express';
import redis from './redis';   // assume a configured Redis client
import prisma from './prisma'; // assume a configured Prisma client

async function getAllowedOrigins(tenantId: string): Promise {
  const cacheKey = `cors:tenant:${tenantId}`;

  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const tenant = await prisma.tenant.findUnique({
    where: { id: tenantId },
    select: { allowedOrigins: true },
  });

  const origins = tenant?.allowedOrigins ?? [];
  await redis.set(cacheKey, JSON.stringify(origins), { EX: 300 }); // 5 min TTL

  return origins;
}

export const dynamicCorsMiddleware = async (req: Request, res: Response, next: NextFunction) => {
  const tenantId = req.headers['x-tenant-id'] as string;
  const origin = req.headers.origin as string;

  if (!tenantId || !origin) return next();

  const allowedOrigins = await getAllowedOrigins(tenantId);

  if (allowedOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Vary', 'Origin'); // Prevent CDN/proxy cache pollution
  }

  next();
};

.env.example

# Comma‑separated list of allowed origins for production
ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com

# Development (uncomment as needed)
# ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173

设计说明

  • CLAUDE.md:强制在生产环境中不使用 *,从环境变量加载来源,并注明凭证限制。
  • Origin validation:实现为动态白名单检查;没有硬编码的值。
  • Vary header:已添加,以避免在每个请求来源不同的情况下导致 CDN/代理缓存污染。
  • Preflight cachemaxAge: 86400 减少不必要的 OPTIONS 往返请求。

如需进一步阅读 CORS 安全检查,请参阅 Security Pack(¥1,480),其中包括 /security-check 用于检测通配符来源、凭证泄漏以及缺失的 Vary 头。

Myouga (@myougatheaxo) – 专注于 API 安全的 Claude Code 工程师。

0 浏览
Back to Blog

相关文章

阅读更多 »