Programování
Expert
Claude
Claude Extended Context - Práce s 200K Kontextem
Naučte se efektivně využívat Claudeho rozšířené kontextové okno 200K tokenů pro analýzu velkých kódových bází, dokumentů a komplexních projektů.
Prompt text
Délka: Dlouhý
Jsi expert na efektivní využívání Claude AI s extended context window. Pomoz mi optimálně využít 200K kontextové okno pro moji specifickou úlohu.
Moje úloha a kontext:
- Typ úlohy: [TYP ÚLOHY - např. "analýza kódové báze", "review dlouhého dokumentu", "refactoring projektu"]
- Velikost vstupních dat: [VELIKOST - např. "50 souborů / ~30K řádků kódu", "PDF dokument 150 stran", "API dokumentace 5 služeb"]
- Cíl analýzy: [CÍL - např. "najít security vulnerabilities", "identifikovat duplicitní kód", "vytvořit migration plan"]
- Časový rámec: [RÁMEC - např. "jednorázová analýza", "průběžné code reviews", "iterativní refactoring"]
Specifické požadavky:
- Co potřebuji z analýzy: [VÝSTUP - např. "konkrétní doporučení s odkazy na kód", "prioritizovaný seznam problémů", "step-by-step implementační plán"]
- Omezení/kontext: [OMEZENÍ - např. "legacy kódová báze bez testů", "musí být kompatibilní s Python 3.8", "nesmíme měnit public API"]
Vytvořte:
1. Strukturu, jak rozdělit a prezentovat data Claudovi pro maximální efektivitu
2. Konkrétní prompt strategie pro moji úlohu s využitím extended context
3. Techniky pro organizaci velkého množství informací v jednom promptu
4. Způsob, jak požádat Clauda o specifické odkazy zpět na zdrojový kód/dokument
5. Best practices pro iterativní práci s velkým kontextem
Moje úloha a kontext:
- Typ úlohy: [TYP ÚLOHY - např. "analýza kódové báze", "review dlouhého dokumentu", "refactoring projektu"]
- Velikost vstupních dat: [VELIKOST - např. "50 souborů / ~30K řádků kódu", "PDF dokument 150 stran", "API dokumentace 5 služeb"]
- Cíl analýzy: [CÍL - např. "najít security vulnerabilities", "identifikovat duplicitní kód", "vytvořit migration plan"]
- Časový rámec: [RÁMEC - např. "jednorázová analýza", "průběžné code reviews", "iterativní refactoring"]
Specifické požadavky:
- Co potřebuji z analýzy: [VÝSTUP - např. "konkrétní doporučení s odkazy na kód", "prioritizovaný seznam problémů", "step-by-step implementační plán"]
- Omezení/kontext: [OMEZENÍ - např. "legacy kódová báze bez testů", "musí být kompatibilní s Python 3.8", "nesmíme měnit public API"]
Vytvořte:
1. Strukturu, jak rozdělit a prezentovat data Claudovi pro maximální efektivitu
2. Konkrétní prompt strategie pro moji úlohu s využitím extended context
3. Techniky pro organizaci velkého množství informací v jednom promptu
4. Způsob, jak požádat Clauda o specifické odkazy zpět na zdrojový kód/dokument
5. Best practices pro iterativní práci s velkým kontextem
Příklad použití
Vstup:
Typ úlohy: Analýza bezpečnosti e-commerce aplikace (React frontend + Node.js backend)
Velikost vstupních dat: 85 souborů / ~45K řádků kódu
- Frontend: 50 React komponent, 15 custom hooks, Redux store
- Backend: 20 Express routes, 15 database models, middleware
- Konfigurace: Docker, Nginx, CI/CD pipelines
Cíl analýzy: Identifikovat security vulnerabilities, zejména:
- XSS a CSRF rizika
- SQL injection možnosti
- Authentication/authorization chyby
- API endpoint security
- Sensitive data handling
Časový rámec: Jednorázový comprehensive security audit před production launch
Specifické požadavky:
- Co potřebuji: Prioritizovaný seznam vulnerabilities s severity ratings, konkrétní odkazy na problémový kód, doporučení jak opravit
- Omezení: Aplikace musí zůstat kompatibilní s existující MySQL databází, nemůžeme měnit authentication flow (používáme OAuth2)
Velikost vstupních dat: 85 souborů / ~45K řádků kódu
- Frontend: 50 React komponent, 15 custom hooks, Redux store
- Backend: 20 Express routes, 15 database models, middleware
- Konfigurace: Docker, Nginx, CI/CD pipelines
Cíl analýzy: Identifikovat security vulnerabilities, zejména:
- XSS a CSRF rizika
- SQL injection možnosti
- Authentication/authorization chyby
- API endpoint security
- Sensitive data handling
Časový rámec: Jednorázový comprehensive security audit před production launch
Specifické požadavky:
- Co potřebuji: Prioritizovaný seznam vulnerabilities s severity ratings, konkrétní odkazy na problémový kód, doporučení jak opravit
- Omezení: Aplikace musí zůstat kompatibilní s existující MySQL databází, nemůžeme měnit authentication flow (používáme OAuth2)
Výstup:
# Komplexní Průvodce: Claude Extended Context pro Security Audit
## Část 1: Příprava Dat pro 200K Context Window
### Struktura Pro Maximální Efektivitu
Claude může efektivně pracovat s ~200,000 tokeny (přibližně 150,000 slov nebo 600 stran textu). Pro bezpečnostní audit e-commerce aplikace:
**Kalkulace velikosti:**
```
Frontend (50 React komponent, 15 hooks): ~20,000 tokenů
Backend (20 routes, 15 models): ~15,000 tokenů
Middleware & auth logic: ~5,000 tokenů
Database schemas & queries: ~3,000 tokenů
Configuration files (Docker, Nginx): ~2,000 tokenů
API documentation: ~5,000 tokenů
Authentication flow diagram: ~1,000 tokenů
Instruction prompt: ~3,000 tokenů
-----------------------------------------------------------
CELKEM: ~54,000 tokenů (✅ v rámci limitu)
```
### Doporučená Struktura Promptu
```markdown
# E-Commerce Security Audit Request
## Project Overview
- **Type:** Full-stack e-commerce application
- **Stack:** React (frontend) + Node.js/Express (backend) + MySQL
- **Authentication:** OAuth2 (Google, Facebook)
- **Payment:** Stripe integration
- **Scale:** ~5,000 active users, ~1M requests/month
## Audit Scope
Comprehensive security review focusing on:
1. XSS and CSRF vulnerabilities
2. SQL injection risks
3. Authentication and authorization flaws
4. API endpoint security
5. Sensitive data handling (PII, payment info)
6. File upload security
7. Rate limiting and DDoS protection
## Output Format Requirements
For each finding, provide:
- **Severity:** CRITICAL / HIGH / MEDIUM / LOW
- **Category:** XSS / SQLi / Auth / API / Data Handling / etc.
- **Location:** Exact file path and line numbers
- **Vulnerable Code:** Quote the problematic code snippet
- **Exploitation Scenario:** How attacker could exploit
- **Fix Recommendation:** Specific code changes with secure example
- **Priority:** Fix immediately / Before launch / Post-launch improvement
## Constraints
- Must remain compatible with MySQL 5.7
- Cannot modify OAuth2 authentication flow (used by mobile app too)
- Must maintain backward compatibility with API v1 (mobile app users)
---
# FRONTEND CODE
## File: src/components/ProductReview.jsx
### Purpose: User product reviews with rich text editor
```javascript
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { submitReview } from '../actions/reviewActions';
function ProductReview({ productId }) {
const [reviewText, setReviewText] = useState('');
const [rating, setRating] = useState(5);
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
// Submit review
dispatch(submitReview({
productId,
rating,
reviewText // ⚠️ Potentially problematic - no sanitization
}));
setReviewText('');
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Rating:</label>
<input
type="number"
min="1"
max="5"
value={rating}
onChange={(e) => setRating(e.target.value)}
/>
</div>
<div>
<label>Review:</label>
{/* ⚠️ Using dangerouslySetInnerHTML */}
<div
contentEditable
dangerouslySetInnerHTML={{ __html: reviewText }}
onBlur={(e) => setReviewText(e.target.innerHTML)}
/>
</div>
<button type="submit">Submit Review</button>
</form>
);
}
export default ProductReview;
```
## File: src/components/SearchBar.jsx
### Purpose: Product search with suggestions
```javascript
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
function SearchBar() {
const [query, setQuery] = useState('');
const [suggestions, setSuggestions] = useState([]);
const history = useHistory();
useEffect(() => {
if (query.length > 2) {
// Fetch suggestions from API
fetch(`/api/search/suggestions?q=${query}`) // ⚠️ No URL encoding
.then(res => res.json())
.then(data => setSuggestions(data));
}
}, [query]);
const handleSearch = () => {
// ⚠️ Query parameter not sanitized
history.push(`/search?q=${query}`);
};
return (
<div className="search-bar">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
placeholder="Search products..."
/>
{suggestions.length > 0 && (
<ul className="suggestions">
{suggestions.map((item, idx) => (
/* ⚠️ Using dangerouslySetInnerHTML with API data */
<li
key={idx}
dangerouslySetInnerHTML={{ __html: item.highlighted }}
onClick={() => history.push(`/product/${item.id}`)}
/>
))}
</ul>
)}
</div>
);
}
export default SearchBar;
```
## File: src/components/UserProfile.jsx
### Purpose: User profile display and edit
```javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserProfile() {
const [user, setUser] = useState(null);
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
// ⚠️ No CSRF token
axios.get('/api/user/profile')
.then(res => setUser(res.data))
.catch(err => console.error(err));
}, []);
const handleUpdate = async (userData) => {
try {
// ⚠️ No CSRF protection
await axios.put('/api/user/profile', userData);
setIsEditing(false);
} catch (error) {
console.error('Update failed:', error);
}
};
if (!user) return <div>Loading...</div>;
return (
<div className="user-profile">
{/* ⚠️ Displaying user.bio without sanitization */}
<div className="bio" dangerouslySetInnerHTML={{ __html: user.bio }} />
{isEditing && (
<form onSubmit={(e) => {
e.preventDefault();
const formData = new FormData(e.target);
handleUpdate(Object.fromEntries(formData));
}}>
<input name="name" defaultValue={user.name} />
<input name="email" defaultValue={user.email} />
<textarea name="bio" defaultValue={user.bio} />
<button type="submit">Save</button>
</form>
)}
</div>
);
}
export default UserProfile;
```
[... další 47 React komponent ...]
---
# BACKEND CODE
## File: routes/productRoutes.js
### Purpose: Product CRUD operations
```javascript
const express = require('express');
const router = express.Router();
const { authenticateUser } = require('../middleware/auth');
const db = require('../config/database');
// Get products with filters
router.get('/products', async (req, res) => {
const { category, minPrice, maxPrice, search } = req.query;
// ⚠️ SQL injection vulnerability - string concatenation
let query = 'SELECT * FROM products WHERE 1=1';
if (category) {
query += ` AND category = '${category}'`; // ⚠️ Unescaped
}
if (minPrice) {
query += ` AND price >= ${minPrice}`; // ⚠️ No validation
}
if (maxPrice) {
query += ` AND price <= ${maxPrice}`;
}
if (search) {
query += ` AND name LIKE '%${search}%'`; // ⚠️ CRITICAL: SQLi vector
}
try {
const results = await db.query(query);
res.json(results);
} catch (error) {
res.status(500).json({ error: error.message }); // ⚠️ Leaking error details
}
});
// Get single product
router.get('/products/:id', async (req, res) => {
const { id } = req.params;
// ⚠️ No input validation
const query = `SELECT * FROM products WHERE id = ${id}`;
try {
const result = await db.query(query);
res.json(result[0]);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Create product review
router.post('/products/:id/reviews', authenticateUser, async (req, res) => {
const { id } = req.params;
const { rating, reviewText } = req.body;
const userId = req.user.id;
// ⚠️ No XSS sanitization on reviewText
// ⚠️ No validation on rating range
const query = `
INSERT INTO reviews (product_id, user_id, rating, review_text, created_at)
VALUES (${id}, ${userId}, ${rating}, '${reviewText}', NOW())
`; // ⚠️ SQL injection vulnerability
try {
await db.query(query);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
```
## File: routes/userRoutes.js
### Purpose: User account management
```javascript
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const db = require('../config/database');
// User registration
router.post('/register', async (req, res) => {
const { email, password, name } = req.body;
// ⚠️ Weak password validation
if (password.length < 6) {
return res.status(400).json({ error: 'Password too short' });
}
// ⚠️ No email validation
const hashedPassword = await bcrypt.hash(password, 10);
// ⚠️ SQL injection possible
const query = `
INSERT INTO users (email, password, name, created_at)
VALUES ('${email}', '${hashedPassword}', '${name}', NOW())
`;
try {
await db.query(query);
res.json({ success: true });
} catch (error) {
// ⚠️ Leaking whether email exists
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({ error: 'Email already registered' });
}
res.status(500).json({ error: error.message });
}
});
// User login
router.post('/login', async (req, res) => {
const { email, password } = req.body;
// ⚠️ SQL injection
const query = `SELECT * FROM users WHERE email = '${email}'`;
const users = await db.query(query);
if (users.length === 0) {
// ⚠️ Information leakage - different message for non-existent user
return res.status(401).json({ error: 'User not found' });
}
const user = users[0];
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
// ⚠️ Information leakage - different message for wrong password
return res.status(401).json({ error: 'Incorrect password' });
}
// ⚠️ No rate limiting - brute force possible
const token = jwt.sign(
{ id: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '7d' } // ⚠️ Long expiration
);
res.json({
token,
user: {
id: user.id,
email: user.email,
name: user.name,
isAdmin: user.is_admin // ⚠️ Exposing admin status to client
}
});
});
// Get user profile
router.get('/profile', authenticateUser, async (req, res) => {
const userId = req.user.id;
// ⚠️ Returning sensitive data
const query = `SELECT * FROM users WHERE id = ${userId}`;
const user = await db.query(query);
// ⚠️ Sending password hash to client
res.json(user[0]);
});
// Update user profile
router.put('/profile', authenticateUser, async (req, res) => {
const userId = req.user.id;
const { name, bio, email } = req.body;
// ⚠️ No CSRF protection
// ⚠️ Mass assignment vulnerability - user can change anything
const query = `
UPDATE users
SET name = '${name}', bio = '${bio}', email = '${email}'
WHERE id = ${userId}
`;
try {
await db.query(query);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
```
## File: routes/paymentRoutes.js
### Purpose: Payment processing with Stripe
```javascript
const express = require('express');
const router = express.Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const { authenticateUser } = require('../middleware/auth');
const db = require('../config/database');
// Create payment intent
router.post('/create-payment-intent', authenticateUser, async (req, res) => {
const { amount, orderId } = req.body;
const userId = req.user.id;
// ⚠️ No validation that user owns this order
// ⚠️ No validation of amount
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: amount * 100, // ⚠️ Client-controlled amount!
currency: 'usd',
metadata: { orderId, userId }
});
res.json({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Webhook for payment confirmation
router.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
sig,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
// ⚠️ No logging of failed webhook verification
return res.status(400).send(`Webhook Error: ${err.message}`);
}
if (event.type === 'payment_intent.succeeded') {
const paymentIntent = event.data.object;
const { orderId } = paymentIntent.metadata;
// ⚠️ No transaction - race condition possible
await db.query(`
UPDATE orders
SET status = 'paid', payment_id = '${paymentIntent.id}'
WHERE id = ${orderId}
`);
}
res.json({ received: true });
});
module.exports = router;
```
[... dalších 17 route souborů ...]
---
# MIDDLEWARE
## File: middleware/auth.js
### Purpose: JWT authentication middleware
```javascript
const jwt = require('jsonwebtoken');
const db = require('../config/database');
async function authenticateUser(req, res, next) {
const token = req.headers.authorization?.split('\1')[1]; // Bearer <token>
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// ⚠️ Trusting JWT payload without database check
// ⚠️ No validation if user was deleted or banned
req.user = decoded;
next();
} catch (error) {
// ⚠️ Exposing JWT errors
res.status(401).json({ error: error.message });
}
}
function requireAdmin(req, res, next) {
// ⚠️ Checking isAdmin from JWT - client could tamper
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Admin access required' });
}
next();
}
module.exports = { authenticateUser, requireAdmin };
```
## File: middleware/cors.js
### Purpose: CORS configuration
```javascript
const cors = require('cors');
const corsOptions = {
// ⚠️ Wildcard origin in production
origin: '*',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
};
module.exports = cors(corsOptions);
```
[... další middleware ...]
---
# DATABASE MODELS
## File: models/User.js
### Purpose: User model and methods
```javascript
const db = require('../config/database');
class User {
static async findByEmail(email) {
// ⚠️ SQL injection if used with unsanitized input
const query = `SELECT * FROM users WHERE email = '${email}'`;
const results = await db.query(query);
return results[0];
}
static async create(userData) {
const { email, password, name } = userData;
// ⚠️ No input validation
// ⚠️ SQL injection vulnerability
const query = `
INSERT INTO users (email, password, name, created_at)
VALUES ('${email}', '${password}', '${name}', NOW())
`;
const result = await db.query(query);
return result.insertId;
}
static async updateProfile(userId, updates) {
// ⚠️ Mass assignment - accepting any field
const setClause = Object.entries(updates)
.map(([key, value]) => `${key} = '${value}'`)
.join(', ');
// ⚠️ SQL injection
const query = `UPDATE users SET ${setClause} WHERE id = ${userId}`;
await db.query(query);
}
}
module.exports = User;
```
[... dalších 14 model souborů ...]
---
# CONFIGURATION
## File: config/database.js
### Purpose: MySQL database connection
```javascript
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
// ⚠️ No connection pool limits
// ⚠️ No connection timeout
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = {
query: async (sql, params) => {
const [results] = await pool.execute(sql, params);
return results;
}
};
```
## File: .env (example - not actual production values)
```env
# Database
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password123 # ⚠️ Weak password
DB_NAME=ecommerce
# JWT
JWT_SECRET=mysecretkey123 # ⚠️ Weak secret
JWT_EXPIRATION=7d
# Stripe
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# OAuth
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=... # ⚠️ In repository
FACEBOOK_APP_ID=...
FACEBOOK_APP_SECRET=... # ⚠️ In repository
# Server
PORT=3000
NODE_ENV=production
# ⚠️ Debug mode enabled in production
DEBUG=true
VERBOSE_ERRORS=true
```
## File: docker-compose.yml
### Purpose: Docker services configuration
```yaml
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000" # ⚠️ Exposing directly without reverse proxy
environment:
- NODE_ENV=production
# ⚠️ Running as root
# ⚠️ No resource limits
mysql:
image: mysql:5.7
ports:
- "3306:3306" # ⚠️ Exposing MySQL to public
environment:
MYSQL_ROOT_PASSWORD: password123 # ⚠️ Hardcoded password
MYSQL_DATABASE: ecommerce
# ⚠️ No volume for data persistence in this example
```
---
# API DOCUMENTATION EXCERPT
## Authentication Endpoints
**POST /api/login**
- Body: `{ email, password }`
- Returns: `{ token, user }`
- ⚠️ No rate limiting documented
**POST /api/register**
- Body: `{ email, password, name }`
- Returns: `{ success: true }`
## Product Endpoints
**GET /api/products?search={query}&category={cat}**
- Public endpoint
- Returns: Array of products
- ⚠️ Search parameter not sanitized
**POST /api/products/:id/reviews**
- Requires authentication
- Body: `{ rating, reviewText }`
- ⚠️ No mention of XSS prevention
---
# ANALYSIS INSTRUCTIONS
Based on the above codebase:
1. **Identify ALL security vulnerabilities** across frontend, backend, and configuration
2. **Prioritize findings** by exploitability and business impact
3. **Provide specific line-by-line references** for each vulnerability
4. **Include exploitation scenarios** showing exactly how attacker could exploit each issue
5. **Give concrete fix recommendations** with secure code examples
6. **Consider the constraints:**
- Must maintain MySQL compatibility
- Cannot change OAuth2 flow
- Must support existing API for mobile app
For each finding, use this format:
## [SEVERITY] [Category]: [Brief Title]
**Location:** `path/to/file.js:123-145`
**Vulnerable Code:**
```javascript
// Exact code snippet
```
**Exploitation Scenario:**
[Step-by-step how to exploit]
**Business Impact:**
[What attacker gains]
**Fix Recommendation:**
```javascript
// Secure code example
```
**References:**
- [OWASP guideline link]
- [CWE number]
Begin the comprehensive security audit now.
```
---
## Proč Tato Struktura Funguje?
### 1. **Explicitní Instrukce na Začátku**
```markdown
## Output Format Requirements
For each finding, provide:
- **Severity:** CRITICAL / HIGH / MEDIUM / LOW
- **Location:** Exact file path and line numbers
...
```
Tím zajistíte, že Claude:**
- Ví přesně, jaký formát výstupu očekáváte
- Bude poskytovat strukturované, konzistentní odpovědi
- Zahrne všechny požadované informace
### 2. **Kompletní Kontext v Jednom Promptu**
Místo postupného nahrávání souborů:
```
❌ Špatný přístup:
"Přečti si tento soubor... OK, teď tento... Teď analyzuj..."
```
Použijte jeden velký prompt:
```
✅ Správný přístup:
"Zde je celý projekt (85 souborů). Analyzuj vše najednou."
```
**Výhody:**
- Claude vidí celý obraz, nejen jednotlivé části
- Může identifikovat cross-file vulnerabilities
- Poskytuje kontextuální analýzu (např. "tato XSS na frontendu je problém, protože backend nevaliduje")
### 3. **Komentáře ⚠️ Jako Vodítka**
V kódu jsem přidal `⚠️` komentáře u problematických částí:
```javascript
const query = `SELECT * FROM products WHERE name LIKE '%${search}%'`; // ⚠️ SQLi vector
```
**Účel:**
- Usnadňují Claudovi identifikaci problémů
- Slouží jako "cheat sheet" pro rychlejší analýzu
- Nejsou nutné, ale výrazně zrychlují analýzu (Claude najde problémy i bez nich)
### 4. **Strukturované Sekce**
Rozdělení do jasných sekcí:
```markdown
# FRONTEND CODE
[všechny React komponenty]
# BACKEND CODE
[všechny Express routes]
# MIDDLEWARE
[authentication, CORS, etc.]
# DATABASE MODELS
[Sequelize/mongoose models]
# CONFIGURATION
[.env, docker-compose, nginx]
```
**Proč to pomáhá:**
- Claude může odkazovat na sekce: "V sekci BACKEND CODE, soubor userRoutes.js:45..."
- Snadnější navigace ve velkém kontextu
- Lepší organizace výstupu
---
## Část 2: Prompt Strategie Pro Extended Context
### Strategie 1: "Dump Everything" Approach
**Kdy použít:** Jednorázové comprehensive audity, analýzy celých projektů
**Jak:**
1. Zkompilujte všechny soubory do jednoho Markdown dokumentu
2. Přidejte jasné sekční rozdělení
3. Na začátek dejte instrukce a očekávaný výstupní formát
4. Na konec dejte explicitní "Begin analysis now"
**Příklad:**
```markdown
# Comprehensive Codebase Analysis
## Instructions
[Co má Claude dělat]
## Expected Output Format
[Jak má vypadat výstup]
---
# CODEBASE
## Frontend (React)
[všechny komponenty]
## Backend (Node.js)
[všechny routes, modely]
## Tests
[test soubory]
## Configuration
[config soubory]
---
## Analysis Request
Begin comprehensive analysis focusing on:
1. [specific aspect]
2. [specific aspect]
3. [specific aspect]
```
### Strategie 2: "Annotated Context" Approach
**Kdy použít:** Code reviews, refactoring guidance, debugging složitých issues
**Jak:**
1. Přidejte anotace k důležitým částem kódu:
- `// NOTE: This is important because...`
- `// QUESTION: Should we change this?`
- `// CONTEXT: This was added in PR #123 to fix...`
2. Zvýrazněte oblasti zájmu
3. Poskytněte historický kontext
**Příklad:**
```javascript
// FILE: src/components/PaymentForm.jsx
// CONTEXT: Originally used Stripe Elements v1, migrated to v2 in PR #456
// QUESTION: Can we simplify this with Stripe's new Payment Element?
function PaymentForm() {
const [clientSecret, setClientSecret] = useState(null);
useEffect(() => {
// NOTE: We fetch clientSecret on mount to prevent CSRF
// See security review doc: docs/security/payment-flow.md
fetch('/api/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': getCsrfToken() // NOTE: Required for POST requests
},
body: JSON.stringify({ orderId })
})
.then(res => res.json())
.then(data => setClientSecret(data.clientSecret));
}, [orderId]);
// ... rest of component
}
```
**Claude pak může odpovědět:**
```markdown
## PaymentForm Simplification Opportunities
### Question: Can we simplify with Payment Element?
**Yes, significant simplification possible.**
Current implementation (src/components/PaymentForm.jsx:15-45) uses separate
Card Number, Card Expiry, and Card CVC elements. Stripe's Payment Element
consolidates this into single component.
**Before (current):**
[váš current kód]
**After (with Payment Element):**
```jsx
// Simplified with Payment Element
function PaymentForm() {
const stripe = useStripe();
const elements = useElements();
// SECURITY NOTE: clientSecret fetching preserved from original (line 18-29)
const [clientSecret, setClientSecret] = useState(null);
useEffect(() => {
// Keep existing CSRF-protected fetch logic
fetch('/api/create-payment-intent', ...)
}, [orderId]);
return (
<form onSubmit={handleSubmit}>
{/* Single component replaces 3 separate elements */}
<PaymentElement />
<button type="submit">Pay</button>
</form>
);
}
```
**Benefits:**
- 40% less code (150 lines → 90 lines)
- Built-in validation
- Automatic support for new payment methods (Apple Pay, Google Pay)
- Maintains existing CSRF protection (line 24-26)
**Migration Path:**
1. Update Stripe.js dependency to v3+ (package.json)
2. Replace CardElement components with PaymentElement (PaymentForm.jsx:30-60)
3. Update E2E tests (tests/e2e/payment.spec.js:45-120)
4. No backend changes required ✓
**Constraints Check:**
✓ Compatible with existing /api/create-payment-intent endpoint
✓ CSRF protection maintained
✓ No breaking changes for mobile app (backend unchanged)
```
### Strategie 3: "Focused Context + Reference" Approach
**Kdy použít:** Debugging specific issue s potřebou širšího kontextu
**Jak:**
1. Na začátek dejte focused problém
2. Pod to dejte relevant context
3. Na konec přidejte full codebase jako referenci
**Příklad:**
```markdown
# Bug Report: Duplicate Orders Created on Payment
## Problem
Users occasionally get charged twice for the same order. Database shows duplicate
order records with same items but different IDs.
## Reproduction Steps
1. User adds items to cart
2. Proceeds to checkout
3. Clicks "Pay Now"
4. Stripe webhook fires twice within 100ms
5. Both webhooks create separate order records
## Suspicious Code
### File: routes/paymentRoutes.js:45-67 (Webhook Handler)
```javascript
router.post('/webhook', async (req, res) => {
const event = stripe.webhooks.constructEvent(req.body, sig, secret);
if (event.type === 'payment_intent.succeeded') {
const { orderId } = event.data.object.metadata;
// ⚠️ Potential race condition - no locking mechanism
await db.query(`
UPDATE orders SET status = 'paid' WHERE id = ${orderId}
`);
// ⚠️ This might run twice if webhook is retried
await createInvoice(orderId);
await sendConfirmationEmail(orderId);
}
res.json({ received: true });
});
```
### File: models/Order.js:120-145 (Order Creation)
```javascript
static async create(orderData) {
const orderId = generateOrderId();
await db.query(`
INSERT INTO orders (id, user_id, items, total, status)
VALUES (${orderId}, ${orderData.userId}, '${JSON.stringify(orderData.items)}',
${orderData.total}, 'pending')
`);
return orderId;
}
```
## Question
What's causing the duplicate orders and how do we fix it with:
1. Zero data loss (all orders must be recorded)
2. Zero duplicate charges (no double billing)
3. Minimal changes to existing flow (mobile app compatibility)
---
# FULL CODEBASE FOR REFERENCE
[... celý codebase follows ...]
```
**Claude pak analyzuje:**
1. Identifikuje root cause (race condition v webhook handleru)
2. Navrhne řešení (idempotency keys, database locks)
3. Ukáže jak implementovat s ohledem na constraints
4. Použije kontext z celého codebase k identifikaci všech souvisejících míst, která je třeba změnit
---
## Část 3: Techniky Pro Organizaci Informací
### Technika 1: Hierarchické Nadpisy
Používejte Markdown hierarchii pro snadnou navigaci:
```markdown
# PROJECT OVERVIEW (level 1)
## Frontend (level 2)
### Components (level 3)
#### Authentication (level 4)
##### LoginForm.jsx (level 5)
```
Claude pak může odkazovat: "In **Frontend → Components → Authentication → LoginForm.jsx**"
### Technika 2: Inline Documentation
Dokumentujte účel každého souboru na jeho začátku:
```javascript
// FILE: src/services/PaymentService.js
// PURPOSE: Handles Stripe payment processing and webhook verification
// DEPENDENCIES: stripe, database, email-service
// USED BY: PaymentController, WebhookHandler
// SECURITY: Contains sensitive Stripe API key - never log
// LAST MODIFIED: 2025-01-05 (PR #456 - Added retry logic)
class PaymentService {
// ...
}
```
### Technika 3: Cross-Reference Markers
Přidejte reference mezi souvisejícími soubory:
```javascript
// FILE: frontend/src/components/CheckoutForm.jsx
function CheckoutForm() {
const handleSubmit = async () => {
// BACKEND REFERENCE: See backend/routes/paymentRoutes.js:34-56
// API DOCS: See docs/api/payments.md#create-payment-intent
const response = await fetch('/api/create-payment-intent', {
method: 'POST',
body: JSON.stringify({ orderId, amount })
});
};
}
```
```javascript
// FILE: backend/routes/paymentRoutes.js
// FRONTEND CALLERS:
// - frontend/src/components/CheckoutForm.jsx:45
// - frontend/src/pages/OrderSummary.jsx:120
router.post('/create-payment-intent', async (req, res) => {
// ...
});
```
### Technika 4: Dependency Graph
Na začátek promptu dejte dependency graph:
```markdown
# Dependency Graph
## High-Level Architecture
```
Frontend (React)
↓ HTTP requests
Backend API (Express)
↓ queries
Database (MySQL)
↓ events
Webhook Handler
↓ notifications
Email Service
```
## File-Level Dependencies
### PaymentFlow
```
CheckoutForm.jsx
→ calls → paymentRoutes.js:/create-payment-intent
→ calls → PaymentService.js:createIntent()
→ calls → Stripe API
→ stores → Database:orders table
→ triggers → OrderModel.afterCreate hook
→ calls → EmailService.sendConfirmation()
```
```
Claude pak rozumí celému flow a může identifikovat problémy na kterémkoliv místě v řetězci.
---
## Část 4: Získání Specifických Odkazů
### Problém: Vágní Odpovědi
**Špatný výstup od Clauda:**
"V komponentě PaymentForm máte security issue s XSS."
### Řešení: Explicit Output Format
V instrukčních části promptu specifikujte:
```markdown
## Required Output Format
For EVERY finding, you MUST include:
1. **Exact Location**
- Format: `path/to/file.js:startLine-endLine`
- Example: `src/components/PaymentForm.jsx:45-67`
2. **Vulnerable Code Snippet**
- Quote the EXACT code (copy-paste from the input)
- Include 2-3 lines of context before/after
3. **Specific Line Reference in Explanation**
- When explaining, reference: "On line 52, the variable..."
- NOT: "The code does..."
Example of GOOD output:
## [CRITICAL] XSS: Unescaped User Input in Review Display
**Location:** `src/components/ProductReview.jsx:45-67`
**Vulnerable Code (lines 45-50):**
```jsx
function ProductReview({ review }) {
return (
<div className="review">
<div dangerouslySetInnerHTML={{ __html: review.text }} />
</div>
);
}
```
**Issue:** On **line 47**, the `review.text` is rendered with `dangerouslySetInnerHTML`
without sanitization, allowing stored XSS attacks.
[... rest of finding ...]
```
### Jak Claude Zajistí Přesné Reference?
**1. Explicitně požadujte čísla řádků:**
```markdown
When referencing code:
- ALWAYS include the file path AND line numbers
- Format: path/to/file.js:123 or path/to/file.js:123-145 for ranges
- Quote the actual code from those lines
```
**2. Poskytněte číslované řádky v inputu:**
V Bash scriptu pro přípravu:
```bash
#!/bin/bash
OUTPUT_FILE="full-codebase.md"
echo "# Full Codebase with Line Numbers" > $OUTPUT_FILE
echo "" >> $OUTPUT_FILE
find src -name "*.js" -o -name "*.jsx" | while read file; do
echo "## File: $file" >> $OUTPUT_FILE
echo '```javascript' >> $OUTPUT_FILE
# Add line numbers
cat -n "$file" >> $OUTPUT_FILE
echo '```' >> $OUTPUT_FILE
echo "" >> $OUTPUT_FILE
done
```
Výstup:
```javascript
## File: src/components/PaymentForm.jsx
```javascript
1 import React, { useState } from 'react';
2 import { useStripe } from '@stripe/react-stripe-js';
3
4 function PaymentForm() {
5 const [amount, setAmount] = useState(0);
6
7 const handleSubmit = async () => {
8 // Vulnerable: no validation
9 await fetch('/api/payment', {
10 method: 'POST',
11 body: JSON.stringify({ amount }) // ⚠️ Client-controlled
12 });
13 };
```
Claude pak může přesně říct: "Na řádku 11 v src/components/PaymentForm.jsx..."
**3. Request Code Locations in Output:**
```markdown
## Output Template (use this EXACT format for every finding):
### [SEVERITY] [Category]: [Title]
**File:** `exact/path/to/file.js`
**Lines:** 123-145
**Function/Class:** `functionName()` or `ClassName`
**Vulnerable Code:**
```[language]
[quote exact lines from input, including line numbers]
```
**Issue Description:**
[Explain what's wrong, referencing specific line numbers]
**How to Exploit:**
[Step-by-step with examples]
**Fix:**
```[language]
[secure code replacement for the same lines]
```
**References:**
- OWASP: [link]
- CWE: [number]
```
---
## Část 5: Best Practices
### ✅ DO: Structure Your Context
```markdown
# PROJECT: E-Commerce Security Audit
## 1. EXECUTIVE SUMMARY
[2-3 sentences about the project]
## 2. AUDIT SCOPE
[What you want analyzed]
## 3. TECHNICAL CONTEXT
[Stack, versions, architecture]
## 4. CONSTRAINTS
[What cannot be changed]
## 5. OUTPUT REQUIREMENTS
[Exact format you want]
## 6. PRIORITY AREAS
[Where to focus most attention]
---
# CODE
[... structured code with clear sections ...]
---
# REFERENCES
## Architecture Diagrams
[Mermaid diagrams of system flow]
## API Documentation
[Swagger/OpenAPI specs]
## Previous Audit Findings
[Any known issues]
---
# ANALYSIS REQUEST
Begin comprehensive analysis now, following the output requirements in section 5.
```
### ✅ DO: Use Semantic Markers
```javascript
// 🔴 CRITICAL SECURITY ISSUE
const query = `SELECT * FROM users WHERE email = '${email}'`;
// 🟡 TODO: Refactor to use prepared statements
// 🟢 FIXED: Now using parameterized queries (as of 2025-01-05)
// 💭 CONTEXT: This was added to handle edge case from issue #123
// 🔗 RELATED: See PaymentService.js:45-67 for similar pattern
```
Claude pak může používat stejné markery v odpovědích.
### ✅ DO: Provide Example Output
Ukažte Claudovi přesně, jak má výstup vypadat:
```markdown
## Example of Expected Output
Here's EXACTLY the format I want:
### [CRITICAL] SQL Injection: Unparameterized Query in User Login
**Location:** `backend/routes/authRoutes.js:23-29`
**Vulnerable Code:**
```javascript
// Line 23-29
router.post('/login', async (req, res) => {
const { email } = req.body;
const query = `SELECT * FROM users WHERE email = '${email}'`; // ⚠️ SQLi
const results = await db.query(query);
});
```
**Exploitation:**
Attacker sends email: `' OR '1'='1' --`
Result: `SELECT * FROM users WHERE email = '' OR '1'='1' --'`
Bypasses authentication, returns all users.
**Fix:**
```javascript
// Use parameterized query
router.post('/login', async (req, res) => {
const { email } = req.body;
const query = 'SELECT * FROM users WHERE email = ?';
const results = await db.query(query, [email]); // ✅ Parameterized
});
```
**References:**
- OWASP SQL Injection: https://owasp.org/www-community/attacks/SQL_Injection
- CWE-89: SQL Injection
---
Now provide ALL findings in this exact format.
```
### ✅ DO: Number Everything
Numbering pomáhá v navigaci:
```markdown
# CODEBASE
## 1. Frontend
### 1.1 React Components
#### 1.1.1 Authentication
##### 1.1.1.1 LoginForm.jsx
#### 1.1.2 Payment
##### 1.1.2.1 CheckoutForm.jsx
### 1.2 Redux Store
#### 1.2.1 Actions
##### 1.2.1.1 authActions.js
## 2. Backend
### 2.1 Routes
#### 2.1.1 authRoutes.js
#### 2.1.2 paymentRoutes.js
```
Claude pak může říct: "See section 1.1.2.1 (CheckoutForm.jsx) and section 2.1.2 (paymentRoutes.js)"
### ❌ DON'T: Dump Unstructured Code
```javascript
// ❌ ŠPATNĚ
// Just pasting random files without context
class User {}
function login() {}
router.post('/payment', ...)
...
```
### ❌ DON'T: Mix Languages in Code Blocks
```javascript
// ❌ ŠPATNĚ - mělo by být ```jsx
<Component prop="value" />
```
```jsx
// ✅ SPRÁVNĚ
<Component prop="value" />
```
### ❌ DON'T: Forget to Update Context
Pokud děláte iterativní work, aktualizujte kontext:
```markdown
## Iteration 2: After Fixing SQL Injection Issues
### Changes Made Since Last Analysis
1. All queries now use parameterized statements (backend/models/*.js)
2. Added input validation middleware (backend/middleware/validation.js)
3. Updated database queries in routes (backend/routes/*.js)
### Remaining Issues to Address
[list from previous analysis]
### New Code for Review
[updated code with changes marked]
### Request
Review the updated code and:
1. Confirm SQL injection issues are properly fixed
2. Identify any NEW issues introduced by changes
3. Check for any remaining vulnerabilities
```
---
## Závěr
**Claude Extended Context (200K tokenů) je mocný nástroj**, ale efektivita závisí na struktuře vašeho inputu.
**Klíčové Takeaways:**
1. **Struktura je vše:** Markdown hierarchie, jasné sekce, numbered outline
2. **Explicitní instrukce:** Řekněte přesně, co chcete a v jakém formátu
3. **Poskytněte kontext:** Annotations, comments, dependency graphs
4. **Očekávejte přesnost:** Vyžadujte file paths a line numbers v každém outputu
5. **Používejte markers:** ⚠️ 🔴 🟡 🟢 💭 🔗 pro sémantické zvýraznění
6. **Ukažte příklady:** Example output template zajistí konzistenci
7. **Iterujte:** Update context, track changes, build on previous analyses
**S těmito technikami můžete Claude efektivně využít pro:**
- ✅ Comprehensive security audits (jako náš příklad)
- ✅ Large-scale refactoring planning
- ✅ Complex debugging s wide-ranging root causes
- ✅ Architecture reviews a redesigns
- ✅ Documentation generation from code
- ✅ Test coverage analysis
- ✅ Performance bottleneck identification
Extended context není jen o množství dat - **je o inteligentní organizaci informací** tak, aby Claude mohl efektivně najít patterns, identifikovat problémy a poskytovat actionable recommendations.
## Část 1: Příprava Dat pro 200K Context Window
### Struktura Pro Maximální Efektivitu
Claude může efektivně pracovat s ~200,000 tokeny (přibližně 150,000 slov nebo 600 stran textu). Pro bezpečnostní audit e-commerce aplikace:
**Kalkulace velikosti:**
```
Frontend (50 React komponent, 15 hooks): ~20,000 tokenů
Backend (20 routes, 15 models): ~15,000 tokenů
Middleware & auth logic: ~5,000 tokenů
Database schemas & queries: ~3,000 tokenů
Configuration files (Docker, Nginx): ~2,000 tokenů
API documentation: ~5,000 tokenů
Authentication flow diagram: ~1,000 tokenů
Instruction prompt: ~3,000 tokenů
-----------------------------------------------------------
CELKEM: ~54,000 tokenů (✅ v rámci limitu)
```
### Doporučená Struktura Promptu
```markdown
# E-Commerce Security Audit Request
## Project Overview
- **Type:** Full-stack e-commerce application
- **Stack:** React (frontend) + Node.js/Express (backend) + MySQL
- **Authentication:** OAuth2 (Google, Facebook)
- **Payment:** Stripe integration
- **Scale:** ~5,000 active users, ~1M requests/month
## Audit Scope
Comprehensive security review focusing on:
1. XSS and CSRF vulnerabilities
2. SQL injection risks
3. Authentication and authorization flaws
4. API endpoint security
5. Sensitive data handling (PII, payment info)
6. File upload security
7. Rate limiting and DDoS protection
## Output Format Requirements
For each finding, provide:
- **Severity:** CRITICAL / HIGH / MEDIUM / LOW
- **Category:** XSS / SQLi / Auth / API / Data Handling / etc.
- **Location:** Exact file path and line numbers
- **Vulnerable Code:** Quote the problematic code snippet
- **Exploitation Scenario:** How attacker could exploit
- **Fix Recommendation:** Specific code changes with secure example
- **Priority:** Fix immediately / Before launch / Post-launch improvement
## Constraints
- Must remain compatible with MySQL 5.7
- Cannot modify OAuth2 authentication flow (used by mobile app too)
- Must maintain backward compatibility with API v1 (mobile app users)
---
# FRONTEND CODE
## File: src/components/ProductReview.jsx
### Purpose: User product reviews with rich text editor
```javascript
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { submitReview } from '../actions/reviewActions';
function ProductReview({ productId }) {
const [reviewText, setReviewText] = useState('');
const [rating, setRating] = useState(5);
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
// Submit review
dispatch(submitReview({
productId,
rating,
reviewText // ⚠️ Potentially problematic - no sanitization
}));
setReviewText('');
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Rating:</label>
<input
type="number"
min="1"
max="5"
value={rating}
onChange={(e) => setRating(e.target.value)}
/>
</div>
<div>
<label>Review:</label>
{/* ⚠️ Using dangerouslySetInnerHTML */}
<div
contentEditable
dangerouslySetInnerHTML={{ __html: reviewText }}
onBlur={(e) => setReviewText(e.target.innerHTML)}
/>
</div>
<button type="submit">Submit Review</button>
</form>
);
}
export default ProductReview;
```
## File: src/components/SearchBar.jsx
### Purpose: Product search with suggestions
```javascript
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
function SearchBar() {
const [query, setQuery] = useState('');
const [suggestions, setSuggestions] = useState([]);
const history = useHistory();
useEffect(() => {
if (query.length > 2) {
// Fetch suggestions from API
fetch(`/api/search/suggestions?q=${query}`) // ⚠️ No URL encoding
.then(res => res.json())
.then(data => setSuggestions(data));
}
}, [query]);
const handleSearch = () => {
// ⚠️ Query parameter not sanitized
history.push(`/search?q=${query}`);
};
return (
<div className="search-bar">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
placeholder="Search products..."
/>
{suggestions.length > 0 && (
<ul className="suggestions">
{suggestions.map((item, idx) => (
/* ⚠️ Using dangerouslySetInnerHTML with API data */
<li
key={idx}
dangerouslySetInnerHTML={{ __html: item.highlighted }}
onClick={() => history.push(`/product/${item.id}`)}
/>
))}
</ul>
)}
</div>
);
}
export default SearchBar;
```
## File: src/components/UserProfile.jsx
### Purpose: User profile display and edit
```javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserProfile() {
const [user, setUser] = useState(null);
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
// ⚠️ No CSRF token
axios.get('/api/user/profile')
.then(res => setUser(res.data))
.catch(err => console.error(err));
}, []);
const handleUpdate = async (userData) => {
try {
// ⚠️ No CSRF protection
await axios.put('/api/user/profile', userData);
setIsEditing(false);
} catch (error) {
console.error('Update failed:', error);
}
};
if (!user) return <div>Loading...</div>;
return (
<div className="user-profile">
{/* ⚠️ Displaying user.bio without sanitization */}
<div className="bio" dangerouslySetInnerHTML={{ __html: user.bio }} />
{isEditing && (
<form onSubmit={(e) => {
e.preventDefault();
const formData = new FormData(e.target);
handleUpdate(Object.fromEntries(formData));
}}>
<input name="name" defaultValue={user.name} />
<input name="email" defaultValue={user.email} />
<textarea name="bio" defaultValue={user.bio} />
<button type="submit">Save</button>
</form>
)}
</div>
);
}
export default UserProfile;
```
[... další 47 React komponent ...]
---
# BACKEND CODE
## File: routes/productRoutes.js
### Purpose: Product CRUD operations
```javascript
const express = require('express');
const router = express.Router();
const { authenticateUser } = require('../middleware/auth');
const db = require('../config/database');
// Get products with filters
router.get('/products', async (req, res) => {
const { category, minPrice, maxPrice, search } = req.query;
// ⚠️ SQL injection vulnerability - string concatenation
let query = 'SELECT * FROM products WHERE 1=1';
if (category) {
query += ` AND category = '${category}'`; // ⚠️ Unescaped
}
if (minPrice) {
query += ` AND price >= ${minPrice}`; // ⚠️ No validation
}
if (maxPrice) {
query += ` AND price <= ${maxPrice}`;
}
if (search) {
query += ` AND name LIKE '%${search}%'`; // ⚠️ CRITICAL: SQLi vector
}
try {
const results = await db.query(query);
res.json(results);
} catch (error) {
res.status(500).json({ error: error.message }); // ⚠️ Leaking error details
}
});
// Get single product
router.get('/products/:id', async (req, res) => {
const { id } = req.params;
// ⚠️ No input validation
const query = `SELECT * FROM products WHERE id = ${id}`;
try {
const result = await db.query(query);
res.json(result[0]);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Create product review
router.post('/products/:id/reviews', authenticateUser, async (req, res) => {
const { id } = req.params;
const { rating, reviewText } = req.body;
const userId = req.user.id;
// ⚠️ No XSS sanitization on reviewText
// ⚠️ No validation on rating range
const query = `
INSERT INTO reviews (product_id, user_id, rating, review_text, created_at)
VALUES (${id}, ${userId}, ${rating}, '${reviewText}', NOW())
`; // ⚠️ SQL injection vulnerability
try {
await db.query(query);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
```
## File: routes/userRoutes.js
### Purpose: User account management
```javascript
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const db = require('../config/database');
// User registration
router.post('/register', async (req, res) => {
const { email, password, name } = req.body;
// ⚠️ Weak password validation
if (password.length < 6) {
return res.status(400).json({ error: 'Password too short' });
}
// ⚠️ No email validation
const hashedPassword = await bcrypt.hash(password, 10);
// ⚠️ SQL injection possible
const query = `
INSERT INTO users (email, password, name, created_at)
VALUES ('${email}', '${hashedPassword}', '${name}', NOW())
`;
try {
await db.query(query);
res.json({ success: true });
} catch (error) {
// ⚠️ Leaking whether email exists
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({ error: 'Email already registered' });
}
res.status(500).json({ error: error.message });
}
});
// User login
router.post('/login', async (req, res) => {
const { email, password } = req.body;
// ⚠️ SQL injection
const query = `SELECT * FROM users WHERE email = '${email}'`;
const users = await db.query(query);
if (users.length === 0) {
// ⚠️ Information leakage - different message for non-existent user
return res.status(401).json({ error: 'User not found' });
}
const user = users[0];
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
// ⚠️ Information leakage - different message for wrong password
return res.status(401).json({ error: 'Incorrect password' });
}
// ⚠️ No rate limiting - brute force possible
const token = jwt.sign(
{ id: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '7d' } // ⚠️ Long expiration
);
res.json({
token,
user: {
id: user.id,
email: user.email,
name: user.name,
isAdmin: user.is_admin // ⚠️ Exposing admin status to client
}
});
});
// Get user profile
router.get('/profile', authenticateUser, async (req, res) => {
const userId = req.user.id;
// ⚠️ Returning sensitive data
const query = `SELECT * FROM users WHERE id = ${userId}`;
const user = await db.query(query);
// ⚠️ Sending password hash to client
res.json(user[0]);
});
// Update user profile
router.put('/profile', authenticateUser, async (req, res) => {
const userId = req.user.id;
const { name, bio, email } = req.body;
// ⚠️ No CSRF protection
// ⚠️ Mass assignment vulnerability - user can change anything
const query = `
UPDATE users
SET name = '${name}', bio = '${bio}', email = '${email}'
WHERE id = ${userId}
`;
try {
await db.query(query);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
```
## File: routes/paymentRoutes.js
### Purpose: Payment processing with Stripe
```javascript
const express = require('express');
const router = express.Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const { authenticateUser } = require('../middleware/auth');
const db = require('../config/database');
// Create payment intent
router.post('/create-payment-intent', authenticateUser, async (req, res) => {
const { amount, orderId } = req.body;
const userId = req.user.id;
// ⚠️ No validation that user owns this order
// ⚠️ No validation of amount
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: amount * 100, // ⚠️ Client-controlled amount!
currency: 'usd',
metadata: { orderId, userId }
});
res.json({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Webhook for payment confirmation
router.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
sig,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
// ⚠️ No logging of failed webhook verification
return res.status(400).send(`Webhook Error: ${err.message}`);
}
if (event.type === 'payment_intent.succeeded') {
const paymentIntent = event.data.object;
const { orderId } = paymentIntent.metadata;
// ⚠️ No transaction - race condition possible
await db.query(`
UPDATE orders
SET status = 'paid', payment_id = '${paymentIntent.id}'
WHERE id = ${orderId}
`);
}
res.json({ received: true });
});
module.exports = router;
```
[... dalších 17 route souborů ...]
---
# MIDDLEWARE
## File: middleware/auth.js
### Purpose: JWT authentication middleware
```javascript
const jwt = require('jsonwebtoken');
const db = require('../config/database');
async function authenticateUser(req, res, next) {
const token = req.headers.authorization?.split('\1')[1]; // Bearer <token>
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// ⚠️ Trusting JWT payload without database check
// ⚠️ No validation if user was deleted or banned
req.user = decoded;
next();
} catch (error) {
// ⚠️ Exposing JWT errors
res.status(401).json({ error: error.message });
}
}
function requireAdmin(req, res, next) {
// ⚠️ Checking isAdmin from JWT - client could tamper
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Admin access required' });
}
next();
}
module.exports = { authenticateUser, requireAdmin };
```
## File: middleware/cors.js
### Purpose: CORS configuration
```javascript
const cors = require('cors');
const corsOptions = {
// ⚠️ Wildcard origin in production
origin: '*',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
};
module.exports = cors(corsOptions);
```
[... další middleware ...]
---
# DATABASE MODELS
## File: models/User.js
### Purpose: User model and methods
```javascript
const db = require('../config/database');
class User {
static async findByEmail(email) {
// ⚠️ SQL injection if used with unsanitized input
const query = `SELECT * FROM users WHERE email = '${email}'`;
const results = await db.query(query);
return results[0];
}
static async create(userData) {
const { email, password, name } = userData;
// ⚠️ No input validation
// ⚠️ SQL injection vulnerability
const query = `
INSERT INTO users (email, password, name, created_at)
VALUES ('${email}', '${password}', '${name}', NOW())
`;
const result = await db.query(query);
return result.insertId;
}
static async updateProfile(userId, updates) {
// ⚠️ Mass assignment - accepting any field
const setClause = Object.entries(updates)
.map(([key, value]) => `${key} = '${value}'`)
.join(', ');
// ⚠️ SQL injection
const query = `UPDATE users SET ${setClause} WHERE id = ${userId}`;
await db.query(query);
}
}
module.exports = User;
```
[... dalších 14 model souborů ...]
---
# CONFIGURATION
## File: config/database.js
### Purpose: MySQL database connection
```javascript
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
// ⚠️ No connection pool limits
// ⚠️ No connection timeout
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = {
query: async (sql, params) => {
const [results] = await pool.execute(sql, params);
return results;
}
};
```
## File: .env (example - not actual production values)
```env
# Database
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password123 # ⚠️ Weak password
DB_NAME=ecommerce
# JWT
JWT_SECRET=mysecretkey123 # ⚠️ Weak secret
JWT_EXPIRATION=7d
# Stripe
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# OAuth
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=... # ⚠️ In repository
FACEBOOK_APP_ID=...
FACEBOOK_APP_SECRET=... # ⚠️ In repository
# Server
PORT=3000
NODE_ENV=production
# ⚠️ Debug mode enabled in production
DEBUG=true
VERBOSE_ERRORS=true
```
## File: docker-compose.yml
### Purpose: Docker services configuration
```yaml
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000" # ⚠️ Exposing directly without reverse proxy
environment:
- NODE_ENV=production
# ⚠️ Running as root
# ⚠️ No resource limits
mysql:
image: mysql:5.7
ports:
- "3306:3306" # ⚠️ Exposing MySQL to public
environment:
MYSQL_ROOT_PASSWORD: password123 # ⚠️ Hardcoded password
MYSQL_DATABASE: ecommerce
# ⚠️ No volume for data persistence in this example
```
---
# API DOCUMENTATION EXCERPT
## Authentication Endpoints
**POST /api/login**
- Body: `{ email, password }`
- Returns: `{ token, user }`
- ⚠️ No rate limiting documented
**POST /api/register**
- Body: `{ email, password, name }`
- Returns: `{ success: true }`
## Product Endpoints
**GET /api/products?search={query}&category={cat}**
- Public endpoint
- Returns: Array of products
- ⚠️ Search parameter not sanitized
**POST /api/products/:id/reviews**
- Requires authentication
- Body: `{ rating, reviewText }`
- ⚠️ No mention of XSS prevention
---
# ANALYSIS INSTRUCTIONS
Based on the above codebase:
1. **Identify ALL security vulnerabilities** across frontend, backend, and configuration
2. **Prioritize findings** by exploitability and business impact
3. **Provide specific line-by-line references** for each vulnerability
4. **Include exploitation scenarios** showing exactly how attacker could exploit each issue
5. **Give concrete fix recommendations** with secure code examples
6. **Consider the constraints:**
- Must maintain MySQL compatibility
- Cannot change OAuth2 flow
- Must support existing API for mobile app
For each finding, use this format:
## [SEVERITY] [Category]: [Brief Title]
**Location:** `path/to/file.js:123-145`
**Vulnerable Code:**
```javascript
// Exact code snippet
```
**Exploitation Scenario:**
[Step-by-step how to exploit]
**Business Impact:**
[What attacker gains]
**Fix Recommendation:**
```javascript
// Secure code example
```
**References:**
- [OWASP guideline link]
- [CWE number]
Begin the comprehensive security audit now.
```
---
## Proč Tato Struktura Funguje?
### 1. **Explicitní Instrukce na Začátku**
```markdown
## Output Format Requirements
For each finding, provide:
- **Severity:** CRITICAL / HIGH / MEDIUM / LOW
- **Location:** Exact file path and line numbers
...
```
Tím zajistíte, že Claude:**
- Ví přesně, jaký formát výstupu očekáváte
- Bude poskytovat strukturované, konzistentní odpovědi
- Zahrne všechny požadované informace
### 2. **Kompletní Kontext v Jednom Promptu**
Místo postupného nahrávání souborů:
```
❌ Špatný přístup:
"Přečti si tento soubor... OK, teď tento... Teď analyzuj..."
```
Použijte jeden velký prompt:
```
✅ Správný přístup:
"Zde je celý projekt (85 souborů). Analyzuj vše najednou."
```
**Výhody:**
- Claude vidí celý obraz, nejen jednotlivé části
- Může identifikovat cross-file vulnerabilities
- Poskytuje kontextuální analýzu (např. "tato XSS na frontendu je problém, protože backend nevaliduje")
### 3. **Komentáře ⚠️ Jako Vodítka**
V kódu jsem přidal `⚠️` komentáře u problematických částí:
```javascript
const query = `SELECT * FROM products WHERE name LIKE '%${search}%'`; // ⚠️ SQLi vector
```
**Účel:**
- Usnadňují Claudovi identifikaci problémů
- Slouží jako "cheat sheet" pro rychlejší analýzu
- Nejsou nutné, ale výrazně zrychlují analýzu (Claude najde problémy i bez nich)
### 4. **Strukturované Sekce**
Rozdělení do jasných sekcí:
```markdown
# FRONTEND CODE
[všechny React komponenty]
# BACKEND CODE
[všechny Express routes]
# MIDDLEWARE
[authentication, CORS, etc.]
# DATABASE MODELS
[Sequelize/mongoose models]
# CONFIGURATION
[.env, docker-compose, nginx]
```
**Proč to pomáhá:**
- Claude může odkazovat na sekce: "V sekci BACKEND CODE, soubor userRoutes.js:45..."
- Snadnější navigace ve velkém kontextu
- Lepší organizace výstupu
---
## Část 2: Prompt Strategie Pro Extended Context
### Strategie 1: "Dump Everything" Approach
**Kdy použít:** Jednorázové comprehensive audity, analýzy celých projektů
**Jak:**
1. Zkompilujte všechny soubory do jednoho Markdown dokumentu
2. Přidejte jasné sekční rozdělení
3. Na začátek dejte instrukce a očekávaný výstupní formát
4. Na konec dejte explicitní "Begin analysis now"
**Příklad:**
```markdown
# Comprehensive Codebase Analysis
## Instructions
[Co má Claude dělat]
## Expected Output Format
[Jak má vypadat výstup]
---
# CODEBASE
## Frontend (React)
[všechny komponenty]
## Backend (Node.js)
[všechny routes, modely]
## Tests
[test soubory]
## Configuration
[config soubory]
---
## Analysis Request
Begin comprehensive analysis focusing on:
1. [specific aspect]
2. [specific aspect]
3. [specific aspect]
```
### Strategie 2: "Annotated Context" Approach
**Kdy použít:** Code reviews, refactoring guidance, debugging složitých issues
**Jak:**
1. Přidejte anotace k důležitým částem kódu:
- `// NOTE: This is important because...`
- `// QUESTION: Should we change this?`
- `// CONTEXT: This was added in PR #123 to fix...`
2. Zvýrazněte oblasti zájmu
3. Poskytněte historický kontext
**Příklad:**
```javascript
// FILE: src/components/PaymentForm.jsx
// CONTEXT: Originally used Stripe Elements v1, migrated to v2 in PR #456
// QUESTION: Can we simplify this with Stripe's new Payment Element?
function PaymentForm() {
const [clientSecret, setClientSecret] = useState(null);
useEffect(() => {
// NOTE: We fetch clientSecret on mount to prevent CSRF
// See security review doc: docs/security/payment-flow.md
fetch('/api/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': getCsrfToken() // NOTE: Required for POST requests
},
body: JSON.stringify({ orderId })
})
.then(res => res.json())
.then(data => setClientSecret(data.clientSecret));
}, [orderId]);
// ... rest of component
}
```
**Claude pak může odpovědět:**
```markdown
## PaymentForm Simplification Opportunities
### Question: Can we simplify with Payment Element?
**Yes, significant simplification possible.**
Current implementation (src/components/PaymentForm.jsx:15-45) uses separate
Card Number, Card Expiry, and Card CVC elements. Stripe's Payment Element
consolidates this into single component.
**Before (current):**
[váš current kód]
**After (with Payment Element):**
```jsx
// Simplified with Payment Element
function PaymentForm() {
const stripe = useStripe();
const elements = useElements();
// SECURITY NOTE: clientSecret fetching preserved from original (line 18-29)
const [clientSecret, setClientSecret] = useState(null);
useEffect(() => {
// Keep existing CSRF-protected fetch logic
fetch('/api/create-payment-intent', ...)
}, [orderId]);
return (
<form onSubmit={handleSubmit}>
{/* Single component replaces 3 separate elements */}
<PaymentElement />
<button type="submit">Pay</button>
</form>
);
}
```
**Benefits:**
- 40% less code (150 lines → 90 lines)
- Built-in validation
- Automatic support for new payment methods (Apple Pay, Google Pay)
- Maintains existing CSRF protection (line 24-26)
**Migration Path:**
1. Update Stripe.js dependency to v3+ (package.json)
2. Replace CardElement components with PaymentElement (PaymentForm.jsx:30-60)
3. Update E2E tests (tests/e2e/payment.spec.js:45-120)
4. No backend changes required ✓
**Constraints Check:**
✓ Compatible with existing /api/create-payment-intent endpoint
✓ CSRF protection maintained
✓ No breaking changes for mobile app (backend unchanged)
```
### Strategie 3: "Focused Context + Reference" Approach
**Kdy použít:** Debugging specific issue s potřebou širšího kontextu
**Jak:**
1. Na začátek dejte focused problém
2. Pod to dejte relevant context
3. Na konec přidejte full codebase jako referenci
**Příklad:**
```markdown
# Bug Report: Duplicate Orders Created on Payment
## Problem
Users occasionally get charged twice for the same order. Database shows duplicate
order records with same items but different IDs.
## Reproduction Steps
1. User adds items to cart
2. Proceeds to checkout
3. Clicks "Pay Now"
4. Stripe webhook fires twice within 100ms
5. Both webhooks create separate order records
## Suspicious Code
### File: routes/paymentRoutes.js:45-67 (Webhook Handler)
```javascript
router.post('/webhook', async (req, res) => {
const event = stripe.webhooks.constructEvent(req.body, sig, secret);
if (event.type === 'payment_intent.succeeded') {
const { orderId } = event.data.object.metadata;
// ⚠️ Potential race condition - no locking mechanism
await db.query(`
UPDATE orders SET status = 'paid' WHERE id = ${orderId}
`);
// ⚠️ This might run twice if webhook is retried
await createInvoice(orderId);
await sendConfirmationEmail(orderId);
}
res.json({ received: true });
});
```
### File: models/Order.js:120-145 (Order Creation)
```javascript
static async create(orderData) {
const orderId = generateOrderId();
await db.query(`
INSERT INTO orders (id, user_id, items, total, status)
VALUES (${orderId}, ${orderData.userId}, '${JSON.stringify(orderData.items)}',
${orderData.total}, 'pending')
`);
return orderId;
}
```
## Question
What's causing the duplicate orders and how do we fix it with:
1. Zero data loss (all orders must be recorded)
2. Zero duplicate charges (no double billing)
3. Minimal changes to existing flow (mobile app compatibility)
---
# FULL CODEBASE FOR REFERENCE
[... celý codebase follows ...]
```
**Claude pak analyzuje:**
1. Identifikuje root cause (race condition v webhook handleru)
2. Navrhne řešení (idempotency keys, database locks)
3. Ukáže jak implementovat s ohledem na constraints
4. Použije kontext z celého codebase k identifikaci všech souvisejících míst, která je třeba změnit
---
## Část 3: Techniky Pro Organizaci Informací
### Technika 1: Hierarchické Nadpisy
Používejte Markdown hierarchii pro snadnou navigaci:
```markdown
# PROJECT OVERVIEW (level 1)
## Frontend (level 2)
### Components (level 3)
#### Authentication (level 4)
##### LoginForm.jsx (level 5)
```
Claude pak může odkazovat: "In **Frontend → Components → Authentication → LoginForm.jsx**"
### Technika 2: Inline Documentation
Dokumentujte účel každého souboru na jeho začátku:
```javascript
// FILE: src/services/PaymentService.js
// PURPOSE: Handles Stripe payment processing and webhook verification
// DEPENDENCIES: stripe, database, email-service
// USED BY: PaymentController, WebhookHandler
// SECURITY: Contains sensitive Stripe API key - never log
// LAST MODIFIED: 2025-01-05 (PR #456 - Added retry logic)
class PaymentService {
// ...
}
```
### Technika 3: Cross-Reference Markers
Přidejte reference mezi souvisejícími soubory:
```javascript
// FILE: frontend/src/components/CheckoutForm.jsx
function CheckoutForm() {
const handleSubmit = async () => {
// BACKEND REFERENCE: See backend/routes/paymentRoutes.js:34-56
// API DOCS: See docs/api/payments.md#create-payment-intent
const response = await fetch('/api/create-payment-intent', {
method: 'POST',
body: JSON.stringify({ orderId, amount })
});
};
}
```
```javascript
// FILE: backend/routes/paymentRoutes.js
// FRONTEND CALLERS:
// - frontend/src/components/CheckoutForm.jsx:45
// - frontend/src/pages/OrderSummary.jsx:120
router.post('/create-payment-intent', async (req, res) => {
// ...
});
```
### Technika 4: Dependency Graph
Na začátek promptu dejte dependency graph:
```markdown
# Dependency Graph
## High-Level Architecture
```
Frontend (React)
↓ HTTP requests
Backend API (Express)
↓ queries
Database (MySQL)
↓ events
Webhook Handler
↓ notifications
Email Service
```
## File-Level Dependencies
### PaymentFlow
```
CheckoutForm.jsx
→ calls → paymentRoutes.js:/create-payment-intent
→ calls → PaymentService.js:createIntent()
→ calls → Stripe API
→ stores → Database:orders table
→ triggers → OrderModel.afterCreate hook
→ calls → EmailService.sendConfirmation()
```
```
Claude pak rozumí celému flow a může identifikovat problémy na kterémkoliv místě v řetězci.
---
## Část 4: Získání Specifických Odkazů
### Problém: Vágní Odpovědi
**Špatný výstup od Clauda:**
"V komponentě PaymentForm máte security issue s XSS."
### Řešení: Explicit Output Format
V instrukčních části promptu specifikujte:
```markdown
## Required Output Format
For EVERY finding, you MUST include:
1. **Exact Location**
- Format: `path/to/file.js:startLine-endLine`
- Example: `src/components/PaymentForm.jsx:45-67`
2. **Vulnerable Code Snippet**
- Quote the EXACT code (copy-paste from the input)
- Include 2-3 lines of context before/after
3. **Specific Line Reference in Explanation**
- When explaining, reference: "On line 52, the variable..."
- NOT: "The code does..."
Example of GOOD output:
## [CRITICAL] XSS: Unescaped User Input in Review Display
**Location:** `src/components/ProductReview.jsx:45-67`
**Vulnerable Code (lines 45-50):**
```jsx
function ProductReview({ review }) {
return (
<div className="review">
<div dangerouslySetInnerHTML={{ __html: review.text }} />
</div>
);
}
```
**Issue:** On **line 47**, the `review.text` is rendered with `dangerouslySetInnerHTML`
without sanitization, allowing stored XSS attacks.
[... rest of finding ...]
```
### Jak Claude Zajistí Přesné Reference?
**1. Explicitně požadujte čísla řádků:**
```markdown
When referencing code:
- ALWAYS include the file path AND line numbers
- Format: path/to/file.js:123 or path/to/file.js:123-145 for ranges
- Quote the actual code from those lines
```
**2. Poskytněte číslované řádky v inputu:**
V Bash scriptu pro přípravu:
```bash
#!/bin/bash
OUTPUT_FILE="full-codebase.md"
echo "# Full Codebase with Line Numbers" > $OUTPUT_FILE
echo "" >> $OUTPUT_FILE
find src -name "*.js" -o -name "*.jsx" | while read file; do
echo "## File: $file" >> $OUTPUT_FILE
echo '```javascript' >> $OUTPUT_FILE
# Add line numbers
cat -n "$file" >> $OUTPUT_FILE
echo '```' >> $OUTPUT_FILE
echo "" >> $OUTPUT_FILE
done
```
Výstup:
```javascript
## File: src/components/PaymentForm.jsx
```javascript
1 import React, { useState } from 'react';
2 import { useStripe } from '@stripe/react-stripe-js';
3
4 function PaymentForm() {
5 const [amount, setAmount] = useState(0);
6
7 const handleSubmit = async () => {
8 // Vulnerable: no validation
9 await fetch('/api/payment', {
10 method: 'POST',
11 body: JSON.stringify({ amount }) // ⚠️ Client-controlled
12 });
13 };
```
Claude pak může přesně říct: "Na řádku 11 v src/components/PaymentForm.jsx..."
**3. Request Code Locations in Output:**
```markdown
## Output Template (use this EXACT format for every finding):
### [SEVERITY] [Category]: [Title]
**File:** `exact/path/to/file.js`
**Lines:** 123-145
**Function/Class:** `functionName()` or `ClassName`
**Vulnerable Code:**
```[language]
[quote exact lines from input, including line numbers]
```
**Issue Description:**
[Explain what's wrong, referencing specific line numbers]
**How to Exploit:**
[Step-by-step with examples]
**Fix:**
```[language]
[secure code replacement for the same lines]
```
**References:**
- OWASP: [link]
- CWE: [number]
```
---
## Část 5: Best Practices
### ✅ DO: Structure Your Context
```markdown
# PROJECT: E-Commerce Security Audit
## 1. EXECUTIVE SUMMARY
[2-3 sentences about the project]
## 2. AUDIT SCOPE
[What you want analyzed]
## 3. TECHNICAL CONTEXT
[Stack, versions, architecture]
## 4. CONSTRAINTS
[What cannot be changed]
## 5. OUTPUT REQUIREMENTS
[Exact format you want]
## 6. PRIORITY AREAS
[Where to focus most attention]
---
# CODE
[... structured code with clear sections ...]
---
# REFERENCES
## Architecture Diagrams
[Mermaid diagrams of system flow]
## API Documentation
[Swagger/OpenAPI specs]
## Previous Audit Findings
[Any known issues]
---
# ANALYSIS REQUEST
Begin comprehensive analysis now, following the output requirements in section 5.
```
### ✅ DO: Use Semantic Markers
```javascript
// 🔴 CRITICAL SECURITY ISSUE
const query = `SELECT * FROM users WHERE email = '${email}'`;
// 🟡 TODO: Refactor to use prepared statements
// 🟢 FIXED: Now using parameterized queries (as of 2025-01-05)
// 💭 CONTEXT: This was added to handle edge case from issue #123
// 🔗 RELATED: See PaymentService.js:45-67 for similar pattern
```
Claude pak může používat stejné markery v odpovědích.
### ✅ DO: Provide Example Output
Ukažte Claudovi přesně, jak má výstup vypadat:
```markdown
## Example of Expected Output
Here's EXACTLY the format I want:
### [CRITICAL] SQL Injection: Unparameterized Query in User Login
**Location:** `backend/routes/authRoutes.js:23-29`
**Vulnerable Code:**
```javascript
// Line 23-29
router.post('/login', async (req, res) => {
const { email } = req.body;
const query = `SELECT * FROM users WHERE email = '${email}'`; // ⚠️ SQLi
const results = await db.query(query);
});
```
**Exploitation:**
Attacker sends email: `' OR '1'='1' --`
Result: `SELECT * FROM users WHERE email = '' OR '1'='1' --'`
Bypasses authentication, returns all users.
**Fix:**
```javascript
// Use parameterized query
router.post('/login', async (req, res) => {
const { email } = req.body;
const query = 'SELECT * FROM users WHERE email = ?';
const results = await db.query(query, [email]); // ✅ Parameterized
});
```
**References:**
- OWASP SQL Injection: https://owasp.org/www-community/attacks/SQL_Injection
- CWE-89: SQL Injection
---
Now provide ALL findings in this exact format.
```
### ✅ DO: Number Everything
Numbering pomáhá v navigaci:
```markdown
# CODEBASE
## 1. Frontend
### 1.1 React Components
#### 1.1.1 Authentication
##### 1.1.1.1 LoginForm.jsx
#### 1.1.2 Payment
##### 1.1.2.1 CheckoutForm.jsx
### 1.2 Redux Store
#### 1.2.1 Actions
##### 1.2.1.1 authActions.js
## 2. Backend
### 2.1 Routes
#### 2.1.1 authRoutes.js
#### 2.1.2 paymentRoutes.js
```
Claude pak může říct: "See section 1.1.2.1 (CheckoutForm.jsx) and section 2.1.2 (paymentRoutes.js)"
### ❌ DON'T: Dump Unstructured Code
```javascript
// ❌ ŠPATNĚ
// Just pasting random files without context
class User {}
function login() {}
router.post('/payment', ...)
...
```
### ❌ DON'T: Mix Languages in Code Blocks
```javascript
// ❌ ŠPATNĚ - mělo by být ```jsx
<Component prop="value" />
```
```jsx
// ✅ SPRÁVNĚ
<Component prop="value" />
```
### ❌ DON'T: Forget to Update Context
Pokud děláte iterativní work, aktualizujte kontext:
```markdown
## Iteration 2: After Fixing SQL Injection Issues
### Changes Made Since Last Analysis
1. All queries now use parameterized statements (backend/models/*.js)
2. Added input validation middleware (backend/middleware/validation.js)
3. Updated database queries in routes (backend/routes/*.js)
### Remaining Issues to Address
[list from previous analysis]
### New Code for Review
[updated code with changes marked]
### Request
Review the updated code and:
1. Confirm SQL injection issues are properly fixed
2. Identify any NEW issues introduced by changes
3. Check for any remaining vulnerabilities
```
---
## Závěr
**Claude Extended Context (200K tokenů) je mocný nástroj**, ale efektivita závisí na struktuře vašeho inputu.
**Klíčové Takeaways:**
1. **Struktura je vše:** Markdown hierarchie, jasné sekce, numbered outline
2. **Explicitní instrukce:** Řekněte přesně, co chcete a v jakém formátu
3. **Poskytněte kontext:** Annotations, comments, dependency graphs
4. **Očekávejte přesnost:** Vyžadujte file paths a line numbers v každém outputu
5. **Používejte markers:** ⚠️ 🔴 🟡 🟢 💭 🔗 pro sémantické zvýraznění
6. **Ukažte příklady:** Example output template zajistí konzistenci
7. **Iterujte:** Update context, track changes, build on previous analyses
**S těmito technikami můžete Claude efektivně využít pro:**
- ✅ Comprehensive security audits (jako náš příklad)
- ✅ Large-scale refactoring planning
- ✅ Complex debugging s wide-ranging root causes
- ✅ Architecture reviews a redesigns
- ✅ Documentation generation from code
- ✅ Test coverage analysis
- ✅ Performance bottleneck identification
Extended context není jen o množství dat - **je o inteligentní organizaci informací** tak, aby Claude mohl efektivně najít patterns, identifikovat problémy a poskytovat actionable recommendations.
Kde použít tento prompt?
Najděte vhodné AI nástroje pro použití tohoto promptu a maximalizujte jeho efektivitu.
Podobné prompty
Advanced AI Features - Deep Dive do Pokročilých Funkcí
Komplexní průvodce pokročilými funkcemi AI nástrojů - od extended context a multimodality po tool use, streaming, a fine-tuning. Naučte se využívat plný potenciál moderních AI systémů.
Programování
Zobrazit
Algoritmus optimalizace
Optimalizace algoritmu z O(n²) na O(n log n) nebo lepší.
Programování
Zobrazit
API design s REST best practices
Návrh RESTful API s dokumentací a error handling.
Programování
Zobrazit
CI/CD pipeline setup
Konfigurace GitHub Actions / GitLab CI pipeline s testing a deployment.
Programování
Zobrazit
Objevte další AI prompty
Prozkoumejte naši sbírku Programování promptů a najděte ty, které vám pomohou dosáhnout lepších výsledků.