csrf-protection — скилл для Claude Code: защита форм от CSRF
Скилл подсказывает агенту, как закрыть формы и эндпоинты от подделки запросов: синхронизатор-токены, double-submit cookie и SameSite.
npx skills add secondsky/claude-skills --skill csrf-protection -a claude-codeЧто делает csrf-protection
Скилл описывает три способа защиты от Cross-Site Request Forgery: скрытое поле с токеном, который проверяется на сервере, пару «cookie + заголовок», которые должны совпасть, и атрибут SameSite у cookie. Внутри есть готовые примеры для Express на JavaScript: генерация токена через crypto.randomBytes, middleware, который кладёт токен в сессию, и проверка на POST-запросах.
Сравнение токенов идёт через crypto.timingSafeEqual. Тут есть подвох: эта функция бросает RangeError, если буферы разной длины, поэтому в примере сначала идёт явная проверка длины. Если скопировать код без неё, валидация упадёт с ошибкой вместо честного 403 — это повод прочитать пример целиком, а не выдёргивать строку.
Отдельно разобраны настройки сессионной cookie (httpOnly, secure, sameSite), вставка скрытого поля _csrf в HTML-форму и список частых ошибок: токен в localStorage, переиспользование токена между сессиями, отсутствие срока жизни. Для Flask и React есть ссылка на references/python-react.md с настройкой Flask-WTF и хуками для работы с токеном.
Какие задачи решает
- закрыть POST-форму от подделки запросов с чужого сайта
- сгенерировать и проверить CSRF-токен в Express без сторонней библиотеки
- настроить SameSite и secure у сессионной cookie
- сравнить токены без утечки времени через timingSafeEqual
- разобрать типичные ошибки вроде токена в localStorage
Примеры запросов агенту
- добавь CSRF-защиту в форму перевода через синхронизатор-токен
- проверь мои POST-роуты в Express и подскажи, где не хватает валидации токена
- настрой SameSite=Strict для сессионной cookie
Как установить csrf-protection
1Через Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill csrf-protection -a claude-code2Вручную: положить файлы
~/.claude/skills/csrf-protection/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/csrf-protection/
1Через Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill csrf-protection -a codex2Вручную: положить файлы
.agents/skills/csrf-protection/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill csrf-protection -a cursor2Вручную: положить файлы
.cursor/skills/csrf-protection/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install secondsky/claude-skills csrf-protection2Вручную: положить файлы
.github/skills/csrf-protection/SKILL.md1Через Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill csrf-protection -a gemini-cli2Командой платформы
gemini skills install https://github.com/secondsky/claude-skills --path plugins/csrf-protection/skills/csrf-protectionВручную: положить файлы
.devin/skills/csrf-protection/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill csrf-protection -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о csrf-protection
Как установить csrf-protection в Claude?
Выполните npx skills add secondsky/claude-skills --skill csrf-protection -a claude-code. После этого скилл появится в ~/.claude/skills/csrf-protection/SKILL.md.
Что делает csrf-protection?
Описывает защиту от Cross-Site Request Forgery через синхронизатор-токены, double-submit cookie и атрибут SameSite, с примерами кода для Express.
Нужны ли дополнительные библиотеки?
В примерах для Express используется встроенный модуль crypto, а для Flask и React скилл ссылается на references/python-react.md с настройкой Flask-WTF.
Исходный текст
SKILL.md · MIT
---
name: csrf-protection
description: Implements CSRF protection using synchronizer tokens, double-submit cookies, and SameSite attributes. Use when securing web forms, protecting state-changing endpoints, or implementing defense-in-depth authentication.
license: MIT
---
# CSRF Protection
Defend against Cross-Site Request Forgery attacks using multiple protection layers.
## Protection Methods
| Method | How It Works | Browser Support |
|--------|--------------|-----------------|
| Synchronizer Token | Hidden form field validated server-side | All |
| Double Submit | Cookie + header must match | All |
| SameSite Cookie | Browser blocks cross-origin requests | Modern |
## Token-Based Protection (Express)
```javascript
const crypto = require('crypto');
function generateToken() {
return crypto.randomBytes(32).toString('hex');
}
// Middleware
app.use((req, res, next) => {
if (!req.session.csrfToken) {
req.session.csrfToken = generateToken();
}
res.locals.csrfToken = req.session.csrfToken;
next();
});
// Validation
app.post('*', (req, res, next) => {
const token = req.body._csrf || req.headers['x-csrf-token'];
// crypto.timingSafeEqual throws RangeError when buffers differ in length,
// so check length explicitly first (still constant-time on the equal-length path).
const csrf = req.session.csrfToken || '';
if (!token || token.length !== csrf.length) {
return res.status(403).json({ error: 'Invalid CSRF token' });
}
if (!crypto.timingSafeEqual(Buffer.from(token), Buffer.from(csrf))) {
return res.status(403).json({ error: 'Invalid CSRF token' });
}
next();
});
```
## SameSite Cookies
```javascript
app.use(session({
cookie: {
httpOnly: true,
secure: true,
sameSite: 'strict', // or 'lax'
maxAge: 3600000
}
}));
```
## HTML Form Integration
```html
<form method="POST" action="/transfer">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit">Submit</button>
</form>
```
## Best Practices
- Apply to all state-changing requests (POST, PUT, DELETE)
- Use SameSite=Strict for sensitive cookies
- Validate Origin/Referer headers
- Never use GET for modifications
- Implement token expiration (1 hour typical)
- Combine multiple defense layers
## Additional Implementations
See [references/python-react.md](references/python-react.md) for:
- Flask-WTF complete CSRF setup
- React hooks for CSRF token management
- Double submit cookie pattern
## Common Mistakes
- Assuming authentication prevents CSRF
- Reusing tokens across sessions
- Storing tokens in localStorage
- Missing token expiration
© secondsky · MIT · secondsky/claude-skills