К основному содержанию
скилл CX Codex

cloudflare-troubleshooting — скилл для Claude Code: разбор сбоев

Скилл для диагностики конфигурации Cloudflare через API: находит причину редирект-петель, ошибок SSL и DNS, а не гадает.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add daymade/claude-code-skills --skill cloudflare-troubleshooting -a claude-code
Открыть на GitHub

Что делает cloudflare-troubleshooting

Скилл ведёт агента по методике «сначала доказательства, потом выводы». Вместо предположений о том, что сломано, он запрашивает реальное состояние конфигурации через Cloudflare API: режим SSL, настройку Always Use HTTPS, Page Rules, DNS-записи, статус DNSSEC, сертификаты и правила файрвола.

Внутри — готовые последовательности вызовов curl для типовых сбоев. Для петли ERR_TOO_MANY_REDIRECTS скилл проверяет режим SSL, затем Always Use HTTPS, затем Page Rules и только потом origin напрямую. Если режим стоит flexible, а origin требует HTTPS, петля объясняется сразу. Похожие ветки есть для ошибок 525 и 526, для 502/503/504 и для DNS.

Для работы понадобится домен и доступ к API: email плюс Global API Key либо API Token. Скилл советует переиспользовать уже настроенную авторизацию и спрашивать только недостающее. Global API Key лежит в Cloudflare Dashboard → My Profile → API Tokens. Если у вас Pages-хостинг, который ещё не привязан к зоне, пустой результат поиска зоны — это факт для разбора, а не повод создавать новую зону.

Какие задачи решает

  • разобраться, почему сайт уходит в бесконечный редирект
  • найти причину ошибки 526 при строгом режиме SSL
  • проверить, куда указывают DNS-записи и включён ли прокси
  • отличить проблему на origin от ошибки в настройках Cloudflare
  • сбросить устаревший HTTP-редирект из кеша после правки

Примеры запросов агенту

  • Сайт уходит в ERR_TOO_MANY_REDIRECTS, проверь настройки Cloudflare через API и скажи, что менять
  • Получаю ошибку 526, посмотри статус сертификатов и режим SSL для моего домена
  • Кастомный домен не открывается, хотя pages.dev работает — проверь DNS и привязку

Как установить cloudflare-troubleshooting

1Через Skills CLI (Vercel)

npx skills add daymade/claude-code-skills --skill cloudflare-troubleshooting -a claude-code

2Вручную: положить файлы

~/.claude/skills/cloudflare-troubleshooting/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/cloudflare-troubleshooting/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о cloudflare-troubleshooting

Как установить cloudflare-troubleshooting в Claude?

Выполните npx skills add daymade/claude-code-skills --skill cloudflare-troubleshooting -a claude-code. Скилл окажется в ~/.claude/skills/cloudflare-troubleshooting/SKILL.md.

Что делает cloudflare-troubleshooting?

Собирает доказательства о конфигурации Cloudflare через API и по ним ставит диагноз: режим SSL, Always Use HTTPS, Page Rules, DNS, DNSSEC, сертификаты, файрвол.

Что нужно, чтобы скилл заработал?

Домен и авторизация в Cloudflare: email с Global API Key или API Token. Уже настроенное подключение скилл переиспользует и запрашивает только недостающее.

Исходный текст

SKILL.md · MIT
---
name: cloudflare-troubleshooting
description: Investigate and resolve Cloudflare configuration issues using API-driven evidence gathering. Use when troubleshooting ERR_TOO_MANY_REDIRECTS, SSL errors, DNS issues, or any Cloudflare-related problems. Focus on systematic investigation using Cloudflare API to examine actual configuration rather than making assumptions.
---

# Cloudflare Troubleshooting

> **Methodology base:** the general evidence-driven network-diagnosis discipline (falsification, layered isolation, counter-review) lives in the **debugging-network-issues** skill. This skill is the Cloudflare *domain* layer on top of it.

## Core Principle

**Investigate with evidence, not assumptions.** Always query Cloudflare API to examine actual configuration before diagnosing issues. The skill's value is the systematic investigation methodology, not predetermined solutions.

## Investigation Methodology

### 1. Gather Credentials

Reuse the domain and authorized Cloudflare connection already supplied by the user or project configuration. Ask only for missing connection information: domain, account email plus Global API Key, or API Token. Keep the working authentication method; troubleshooting does not require replacing it.

Global API Key location: Cloudflare Dashboard → My Profile → API Tokens → View Global API Key

### 2. Get Zone Information

For zone-scoped troubleshooting, obtain the zone ID:

```bash
curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=<domain>" \
  -H "X-Auth-Email: <email>" \
  -H "X-Auth-Key: <api_key>" | jq '.'
```

Select the exact matching zone and account before extracting its `id`; do not blindly select the first result when account or domain identity is ambiguous. Use that zone’s `account.id` for account-scoped calls.

For a Pages hostname that has never been attached, an empty exact-zone result is a finding, not an account ID or proof that the site is absent. Resolve the existing account/project from its authorized configuration and follow [Pages custom domains and DNSSEC migration](references/pages-custom-domain.md). Do not create a zone merely to make this lookup succeed.

### 3. Investigate Systematically

For each issue, gather evidence before making conclusions. Use Cloudflare API to inspect:
- Current configuration state
- Recent changes (if audit log available)
- Related settings that might interact

## Common Investigation Patterns

### Redirect Loops (ERR_TOO_MANY_REDIRECTS)

**Evidence gathering sequence:**

1. **Check SSL/TLS mode:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/settings/ssl" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

   Look for: `result.value` - tells current SSL mode

2. **Check Always Use HTTPS setting:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/settings/always_use_https" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

3. **Check Page Rules for redirects:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/pagerules" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

   Look for: `forwarding_url` or `always_use_https` actions

4. **Test origin server directly (if possible):**
   ```bash
   curl -I -H "Host: <domain>" https://<origin_ip>
   ```

**Diagnosis logic:**
- SSL mode "flexible" + origin enforces HTTPS = redirect loop
- Multiple redirect rules can conflict
- Check browser vs curl behavior differences

**Fix:**
```bash
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/settings/ssl" \
  -H "X-Auth-Email: email" \
  -H "X-Auth-Key: key" \
  -H "Content-Type: application/json" \
  --data '{"value":"full"}'
```

If stale HTTP redirects remain after the fix, purge the relevant HTTP cache:
```bash
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
  -H "X-Auth-Email: email" \
  -H "X-Auth-Key: key" \
  -d '{"purge_everything":true}'
```

### Email Routing and Forwarding

For alias delivery, destination verification, catch-all behavior or forwarding MX issues, follow [Email Routing](references/email-routing.md). It supplies the account/zone API read sequence and separates saved configuration from actual Inbox arrival.

### DNS Issues

For a working `pages.dev` site with an unreachable custom hostname, missing Pages binding, or a nameserver/DNSSEC move, load [Pages custom domains and DNSSEC migration](references/pages-custom-domain.md) before changing DNS. It separates registrar identity, parent publication, recursive caches and normal-hostname acceptance.

**Evidence gathering:**

1. **List DNS records:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

2. **Check external DNS resolution:**
   ```bash
   dig <domain>
   dig @8.8.8.8 <domain>
   ```

3. **Check DNSSEC status:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/dnssec" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

**Look for:**
- Missing A/AAAA/CNAME records
- Incorrect proxy status (proxied vs DNS-only)
- TTL values
- Conflicting records

### SSL Certificate Errors

**Evidence gathering:**

1. **Check SSL certificate status:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/ssl/certificate_packs" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

2. **Check origin certificate (if using Full Strict):**
   ```bash
   openssl s_client -connect <origin_ip>:443 -servername <domain>
   ```

3. **Check SSL settings:**
   - Minimum TLS version
   - TLS 1.3 status
   - Opportunistic Encryption

**Common issues:**
- Error 526: SSL mode is "strict" but origin cert invalid
- Error 525: SSL handshake failure at origin
- Provisioning delay: inspect the selected product's certificate/domain validation state and report the remaining prerequisite or pending state

### Origin Server Errors (502/503/504)

**Evidence gathering:**

1. **Check if origin is reachable:**
   ```bash
   curl -I -H "Host: <domain>" https://<origin_ip>
   ```

2. **Check DNS records point to correct origin:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

3. **Review load balancer config (if applicable):**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/load_balancers" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

4. **Check firewall rules:**
   ```bash
   curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/firewall/rules" \
     -H "X-Auth-Email: email" \
     -H "X-Auth-Key: key"
   ```

## Learning New APIs

When encountering issues not covered above, consult Cloudflare API documentation:

1. **Browse API reference:** https://developers.cloudflare.com/api/
2. **Search for relevant endpoints** using issue keywords
3. **Check API schema** to understand available operations
4. **Test with GET requests** first to understand data structure
5. **Make changes with PATCH/POST** after confirming approach

**Pattern for exploring new APIs:**
```bash
# List available settings for a zone
curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/settings" \
  -H "X-Auth-Email: email" \
  -H "X-Auth-Key: key"
```

## API Reference Overview

Consult `references/api_overview.md` for:
- Common endpoints organized by category
- Request/response schemas
- Authentication patterns
- Rate limits and error handling

Consult `references/ssl_modes.md` for:
- Detailed SSL/TLS mode explanations
- Platform compatibility
- Security implications

Consult `references/common_issues.md` for:
- Issue patterns and symptoms
- Investigation checklists
- Platform-specific notes

## Best Practices

### Evidence-Based Investigation

1. **Query before assuming** - Use API to check actual state
2. **Gather multiple data points** - Cross-reference settings
3. **Check related configurations** - Settings often interact
4. **Verify externally** - Use dig/curl to confirm
5. **Test incrementally** - One change at a time

### API Usage

1. **Parse JSON responses** - Use `jq` or python for readability
2. **Check success field** - `"success": true/false` in responses
3. **Handle errors gracefully** - Read `errors` array in responses
4. **Respect rate limits** - Cloudflare API has limits
5. **Use appropriate methods:**
   - GET: Retrieve information
   - PATCH: Update settings
   - POST: Create resources / trigger actions
   - DELETE: Remove resources

### Making Changes

1. **Gather evidence first** - Understand current state
2. **Identify root cause** - Don't guess
3. **Apply targeted fix** - Change only what's needed
4. **Purge HTTP cache only when implicated** - A CDN purge does not publish registrar changes or clear recursive DNS caches
5. **Verify fix** - Re-query API to confirm
6. **Report the waiting stage and next observation:** use current activation state, registry publication policy and observed TTLs. Registrar save, parent publication and client recovery can occur at different times; do not prescribe a fixed delay or browser-cache clearing without evidence.

### Security

- Never log API keys in output
- Warn if user shares credentials in public context
- Recommend API Tokens with scoped permissions over Global API Key
- Use read-only operations for investigation

## Workflow Template

```
1. Reuse the configured domain and authorized API connection; obtain only missing values
2. Get zone_id via zones API
3. Investigate:
   - Query relevant APIs for evidence
   - Check multiple related settings
   - Verify with external tools (dig, curl)
4. Analyze evidence to determine root cause
5. Apply fix via appropriate API endpoint
6. Purge HTTP cache only if stale HTTP content is implicated
7. Verify fix via API query and normal-hostname external testing; provider or forced-IP success alone is partial
8. Inform user of resolution and any required actions
```

## Example: Complete Investigation

When user reports "site shows ERR_TOO_MANY_REDIRECTS":

```bash
# 1. Get zone ID
curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=example.com" \
  -H "X-Auth-Email: [email protected]" \
  -H "X-Auth-Key: abc123" | jq '.result[] | select(.name == "example.com") | {id, account}'

# Select the intended account from the exact-domain result before using its id.
# 2. Check SSL mode (primary suspect for redirect loops)
curl -s -X GET "https://api.cloudflare.com/client/v4/zones/ZONE_ID/settings/ssl" \
  -H "X-Auth-Email: [email protected]" \
  -H "X-Auth-Key: abc123" | jq '.result.value'

# If returns "flexible" and origin is GitHub Pages/Netlify/Vercel:

# 3. Fix by changing to "full"
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/ZONE_ID/settings/ssl" \
  -H "X-Auth-Email: [email protected]" \
  -H "X-Auth-Key: abc123" \
  -H "Content-Type: application/json" \
  --data '{"value":"full"}'

# 4. Only if stale HTTP redirects remain, purge HTTP cache
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
  -H "X-Auth-Email: [email protected]" \
  -H "X-Auth-Key: abc123" \
  -d '{"purge_everything":true}'

# 5. Recheck the ordinary hostname and browser; report observed recovery or the unresolved layer
```

## When Scripts Are Useful

The bundled scripts (`scripts/check_cloudflare_config.py`, `scripts/fix_ssl_mode.py`) serve as:
- **Reference implementations** of investigation patterns
- **Quick diagnostic tools** when Python is available
- **Examples** of programmatic API usage

However, **prefer direct API calls via Bash/curl** for flexibility and transparency. Scripts should not limit capability - use them when convenient, but use raw API calls when needed for:
- Unfamiliar scenarios
- Edge cases
- Learning/debugging
- Operations not covered by scripts

The investigation methodology and API knowledge is the core skill, not the scripts.

© daymade · MIT · daymade/claude-code-skills

Похожие скиллы

Всё по теме «DevOps и инфраструктура» →
cloudflare-manager secondsky Скилл управляет аккаунтом Cloudflare из чата: разворачивает Workers, создаёт KV и R2, публикует Pages, настраивает DNS. CX Codex +1 393установок cloudflare-workers devops-skills Скилл для работы с Cloudflare Workers: помогает писать и деплоить edge-функции через Wrangler. Пригодится, если делаете API, cron-задачи или middleware. CX Codex +1 314установок cloudflare cloudflare Помогает агенту подбирать сервисы Cloudflare под задачи проекта, от хостинга до очередей и AI, и выбирать между CLI cf и Wrangler. CX Codex +1 137 800установок cf-cli cloudflare Официальный CLI Cloudflare для работы с API и Workers проектами прямо из редактора кода. Ищет команды по описанию задачи, управляет DNS, хранилищами и развёртыванием. CX Codex +1 11 500установок cloudflare-development Mindrally Скилл с правилами разработки на edge-платформе Cloudflare: Workers, Pages, KV, D1, R2 и Durable Objects. Пригодится, когда агент пишет код для воркеров или настраивает wrangler.toml. CX Codex +1 689установок cloudflare-r2 devops-skills Помогает управлять хранилищем Cloudflare R2, настраивать бакеты через Wrangler, генерировать подписанные ссылки и связывать данные с Cloudflare Workers. CX Codex +1 335установок

Из того же набора64

asr-transcribe-to-text Переводит аудио и видео в текст с таймкодами и метками спикеров: локально через MLX на Apple Silicon или через удалённый API. CX Codex +1 1 000установок github-contributor Ведёт пул-реквест в проект, который вы не поддерживаете: проверка CONTRIBUTING, размер диффа, описание с раскрытием ИИ и ответы на ревью ботов. CX Codex +1 957установок video-comparer Скилл сравнивает два видео и собирает HTML-отчёт с метриками PSNR и SSIM, а также покадровым просмотром до и после сжатия. CX Codex +1 953установок llm-icon-finder Скилл находит ссылки на иконки AI-моделей и провайдеров из библиотеки lobe-icons и помогает скачать их в SVG, PNG или WEBP. CX Codex +1 952установок cli-demo-generator Скилл записывает команды в терминале и отдаёт готовый анимированный GIF. Пригодится для README и документации CLI-инструмента. CX Codex +1 942установок teams-channel-post-writer Пишет обучающие посты в канал Teams про Claude: разбор фич, советы, примеры промптов и принципы вроде context engineering. CX Codex +1 935установок repomix-safe-mixer Скилл сканирует проект на захардкоженные ключи и токены и не даёт repomix упаковать код, пока секреты не убраны. CX Codex +1 912установок financial-data-collector Собирает реальные финансовые данные по публичным компаниям США из yfinance и отдаёт структурированный JSON для DCF, сравнений и разбора отчётности. CX Codex +1 883установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой