mcpField
C
cors-configuration

cors-configuration

github.com/patricio0312rev開発63281 回インストール41 週間前に更新
リポジトリ

cors-configuration について

API や Web アプリのクロスオリジンリソース共有を設定するスキルです。許可するオリジン、プリフライト、認証情報、メソッド、ヘッダーを扱い、Express.js、Next.js、Fastify の例を含みます。

主な機能

  1. 01許可するオリジンとメソッドの設定
  2. 02プリフライトリクエストの処理
  3. 03認証情報と Cookie の設定
  4. 04オリジンの動的な検証
  5. 05CORS 動作のテスト

活用シーン

  1. 01オリジンごとの API アクセス制限
  2. 02認証情報付きクロスオリジンリクエストの設定
  3. 03Web アプリの CORS ルールのテスト

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/patricio0312rev/skills --skill cors-configuration

インストール後、Claude Code で/cors-configurationを入力して読み込まれたか確認します。

詳細

CORS の設定

API と Web アプリケーションで、安全なクロスオリジンリソース共有を設定します。

基本的なワークフロー

  1. オリジンを特定する:許可するオリジンを定義します
  2. ヘッダーを設定する:CORS レスポンスヘッダーを設定します
  3. プリフライトを処理する:OPTIONS リクエストを処理します
  4. 認証情報を設定する:Cookie と認証を処理します
  5. メソッドを制限する:許可する HTTP メソッドを指定します
  6. 設定をテストする:CORS が機能することを確認します

CORS ヘッダーのリファレンス

Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Request-ID
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Access-Control-Expose-Headers: X-Request-ID, X-RateLimit-Remaining

Express.js の設定

基本的な CORS
// middleware/cors.ts
import cors from 'cors';
import { Express } from 'express';

const allowedOrigins = [
  'https://app.example.com',
  'https://admin.example.com',
];

// Add development origins
if (process.env.NODE_ENV === 'development') {
  allowedOrigins.push('http://localhost:3000');
  allowedOrigins.push('http://localhost:5173');
}

export function configureCors(app: Express) {
  app.use(cors({
    origin: (origin, callback) => {
      // Allow requests with no origin (mobile apps, Postman)
      if (!origin) {
        return callback(null, true);
      }

      if (allowedOrigins.includes(origin)) {
        return callback(null, true);
      }

      callback(new Error('Not allowed by CORS'));
    },
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: [
      'Content-Type',
      'Authorization',
      'X-Request-ID',
      'X-CSRF-Token',
    ],
    exposedHeaders: [
      'X-Request-ID',
      'X-RateLimit-Limit',
      'X-RateLimit-Remaining',
    ],
    credentials: true,
    maxAge: 86400, // 24 hours
    preflightContinue: false,
    optionsSuccessStatus: 204,
  }));
}
手動での CORS ミドルウェア
// middleware/manual-cors.ts
import { Request, Response, NextFunction } from 'express';

interface CorsOptions {
  origins: string[];
  methods: string[];
  allowedHeaders: string[];
  exposedHeaders: string[];
  credentials: boolean;
  maxAge: number;
}

const defaultOptions: CorsOptions = {
  origins: [],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: [],
  credentials: false,
  maxAge: 86400,
};

export function createCorsMiddleware(options: Partial<CorsOptions> = {}) {
  const config = { ...defaultOptions, ...options };

  return (req: Request, res: Response, next: NextFunction) => {
    const origin = req.headers.origin;

    // Check if origin is allowed
    if (origin && config.origins.includes(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    } else if (config.origins.includes('*')) {
      res.setHeader('Access-Control-Allow-Origin', '*');
    }

    // Set other CORS headers
    res.setHeader('Access-Control-Allow-Methods', config.methods.join(', '));
    res.setHeader('Access-Control-Allow-Headers', config.allowedHeaders.join(', '));

    if (config.exposedHeaders.length > 0) {
      res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '));
    }

    if (config.credentials) {
      res.setHeader('Access-Control-Allow-Credentials', 'true');
    }

    res.setHeader('Access-Control-Max-Age', String(config.maxAge));

    // Handle preflight request
    if (req.method === 'OPTIONS') {
      res.status(204).end();
      return;
    }

    next();
  };
}
ルート固有の CORS
// routes/api.ts
import { Router } from 'express';
import cors from 'cors';

const router = Router();

// Public endpoints - allow any origin
const publicCors = cors({
  origin: '*',
  methods: ['GET'],
});

// Private endpoints - restrict origin
const privateCors = cors({
  origin: ['https://app.example.com'],
  credentials: true,
});

// Webhook endpoints - specific origins
const webhookCors = cors({
  origin: ['https://stripe.com', 'https://github.com'],
  methods: ['POST'],
});

router.get('/public/data', publicCors, publicDataHandler);
router.post('/private/data', privateCors, privateDataHandler);
router.post('/webhooks/stripe', webhookCors, stripeWebhookHandler);

export default router;

Next.js の設定

ミドルウェアでの CORS
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const allowedOrigins = [
  'https://app.example.com',
  'https://admin.example.com',
];

if (process.env.NODE_ENV === 'development') {
  allowedOrigins.push('http://localhost:3000');
}

export function middleware(request: NextRequest) {
  const origin = request.headers.get('origin');
  const isApiRoute = request.nextUrl.pathname.startsWith('/api');

  // Only apply CORS to API routes
  if (!isApiRoute) {
    return NextResponse.next();
  }

  // Handle preflight
  if (request.method === 'OPTIONS') {
    const response = new NextResponse(null, { status: 204 });

    if (origin && allowedOrigins.includes(origin)) {
      response.headers.set('Access-Control-Allow-Origin', origin);
      response.headers.set('Access-Control-Allow-Credentials', 'true');
      response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      response.headers.set('Access-Control-Max-Age', '86400');
    }

    return response;
  }

  // Handle actual request
  const response = NextResponse.next();

  if (origin && allowedOrigins.includes(origin)) {
    response.headers.set('Access-Control-Allow-Origin', origin);
    response.headers.set('Access-Control-Allow-Credentials', 'true');
  }

  return response;
}

export const config = {
  matcher: '/api/:path*',
};
API ルートでの CORS
// app/api/data/route.ts
import { NextRequest, NextResponse } from 'next/server';

const allowedOrigins = ['https://app.example.com'];

function corsHeaders(origin: string | null) {
  const headers: Record<string, string> = {};

  if (origin && allowedOrigins.includes(origin)) {
    headers['Access-Control-Allow-Origin'] = origin;
    headers['Access-Control-Allow-Credentials'] = 'true';
  }

  return headers;
}

export async function OPTIONS(request: NextRequest) {
  const origin = request.headers.get('origin');

  return new NextResponse(null, {
    status: 204,
    headers: {
      ...corsHeaders(origin),
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '86400',
    },
  });
}

export async function GET(request: NextRequest) {
  const origin = request.headers.get('origin');

  const data = { message: 'Hello' };

  return NextResponse.json(data, {
    headers: corsHeaders(origin),
  });
}

export async function POST(request: NextRequest) {
  const origin = request.headers.get('origin');

  // Verify origin for mutations
  if (!origin || !allowedOrigins.includes(origin)) {
    return new NextResponse('Forbidden', { status: 403 });
  }

  const body = await request.json();
  const result = await processData(body);

  return NextResponse.json(result, {
    headers: corsHeaders(origin),
  });
}

Fastify の設定

// plugins/cors.ts
import fastifyCors from '@fastify/cors';
import { FastifyInstance } from 'fastify';

export async function configureCors(fastify: FastifyInstance) {
  await fastify.register(fastifyCors, {
    origin: (origin, callback) => {
      const allowedOrigins = [
        'https://app.example.com',
        'https://admin.example.com',
      ];

      if (!origin || allowedOrigins.includes(origin)) {
        callback(null, true);
      } else {
        callback(new Error('Not allowed'), false);
      }
    },
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    exposedHeaders: ['X-Request-ID'],
    credentials: true,
    maxAge: 86400,
    preflight: true,
    strictPreflight: true,
  });
}

動的なオリジン検証

// lib/cors/validator.ts
interface CorsConfig {
  allowedOrigins: string[];
  allowedPatterns: RegExp[];
  allowSubdomains: string[];
}

const config: CorsConfig = {
  allowedOrigins: [
    'https://app.example.com',
    'https://admin.example.com',
  ],
  allowedPatterns: [
    /^https:\/\/.*\.vercel\.app$/,
    /^https:\/\/.*\.netlify\.app$/,
  ],
  allowSubdomains: [
    'example.com', // Allows *.example.com
  ],
};

export function isOriginAllowed(origin: string): boolean {
  // Check exact match
  if (config.allowedOrigins.includes(origin)) {
    return true;
  }

  // Check patterns
  for (const pattern of config.allowedPatterns) {
    if (pattern.test(origin)) {
      return true;
    }
  }

  // Check subdomains
  for (const domain of config.allowSubdomains) {
    if (origin.endsWith(`.${domain}`) || origin === `https://${domain}`) {
      return true;
    }
  }

  return false;
}

// Usage in middleware
app.use((req, res, next) => {
  const origin = req.headers.origin;

  if (origin && isOriginAllowed(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Vary', 'Origin');
  }

  next();
});

認証情報と Cookie

// Important: When using credentials
// 1. Cannot use Access-Control-Allow-Origin: *
// 2. Must specify exact origin
// 3. Must set Access-Control-Allow-Credentials: true

// Server
app.use(cors({
  origin: 'https://app.example.com', // Must be exact, not *
  credentials: true,
}));

// Client (fetch)
fetch('https://api.example.com/data', {
  credentials: 'include', // Required for cookies
  headers: {
    'Content-Type': 'application/json',
  },
});

// Client (axios)
axios.defaults.withCredentials = true;

セキュリティヘッダーとの併用

// middleware/security.ts
import helmet from 'helmet';
import { Express } from 'express';

export function configureSecurityHeaders(app: Express) {
  app.use(helmet({
    crossOriginResourcePolicy: { policy: 'cross-origin' },
    crossOriginOpenerPolicy: { policy: 'same-origin-allow-popups' },
    crossOriginEmbedderPolicy: false, // May conflict with third-party resources
  }));

  // Additional headers
  app.use((req, res, next) => {
    // Prevent clickjacking
    res.setHeader('X-Frame-Options', 'SAMEORIGIN');

    // Prevent MIME sniffing
    res.setHeader('X-Content-Type-Options', 'nosniff');

    // XSS protection
    res.setHeader('X-XSS-Protection', '1; mode=block');

    // Referrer policy
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');

    next();
  });
}

CORS のテスト

// tests/cors.test.ts
import request from 'supertest';
import { app } from '../src/app';

describe('CORS', () => {
  it('allows requests from allowed origins', async () => {
    const response = await request(app)
      .get('/api/data')
      .set('Origin', 'https://app.example.com');

    expect(response.headers['access-control-allow-origin']).toBe('https://app.example.com');
  });

  it('blocks requests from disallowed origins', async () => {
    const response = await request(app)
      .get('/api/data')
      .set('Origin', 'https://evil.com');

    expect(response.headers['access-control-allow-origin']).toBeUndefined();
  });

  it('handles preflight requests', async () => {
    const response = await request(app)
      .options('/api/data')
      .set('Origin', 'https://app.example.com')
      .set('Access-Control-Request-Method', 'POST')
      .set('Access-Control-Request-Headers', 'Content-Type');

    expect(response.status).toBe(204);
    expect(response.headers['access-control-allow-methods']).toContain('POST');
  });

  it('includes credentials header when configured', async () => {
    const response = await request(app)
      .get('/api/data')
      .set('Origin', 'https://app.example.com');

    expect(response.headers['access-control-allow-credentials']).toBe('true');
  });
});

よく使われるパターン

// Pattern 1: Development vs Production
const corsOptions = {
  origin: process.env.NODE_ENV === 'production'
    ? ['https://app.example.com']
    : [/localhost/],
};

// Pattern 2: Environment-based configuration
const corsOptions = {
  origin: process.env.ALLOWED_ORIGINS?.split(',') || [],
};

// Pattern 3: Wildcard subdomain
const corsOptions = {
  origin: (origin, callback) => {
    if (!origin || /\.example\.com$/.test(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed'));
    }
  },
};

ベストプラクティス

  1. 認証情報と * を併用しない:特定のオリジンを使用します
  2. 動的に検証する:実行時にオリジンをチェックします
  3. Vary: Origin を使用する:キャッシュの整合性を保ちます
  4. メソッドを制限する:必要な HTTP メソッドだけを許可します
  5. ヘッダーを制限する:必要なヘッダーだけを公開します
  6. Max-Age を設定する:プリフライトレスポンスをキャッシュします
  7. ブロックしたリクエストを記録する:問題がないか監視します
  8. 十分にテストする:すべてのシナリオを網羅します

出力チェックリスト

すべての CORS 設定には、次の項目を含める必要があります。

  • 許可する特定のオリジン(認証情報を使用する場合はワイルドカードを使用しない)
  • 適切なプリフライト処理(OPTIONS)
  • 認証情報の設定
  • 許可するメソッドの指定
  • 許可するヘッダーの一覧
  • 公開するヘッダーの設定
  • プリフライトのキャッシュ用 Max-Age
  • Vary: Origin ヘッダー
  • 開発用オリジンの処理
  • ブロックしたリクエストのエラー処理

コメント