Files
runbooks/n8n-setup-guide.md
kappa bafc79c81b Improve security documentation based on Context7 review
aws-ses-setup.md:
- Add SPF records for email authentication
- Add DMARC policy configuration
- Add bounce/complaint handling with SNS
- Add DNS verification commands

n8n-setup-guide.md:
- Use official Docker registry (docker.n8n.io)
- Add N8N_ENCRYPTION_KEY requirement
- Add N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS
- Add N8N_PUBLIC_API_DISABLED option
- Add security headers to nginx config
- Add healthcheck configuration

gitea-setup.md:
- Add password policy (MIN_PASSWORD_LENGTH, PASSWORD_COMPLEXITY)
- Add argon2 password hashing
- Add DISABLE_GIT_HOOKS for security
- Add Docker Secrets configuration
- Add file-based secret management (SECRET_KEY_URI)
- Add REVERSE_PROXY_TRUSTED_PROXIES setting

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 00:45:40 +09:00

8.2 KiB

🤖 n8n AI Agent: Cloudflare Tunnel 자동화 가이드

n8n에서 Cloudflare Tunnel과 Nginx Proxy Manager를 자동으로 설정하는 AI 에이전트 워크플로우입니다.

🏗️ 아키텍처

graph TD
    A[HTTP Request] --> B[n8n Webhook]
    B --> C[AI Agent 검증]
    C --> D[Cloudflare API]
    C --> E[NPM API]
    D --> F[DNS CNAME 설정]
    E --> G[프록시 호스트 생성]
    F --> H[완료 응답]
    G --> H

📋 사전 요구사항

1. n8n 설치 및 실행

# Docker Compose로 실행 (권장) - 공식 이미지 사용
docker run -it --rm --name n8n -p 5678:5678 docker.n8n.io/n8nio/n8n

# 또는 npm으로 설치
npm install n8n -g
n8n start

주의: n8nio/n8n 대신 공식 레지스트리 docker.n8n.io/n8nio/n8n 사용 권장

2. Credentials 설정

n8n에서 다음 Credentials를 생성해야 합니다:

Cloudflare Credential (cloudflare)

{
  "email": "your-email@example.com",
  "api_key": "your-global-api-key"
}

NPM Credential (npm) - 선택사항

{
  "url": "http://localhost:81",
  "email": "admin@example.com", 
  "password": "changeme"
}

🚀 워크플로우 설치

1. 메인 AI Agent 워크플로우 임포트

  1. n8n 대시보드에서 "Import from file" 선택
  2. n8n-cf-tunnel-workflow.json 파일 업로드
  3. Credentials 연결:
    • cloudflare: Cloudflare credential 선택
    • npm: NPM credential 선택 (있는 경우)

2. Webhook API 워크플로우 임포트

  1. n8n-webhook-workflow.json 파일 임포트
  2. Execute CF Agent 노드에서:
    • CF-TUNNEL-AI-AGENT-WORKFLOW-ID를 실제 워크플로우 ID로 변경

📡 API 사용법

HTTP POST 요청

curl -X POST "http://localhost:5678/webhook/cf-tunnel" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "example.com",
    "subdomain": "app",
    "service_ip": "192.168.1.100", 
    "service_port": "8080"
  }'

성공 응답 (200)

{
  "success": true,
  "domain": "app.example.com",
  "tunnel_id": "0adb287c-10e2-4f1d-af4c-8e083ed878d4",
  "tunnel_domain": "0adb287c-10e2-4f1d-af4c-8e083ed878d4.cfargotunnel.com",
  "service": "192.168.1.100:8080",
  "dns_configured": true,
  "npm_configured": true,
  "npm_host_id": "123",
  "timestamp": "2024-09-07T01:00:00.000Z",
  "message": "🚀 AI Agent 완료: app.example.com → 192.168.1.100:8080"
}

에러 응답 (400/500)

{
  "error": true,
  "message": "Missing required fields: domain, subdomain",
  "required_fields": ["domain", "subdomain", "service_ip", "service_port"],
  "example": {
    "domain": "example.com",
    "subdomain": "app",
    "service_ip": "192.168.1.100", 
    "service_port": "8080"
  }
}

🔧 커스터마이징

1. 터널 ID 변경

각 워크플로우의 Initialize Config 노드에서:

tunnel_id: 'YOUR-TUNNEL-ID-HERE',
tunnel_domain: 'YOUR-TUNNEL-ID-HERE.cfargotunnel.com',

2. 계정 ID 변경

account_id: 'YOUR-ACCOUNT-ID-HERE'

3. NPM 설정 수정

Create NPM Proxy 노드에서 SSL, 캐싱 등 설정 변경 가능:

{
  "ssl_forced": true,
  "caching_enabled": true,
  "certificate_id": 1,
  "meta": {
    "letsencrypt_agree": true,
    "dns_challenge": true
  }
}

🔒 보안 고려사항

1. API 키 보호

  • Vault 연동 사용 권장
  • n8n Credentials에 직접 저장 시 암호화 확인
  • 최소 권한 원칙 적용

2. 웹훅 보안

// Webhook 노드에 인증 추가
const authHeader = $input.all()[0].headers.authorization;
if (!authHeader || authHeader !== 'Bearer YOUR-SECRET-TOKEN') {
  return [{ json: { error: true, message: 'Unauthorized' } }];
}

3. Rate Limiting

n8n에서 실행 제한 설정:

  • Execution Timeout: 300초
  • Max Executions: 시간당 제한 설정

📊 모니터링 및 로깅

1. 실행 로그 확인

n8n 대시보드 → Executions → 워크플로우 실행 기록 확인

2. 에러 알림 설정

Error Workflow 생성하여 실패 시 알림 발송:

{
  "name": "CF-Tunnel-Error-Handler",
  "nodes": [
    {
      "name": "Send Slack Alert",
      "type": "n8n-nodes-base.slack"
    }
  ]
}

3. 성능 메트릭

  • 평균 실행 시간: ~30-60초
  • 성공률: >95% 목표
  • API 응답 시간 모니터링

🧪 테스트 시나리오

1. 기본 테스트

# 새 도메인 생성
curl -X POST "http://localhost:5678/webhook/cf-tunnel" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "test.com",
    "subdomain": "api",
    "service_ip": "127.0.0.1",
    "service_port": "3000"
  }'

2. 기존 도메인 업데이트

# 같은 subdomain.domain으로 다른 서비스로 업데이트
curl -X POST "http://localhost:5678/webhook/cf-tunnel" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "test.com", 
    "subdomain": "api",
    "service_ip": "127.0.0.1",
    "service_port": "4000"
  }'

3. 에러 테스트

# 잘못된 IP 주소
curl -X POST "http://localhost:5678/webhook/cf-tunnel" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "test.com",
    "subdomain": "api", 
    "service_ip": "999.999.999.999",
    "service_port": "3000"
  }'

🚀 프로덕션 배포

1. Docker Compose 설정 (보안 강화)

version: '3.8'
services:
  n8n:
    image: docker.n8n.io/n8nio/n8n
    ports:
      - "127.0.0.1:5678:5678"
    environment:
      # 기본 설정
      - N8N_HOST=0.0.0.0
      - N8N_PORT=5678
      - N8N_PROTOCOL=https
      - NODE_ENV=production
      # 보안 설정 (필수)
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}  # openssl rand -hex 32 로 생성
      - N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true
      # 인증 설정
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER=admin
      - N8N_BASIC_AUTH_PASSWORD=${N8N_ADMIN_PASSWORD}
      # 보안 강화 옵션
      - N8N_PUBLIC_API_DISABLED=true  # Public API 비활성화
      - N8N_RUNNERS_ENABLED=true      # Task Runner 활성화
      - N8N_PROXY_HOPS=1              # 리버스 프록시 사용 시
      # Webhook 설정
      - WEBHOOK_URL=https://n8n.yourdomain.com/
      # 타임존
      - GENERIC_TIMEZONE=Asia/Seoul
      - TZ=Asia/Seoul
    volumes:
      - n8n_data:/home/node/.n8n
      - ./local-files:/files
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "wget", "-q", "--spider", "http://localhost:5678/healthz"]
      interval: 30s
      timeout: 10s
      retries: 3

volumes:
  n8n_data:

환경변수 파일 (.env)

# 암호화 키 생성 (최초 1회)
openssl rand -hex 32

# .env 파일 예시
N8N_ENCRYPTION_KEY=your_generated_key_here
N8N_ADMIN_PASSWORD=secure_password_here

중요: N8N_ENCRYPTION_KEY는 DB에 저장되는 credential을 암호화합니다. 분실 시 모든 credential 재설정 필요.

2. 리버스 프록시 설정 (보안 헤더 포함)

server {
    listen 80;
    server_name n8n.yourdomain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name n8n.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/n8n.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/n8n.yourdomain.com/privkey.pem;

    # 보안 헤더
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;

    location / {
        proxy_pass http://127.0.0.1:5678;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_read_timeout 300s;
    }
}

📝 추가 기능 아이디어

  1. Bulk API: 여러 도메인 한번에 설정
  2. Status Check: 터널 상태 모니터링 API
  3. SSL Certificate: Let's Encrypt 자동 설정
  4. Health Check: 서비스 상태 확인 및 알림
  5. Rollback: 설정 되돌리기 기능

이제 n8n에서 Cloudflare 터널을 자동화하는 AI 에이전트가 준비되었습니다! 🤖