cursor-kit-cli 1.1.1 → 1.2.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -0
- package/bin/cursor-new-instance +74 -0
- package/bin/cursor-remove-instance +69 -0
- package/dist/cli.cjs +601 -62
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +601 -62
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +39 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +33 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
- package/templates/commands/docs.md +5 -3
- package/templates/commands/explain.md +5 -3
- package/templates/commands/fix.md +5 -3
- package/templates/commands/implement.md +5 -3
- package/templates/commands/refactor.md +5 -3
- package/templates/commands/review.md +5 -3
- package/templates/commands/test.md +5 -3
- package/templates/manifest.json +11 -8
- package/templates/rules/git.mdc +0 -2
- package/templates/rules/toc.mdc +17 -9
- package/templates/skills/aesthetic/SKILL.md +121 -0
- package/templates/skills/aesthetic/assets/design-guideline-template.md +163 -0
- package/templates/skills/aesthetic/assets/design-story-template.md +135 -0
- package/templates/skills/aesthetic/references/design-principles.md +62 -0
- package/templates/skills/aesthetic/references/design-resources.md +75 -0
- package/templates/skills/aesthetic/references/micro-interactions.md +53 -0
- package/templates/skills/aesthetic/references/storytelling-design.md +50 -0
- package/templates/skills/backend-development/SKILL.mdc +95 -0
- package/templates/skills/backend-development/references/backend-api-design.md +495 -0
- package/templates/skills/backend-development/references/backend-architecture.md +454 -0
- package/templates/skills/backend-development/references/backend-authentication.md +338 -0
- package/templates/skills/backend-development/references/backend-code-quality.md +659 -0
- package/templates/skills/backend-development/references/backend-debugging.md +904 -0
- package/templates/skills/backend-development/references/backend-devops.md +494 -0
- package/templates/skills/backend-development/references/backend-mindset.md +387 -0
- package/templates/skills/backend-development/references/backend-performance.md +397 -0
- package/templates/skills/backend-development/references/backend-security.md +290 -0
- package/templates/skills/backend-development/references/backend-technologies.md +256 -0
- package/templates/skills/backend-development/references/backend-testing.md +429 -0
- package/templates/skills/frontend-design/SKILL.mdc +41 -0
- package/templates/skills/frontend-design/references/animejs.md +396 -0
- package/templates/skills/frontend-development/SKILL.mdc +399 -0
- package/templates/skills/frontend-development/resources/common-patterns.md +331 -0
- package/templates/skills/frontend-development/resources/complete-examples.md +872 -0
- package/templates/skills/frontend-development/resources/component-patterns.md +502 -0
- package/templates/skills/frontend-development/resources/data-fetching.md +767 -0
- package/templates/skills/frontend-development/resources/file-organization.md +502 -0
- package/templates/skills/frontend-development/resources/loading-and-error-states.md +501 -0
- package/templates/skills/frontend-development/resources/performance.md +406 -0
- package/templates/skills/frontend-development/resources/routing-guide.md +364 -0
- package/templates/skills/frontend-development/resources/styling-guide.md +428 -0
- package/templates/skills/frontend-development/resources/typescript-standards.md +418 -0
- package/templates/skills/problem-solving/SKILL.mdc +96 -0
- package/templates/skills/problem-solving/references/attribution.md +69 -0
- package/templates/skills/problem-solving/references/collision-zone-thinking.md +79 -0
- package/templates/skills/problem-solving/references/inversion-exercise.md +91 -0
- package/templates/skills/problem-solving/references/meta-pattern-recognition.md +87 -0
- package/templates/skills/problem-solving/references/scale-game.md +95 -0
- package/templates/skills/problem-solving/references/simplification-cascades.md +80 -0
- package/templates/skills/problem-solving/references/when-stuck.md +72 -0
- package/templates/skills/research/SKILL.mdc +168 -0
- package/templates/skills/sequential-thinking/.env.example +8 -0
- package/templates/skills/sequential-thinking/README.md +183 -0
- package/templates/skills/sequential-thinking/SKILL.mdc +94 -0
- package/templates/skills/sequential-thinking/package.json +31 -0
- package/templates/skills/sequential-thinking/references/advanced-strategies.md +79 -0
- package/templates/skills/sequential-thinking/references/advanced-techniques.md +76 -0
- package/templates/skills/sequential-thinking/references/core-patterns.md +95 -0
- package/templates/skills/sequential-thinking/references/examples-api.md +88 -0
- package/templates/skills/sequential-thinking/references/examples-architecture.md +94 -0
- package/templates/skills/sequential-thinking/references/examples-debug.md +90 -0
- package/templates/skills/sequential-thinking/scripts/format-thought.js +159 -0
- package/templates/skills/sequential-thinking/scripts/process-thought.js +236 -0
- package/templates/skills/sequential-thinking/tests/format-thought.test.js +133 -0
- package/templates/skills/sequential-thinking/tests/process-thought.test.js +215 -0
- package/templates/skills/ui-styling/LICENSE.txt +202 -0
- package/templates/skills/ui-styling/SKILL.mdc +321 -0
- package/templates/skills/ui-styling/references/canvas-design-system.md +320 -0
- package/templates/skills/ui-styling/references/shadcn-accessibility.md +471 -0
- package/templates/skills/ui-styling/references/shadcn-components.md +424 -0
- package/templates/skills/ui-styling/references/shadcn-theming.md +373 -0
- package/templates/skills/ui-styling/references/tailwind-customization.md +483 -0
- package/templates/skills/ui-styling/references/tailwind-responsive.md +382 -0
- package/templates/skills/ui-styling/references/tailwind-utilities.md +455 -0
- package/templates/rules/frontend-design.mdc +0 -48
- package/templates/rules/performance.mdc +0 -54
- package/templates/rules/react.mdc +0 -58
- package/templates/rules/security.mdc +0 -50
- package/templates/rules/testing.mdc +0 -54
- package/templates/rules/typescript.mdc +0 -36
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
# Backend Performance & Scalability
|
|
2
|
+
|
|
3
|
+
Performance optimization strategies, caching patterns, and scalability best practices (2025).
|
|
4
|
+
|
|
5
|
+
## Database Performance
|
|
6
|
+
|
|
7
|
+
### Query Optimization
|
|
8
|
+
|
|
9
|
+
#### Indexing Strategies
|
|
10
|
+
|
|
11
|
+
**Impact:** 30% disk I/O reduction, 10-100x query speedup
|
|
12
|
+
|
|
13
|
+
```sql
|
|
14
|
+
-- Create index on frequently queried columns
|
|
15
|
+
CREATE INDEX idx_users_email ON users(email);
|
|
16
|
+
CREATE INDEX idx_orders_user_id ON orders(user_id);
|
|
17
|
+
|
|
18
|
+
-- Composite index for multi-column queries
|
|
19
|
+
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
|
|
20
|
+
|
|
21
|
+
-- Partial index for filtered queries
|
|
22
|
+
CREATE INDEX idx_active_users ON users(email) WHERE active = true;
|
|
23
|
+
|
|
24
|
+
-- Analyze query performance
|
|
25
|
+
EXPLAIN ANALYZE SELECT * FROM orders
|
|
26
|
+
WHERE user_id = 123 AND created_at > '2025-01-01';
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
**Index Types:**
|
|
30
|
+
- **B-tree** - Default, general-purpose (equality, range queries)
|
|
31
|
+
- **Hash** - Fast equality lookups, no range queries
|
|
32
|
+
- **GIN** - Full-text search, JSONB queries
|
|
33
|
+
- **GiST** - Geospatial queries, range types
|
|
34
|
+
|
|
35
|
+
**When NOT to Index:**
|
|
36
|
+
- Small tables (<1000 rows)
|
|
37
|
+
- Frequently updated columns
|
|
38
|
+
- Low-cardinality columns (e.g., boolean with 2 values)
|
|
39
|
+
|
|
40
|
+
### Connection Pooling
|
|
41
|
+
|
|
42
|
+
**Impact:** 5-10x performance improvement
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
// PostgreSQL with pg-pool
|
|
46
|
+
import { Pool } from 'pg';
|
|
47
|
+
|
|
48
|
+
const pool = new Pool({
|
|
49
|
+
host: process.env.DB_HOST,
|
|
50
|
+
database: process.env.DB_NAME,
|
|
51
|
+
user: process.env.DB_USER,
|
|
52
|
+
password: process.env.DB_PASSWORD,
|
|
53
|
+
max: 20, // Maximum connections
|
|
54
|
+
min: 5, // Minimum connections
|
|
55
|
+
idleTimeoutMillis: 30000, // Close idle connections after 30s
|
|
56
|
+
connectionTimeoutMillis: 2000, // Error if can't connect in 2s
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Use pool for queries
|
|
60
|
+
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
**Recommended Pool Sizes:**
|
|
64
|
+
- **Web servers:** `connections = (core_count * 2) + effective_spindle_count`
|
|
65
|
+
- **Typical:** 20-30 connections per app instance
|
|
66
|
+
- **Monitor:** Connection saturation in production
|
|
67
|
+
|
|
68
|
+
### N+1 Query Problem
|
|
69
|
+
|
|
70
|
+
**Bad: N+1 queries**
|
|
71
|
+
```typescript
|
|
72
|
+
// Fetches 1 query for posts, then N queries for authors
|
|
73
|
+
const posts = await Post.findAll();
|
|
74
|
+
for (const post of posts) {
|
|
75
|
+
post.author = await User.findById(post.authorId); // N queries!
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
**Good: Join or eager loading**
|
|
80
|
+
```typescript
|
|
81
|
+
// Single query with JOIN
|
|
82
|
+
const posts = await Post.findAll({
|
|
83
|
+
include: [{ model: User, as: 'author' }],
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Caching Strategies
|
|
88
|
+
|
|
89
|
+
### Redis Caching
|
|
90
|
+
|
|
91
|
+
**Impact:** 90% DB load reduction, 10-100x faster response
|
|
92
|
+
|
|
93
|
+
#### Cache-Aside Pattern (Lazy Loading)
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
async function getUser(userId: string) {
|
|
97
|
+
// Try cache first
|
|
98
|
+
const cached = await redis.get(`user:${userId}`);
|
|
99
|
+
if (cached) return JSON.parse(cached);
|
|
100
|
+
|
|
101
|
+
// Cache miss - fetch from DB
|
|
102
|
+
const user = await db.users.findById(userId);
|
|
103
|
+
|
|
104
|
+
// Store in cache (TTL: 1 hour)
|
|
105
|
+
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
|
|
106
|
+
|
|
107
|
+
return user;
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
#### Write-Through Pattern
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
async function updateUser(userId: string, data: UpdateUserDto) {
|
|
115
|
+
// Update database
|
|
116
|
+
const user = await db.users.update(userId, data);
|
|
117
|
+
|
|
118
|
+
// Update cache immediately
|
|
119
|
+
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
|
|
120
|
+
|
|
121
|
+
return user;
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
#### Cache Invalidation
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
// Invalidate on update
|
|
129
|
+
async function deleteUser(userId: string) {
|
|
130
|
+
await db.users.delete(userId);
|
|
131
|
+
await redis.del(`user:${userId}`);
|
|
132
|
+
await redis.del(`user:${userId}:posts`); // Invalidate related caches
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Pattern-based invalidation
|
|
136
|
+
await redis.keys('user:*').then(keys => redis.del(...keys));
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Cache Layers
|
|
140
|
+
|
|
141
|
+
```
|
|
142
|
+
Client
|
|
143
|
+
→ CDN Cache (static assets, 50%+ latency reduction)
|
|
144
|
+
→ API Gateway Cache (public endpoints)
|
|
145
|
+
→ Application Cache (Redis)
|
|
146
|
+
→ Database Query Cache
|
|
147
|
+
→ Database
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Cache Best Practices
|
|
151
|
+
|
|
152
|
+
1. **Cache frequently accessed data** - User profiles, config, product catalogs
|
|
153
|
+
2. **Set appropriate TTL** - Balance freshness vs performance
|
|
154
|
+
3. **Invalidate on write** - Keep cache consistent
|
|
155
|
+
4. **Use cache keys wisely** - `resource:id:attribute` pattern
|
|
156
|
+
5. **Monitor hit rates** - Target >80% hit rate
|
|
157
|
+
|
|
158
|
+
## Load Balancing
|
|
159
|
+
|
|
160
|
+
### Algorithms
|
|
161
|
+
|
|
162
|
+
**Round Robin** - Distribute evenly across servers
|
|
163
|
+
```nginx
|
|
164
|
+
upstream backend {
|
|
165
|
+
server backend1.example.com;
|
|
166
|
+
server backend2.example.com;
|
|
167
|
+
server backend3.example.com;
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
**Least Connections** - Route to server with fewest connections
|
|
172
|
+
```nginx
|
|
173
|
+
upstream backend {
|
|
174
|
+
least_conn;
|
|
175
|
+
server backend1.example.com;
|
|
176
|
+
server backend2.example.com;
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
**IP Hash** - Same client → same server (session affinity)
|
|
181
|
+
```nginx
|
|
182
|
+
upstream backend {
|
|
183
|
+
ip_hash;
|
|
184
|
+
server backend1.example.com;
|
|
185
|
+
server backend2.example.com;
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Health Checks
|
|
190
|
+
|
|
191
|
+
```typescript
|
|
192
|
+
// Express health check endpoint
|
|
193
|
+
app.get('/health', async (req, res) => {
|
|
194
|
+
const checks = {
|
|
195
|
+
uptime: process.uptime(),
|
|
196
|
+
timestamp: Date.now(),
|
|
197
|
+
database: await checkDatabase(),
|
|
198
|
+
redis: await checkRedis(),
|
|
199
|
+
memory: process.memoryUsage(),
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const isHealthy = checks.database && checks.redis;
|
|
203
|
+
res.status(isHealthy ? 200 : 503).json(checks);
|
|
204
|
+
});
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## Asynchronous Processing
|
|
208
|
+
|
|
209
|
+
### Message Queues for Long-Running Tasks
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
// Producer - Add job to queue
|
|
213
|
+
import Queue from 'bull';
|
|
214
|
+
|
|
215
|
+
const emailQueue = new Queue('email', {
|
|
216
|
+
redis: { host: 'localhost', port: 6379 },
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
await emailQueue.add('send-welcome', {
|
|
220
|
+
userId: user.id,
|
|
221
|
+
email: user.email,
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// Consumer - Process jobs
|
|
225
|
+
emailQueue.process('send-welcome', async (job) => {
|
|
226
|
+
await sendWelcomeEmail(job.data.email);
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Use Cases:**
|
|
231
|
+
- Email sending
|
|
232
|
+
- Image/video processing
|
|
233
|
+
- Report generation
|
|
234
|
+
- Data export
|
|
235
|
+
- Webhook delivery
|
|
236
|
+
|
|
237
|
+
## CDN (Content Delivery Network)
|
|
238
|
+
|
|
239
|
+
**Impact:** 50%+ latency reduction for global users
|
|
240
|
+
|
|
241
|
+
### Configuration
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
// Cache-Control headers
|
|
245
|
+
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); // Static assets
|
|
246
|
+
res.setHeader('Cache-Control', 'public, max-age=3600'); // API responses
|
|
247
|
+
res.setHeader('Cache-Control', 'private, no-cache'); // User-specific data
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**CDN Providers:**
|
|
251
|
+
- Cloudflare (generous free tier, global coverage)
|
|
252
|
+
- AWS CloudFront (AWS integration)
|
|
253
|
+
- Fastly (real-time purging)
|
|
254
|
+
|
|
255
|
+
## Horizontal vs Vertical Scaling
|
|
256
|
+
|
|
257
|
+
### Horizontal Scaling (Scale Out)
|
|
258
|
+
|
|
259
|
+
**Pros:**
|
|
260
|
+
- Better fault tolerance
|
|
261
|
+
- Unlimited scaling potential
|
|
262
|
+
- Cost-effective (commodity hardware)
|
|
263
|
+
|
|
264
|
+
**Cons:**
|
|
265
|
+
- Complex architecture
|
|
266
|
+
- Data consistency challenges
|
|
267
|
+
- Network overhead
|
|
268
|
+
|
|
269
|
+
**When to use:** High traffic, need redundancy, stateless applications
|
|
270
|
+
|
|
271
|
+
### Vertical Scaling (Scale Up)
|
|
272
|
+
|
|
273
|
+
**Pros:**
|
|
274
|
+
- Simple architecture
|
|
275
|
+
- No code changes needed
|
|
276
|
+
- Easier data consistency
|
|
277
|
+
|
|
278
|
+
**Cons:**
|
|
279
|
+
- Hardware limits
|
|
280
|
+
- Single point of failure
|
|
281
|
+
- Expensive at high end
|
|
282
|
+
|
|
283
|
+
**When to use:** Monolithic apps, rapid scaling needed, data consistency critical
|
|
284
|
+
|
|
285
|
+
## Database Scaling Patterns
|
|
286
|
+
|
|
287
|
+
### Read Replicas
|
|
288
|
+
|
|
289
|
+
```
|
|
290
|
+
Primary (Write) → Replica 1 (Read)
|
|
291
|
+
→ Replica 2 (Read)
|
|
292
|
+
→ Replica 3 (Read)
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
**Implementation:**
|
|
296
|
+
```typescript
|
|
297
|
+
// Write to primary
|
|
298
|
+
await primaryDb.users.create(userData);
|
|
299
|
+
|
|
300
|
+
// Read from replica
|
|
301
|
+
const users = await replicaDb.users.findAll();
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
**Use Cases:**
|
|
305
|
+
- Read-heavy workloads (90%+ reads)
|
|
306
|
+
- Analytics queries
|
|
307
|
+
- Reporting dashboards
|
|
308
|
+
|
|
309
|
+
### Database Sharding
|
|
310
|
+
|
|
311
|
+
**Horizontal Partitioning** - Split data across databases
|
|
312
|
+
|
|
313
|
+
```typescript
|
|
314
|
+
// Shard by user ID
|
|
315
|
+
function getShardId(userId: string): number {
|
|
316
|
+
return hashCode(userId) % SHARD_COUNT;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const shardId = getShardId(userId);
|
|
320
|
+
const db = shards[shardId];
|
|
321
|
+
const user = await db.users.findById(userId);
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
**Sharding Strategies:**
|
|
325
|
+
- **Range-based:** Users 1-1M → Shard 1, 1M-2M → Shard 2
|
|
326
|
+
- **Hash-based:** Hash(userId) % shard_count
|
|
327
|
+
- **Geographic:** EU users → EU shard, US users → US shard
|
|
328
|
+
- **Entity-based:** Users → Shard 1, Orders → Shard 2
|
|
329
|
+
|
|
330
|
+
## Performance Monitoring
|
|
331
|
+
|
|
332
|
+
### Key Metrics
|
|
333
|
+
|
|
334
|
+
**Application:**
|
|
335
|
+
- Response time (p50, p95, p99)
|
|
336
|
+
- Throughput (requests/second)
|
|
337
|
+
- Error rate
|
|
338
|
+
- CPU/memory usage
|
|
339
|
+
|
|
340
|
+
**Database:**
|
|
341
|
+
- Query execution time
|
|
342
|
+
- Connection pool saturation
|
|
343
|
+
- Cache hit rate
|
|
344
|
+
- Slow query log
|
|
345
|
+
|
|
346
|
+
**Tools:**
|
|
347
|
+
- Prometheus + Grafana (metrics)
|
|
348
|
+
- New Relic / Datadog (APM)
|
|
349
|
+
- Sentry (error tracking)
|
|
350
|
+
- OpenTelemetry (distributed tracing)
|
|
351
|
+
|
|
352
|
+
## Performance Optimization Checklist
|
|
353
|
+
|
|
354
|
+
### Database
|
|
355
|
+
- [ ] Indexes on frequently queried columns
|
|
356
|
+
- [ ] Connection pooling configured
|
|
357
|
+
- [ ] N+1 queries eliminated
|
|
358
|
+
- [ ] Slow query log monitored
|
|
359
|
+
- [ ] Query execution plans analyzed
|
|
360
|
+
|
|
361
|
+
### Caching
|
|
362
|
+
- [ ] Redis cache for hot data
|
|
363
|
+
- [ ] Cache TTL configured appropriately
|
|
364
|
+
- [ ] Cache invalidation on writes
|
|
365
|
+
- [ ] CDN for static assets
|
|
366
|
+
- [ ] >80% cache hit rate achieved
|
|
367
|
+
|
|
368
|
+
### Application
|
|
369
|
+
- [ ] Async processing for long tasks
|
|
370
|
+
- [ ] Response compression enabled (gzip)
|
|
371
|
+
- [ ] Load balancing configured
|
|
372
|
+
- [ ] Health checks implemented
|
|
373
|
+
- [ ] Resource limits set (CPU, memory)
|
|
374
|
+
|
|
375
|
+
### Monitoring
|
|
376
|
+
- [ ] APM tool configured (New Relic/Datadog)
|
|
377
|
+
- [ ] Error tracking (Sentry)
|
|
378
|
+
- [ ] Performance dashboards (Grafana)
|
|
379
|
+
- [ ] Alerting on key metrics
|
|
380
|
+
- [ ] Distributed tracing for microservices
|
|
381
|
+
|
|
382
|
+
## Common Performance Pitfalls
|
|
383
|
+
|
|
384
|
+
1. **No caching** - Repeatedly querying same data
|
|
385
|
+
2. **Missing indexes** - Full table scans
|
|
386
|
+
3. **N+1 queries** - Fetching related data in loops
|
|
387
|
+
4. **Synchronous processing** - Blocking on long tasks
|
|
388
|
+
5. **No connection pooling** - Creating new connections per request
|
|
389
|
+
6. **Unbounded queries** - No LIMIT on large tables
|
|
390
|
+
7. **No CDN** - Serving static assets from origin
|
|
391
|
+
|
|
392
|
+
## Resources
|
|
393
|
+
|
|
394
|
+
- **PostgreSQL Performance:** https://www.postgresql.org/docs/current/performance-tips.html
|
|
395
|
+
- **Redis Best Practices:** https://redis.io/docs/management/optimization/
|
|
396
|
+
- **Web Performance:** https://web.dev/performance/
|
|
397
|
+
- **Database Indexing:** https://use-the-index-luke.com/
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
# Backend Security
|
|
2
|
+
|
|
3
|
+
Security best practices, OWASP Top 10 mitigation, and modern security standards (2025).
|
|
4
|
+
|
|
5
|
+
## OWASP Top 10 (2025 RC1)
|
|
6
|
+
|
|
7
|
+
### New Entries (2025)
|
|
8
|
+
- **Supply Chain Failures** - Vulnerable dependencies, compromised packages
|
|
9
|
+
- **Mishandling of Exceptional Conditions** - Improper error handling exposing system info
|
|
10
|
+
|
|
11
|
+
### Top Vulnerabilities & Mitigation
|
|
12
|
+
|
|
13
|
+
#### 1. Broken Access Control
|
|
14
|
+
**Risk:** Users access unauthorized resources (28% of vulnerabilities)
|
|
15
|
+
|
|
16
|
+
**Mitigation:**
|
|
17
|
+
- Implement RBAC (Role-Based Access Control)
|
|
18
|
+
- Deny by default, explicitly allow
|
|
19
|
+
- Log access control failures
|
|
20
|
+
- Enforce authorization on backend (never client-side)
|
|
21
|
+
- Use JWT with proper claims validation
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
// Good: Server-side authorization check
|
|
25
|
+
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
26
|
+
@Roles('admin')
|
|
27
|
+
async deleteUser(@Param('id') id: string) {
|
|
28
|
+
// Verify user can access this resource
|
|
29
|
+
return this.usersService.delete(id);
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
#### 2. Cryptographic Failures
|
|
34
|
+
**Risk:** Sensitive data exposure, weak encryption
|
|
35
|
+
|
|
36
|
+
**Mitigation:**
|
|
37
|
+
- Use Argon2id for password hashing (replaces bcrypt as of 2025)
|
|
38
|
+
- TLS 1.3 for data in transit
|
|
39
|
+
- Encrypt sensitive data at rest (AES-256)
|
|
40
|
+
- Use crypto.randomBytes() for tokens, not Math.random()
|
|
41
|
+
- Never store passwords in plain text
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
# Good: Argon2id password hashing
|
|
45
|
+
from argon2 import PasswordHasher
|
|
46
|
+
|
|
47
|
+
ph = PasswordHasher()
|
|
48
|
+
hash = ph.hash("password123") # Auto-salted, memory-hard
|
|
49
|
+
ph.verify(hash, "password123") # Verify password
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
#### 3. Injection Attacks
|
|
53
|
+
**Risk:** SQL injection, NoSQL injection, command injection (6x increase 2020-2024)
|
|
54
|
+
|
|
55
|
+
**Mitigation (98% vulnerability reduction):**
|
|
56
|
+
- Use parameterized queries ALWAYS
|
|
57
|
+
- Input validation with allow-lists
|
|
58
|
+
- Escape special characters
|
|
59
|
+
- Use ORMs properly (avoid raw queries)
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
// Bad: Vulnerable to SQL injection
|
|
63
|
+
const query = `SELECT * FROM users WHERE email = '${email}'`;
|
|
64
|
+
|
|
65
|
+
// Good: Parameterized query
|
|
66
|
+
const query = 'SELECT * FROM users WHERE email = $1';
|
|
67
|
+
const result = await db.query(query, [email]);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
#### 4. Insecure Design
|
|
71
|
+
**Risk:** Flawed architecture, missing security controls
|
|
72
|
+
|
|
73
|
+
**Mitigation:**
|
|
74
|
+
- Threat modeling during design phase
|
|
75
|
+
- Security requirements from start
|
|
76
|
+
- Principle of least privilege
|
|
77
|
+
- Defense in depth (multiple security layers)
|
|
78
|
+
|
|
79
|
+
#### 5. Security Misconfiguration
|
|
80
|
+
**Risk:** Default credentials, verbose errors, unnecessary features enabled
|
|
81
|
+
|
|
82
|
+
**Mitigation:**
|
|
83
|
+
- Remove default accounts
|
|
84
|
+
- Disable directory listing
|
|
85
|
+
- Use security headers (CSP, HSTS, X-Frame-Options)
|
|
86
|
+
- Minimize attack surface
|
|
87
|
+
- Regular security audits
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
// Security headers middleware
|
|
91
|
+
app.use(helmet({
|
|
92
|
+
contentSecurityPolicy: {
|
|
93
|
+
directives: {
|
|
94
|
+
defaultSrc: ["'self'"],
|
|
95
|
+
scriptSrc: ["'self'", "'unsafe-inline'"],
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
hsts: {
|
|
99
|
+
maxAge: 31536000,
|
|
100
|
+
includeSubDomains: true,
|
|
101
|
+
},
|
|
102
|
+
}));
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
#### 6. Vulnerable Components
|
|
106
|
+
**Risk:** Outdated dependencies with known vulnerabilities
|
|
107
|
+
|
|
108
|
+
**Mitigation:**
|
|
109
|
+
- Regular dependency updates (npm audit, pip-audit)
|
|
110
|
+
- Use Dependabot/Renovate for automated updates
|
|
111
|
+
- Monitor CVE databases
|
|
112
|
+
- Software composition analysis (SCA) in CI/CD
|
|
113
|
+
- Lock file integrity checks
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
# Check for vulnerabilities
|
|
117
|
+
npm audit fix
|
|
118
|
+
pip-audit --fix
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
#### 7. Authentication Failures
|
|
122
|
+
**Risk:** Weak passwords, session hijacking, credential stuffing
|
|
123
|
+
|
|
124
|
+
**Mitigation:**
|
|
125
|
+
- MFA mandatory for admin accounts
|
|
126
|
+
- Rate limiting on login endpoints (10 attempts/minute)
|
|
127
|
+
- Strong password policies (12+ chars, complexity)
|
|
128
|
+
- Session timeout (15 mins idle, 8 hours absolute)
|
|
129
|
+
- FIDO2/WebAuthn for passwordless auth
|
|
130
|
+
|
|
131
|
+
#### 8. Software & Data Integrity Failures
|
|
132
|
+
**Risk:** CI/CD pipeline compromise, unsigned updates
|
|
133
|
+
|
|
134
|
+
**Mitigation:**
|
|
135
|
+
- Code signing for releases
|
|
136
|
+
- Verify integrity of packages (lock files)
|
|
137
|
+
- Secure CI/CD pipelines (immutable builds)
|
|
138
|
+
- Checksum verification
|
|
139
|
+
|
|
140
|
+
#### 9. Logging & Monitoring Failures
|
|
141
|
+
**Risk:** Breaches undetected, insufficient audit trail
|
|
142
|
+
|
|
143
|
+
**Mitigation:**
|
|
144
|
+
- Log authentication events (success/failure)
|
|
145
|
+
- Log access control failures
|
|
146
|
+
- Centralized logging (ELK Stack, Splunk)
|
|
147
|
+
- Alerting on suspicious patterns
|
|
148
|
+
- Log rotation and retention policies
|
|
149
|
+
|
|
150
|
+
#### 10. Server-Side Request Forgery (SSRF)
|
|
151
|
+
**Risk:** Server makes malicious requests to internal resources
|
|
152
|
+
|
|
153
|
+
**Mitigation:**
|
|
154
|
+
- Validate and sanitize URLs
|
|
155
|
+
- Allow-list for remote resources
|
|
156
|
+
- Network segmentation
|
|
157
|
+
- Disable unnecessary protocols (file://, gopher://)
|
|
158
|
+
|
|
159
|
+
## Input Validation (Prevents 70%+ Vulnerabilities)
|
|
160
|
+
|
|
161
|
+
### Validation Strategies
|
|
162
|
+
|
|
163
|
+
**1. Type Validation**
|
|
164
|
+
```typescript
|
|
165
|
+
// Use class-validator with NestJS
|
|
166
|
+
class CreateUserDto {
|
|
167
|
+
@IsEmail()
|
|
168
|
+
email: string;
|
|
169
|
+
|
|
170
|
+
@IsString()
|
|
171
|
+
@MinLength(12)
|
|
172
|
+
@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
|
|
173
|
+
password: string;
|
|
174
|
+
|
|
175
|
+
@IsInt()
|
|
176
|
+
@Min(18)
|
|
177
|
+
age: number;
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
**2. Sanitization**
|
|
182
|
+
```typescript
|
|
183
|
+
import DOMPurify from 'isomorphic-dompurify';
|
|
184
|
+
|
|
185
|
+
// Sanitize HTML input
|
|
186
|
+
const clean = DOMPurify.sanitize(userInput);
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
**3. Allow-lists (Preferred over Deny-lists)**
|
|
190
|
+
```typescript
|
|
191
|
+
// Good: Allow-list approach
|
|
192
|
+
const allowedFields = ['name', 'email', 'age'];
|
|
193
|
+
const sanitized = Object.keys(input)
|
|
194
|
+
.filter(key => allowedFields.includes(key))
|
|
195
|
+
.reduce((obj, key) => ({ ...obj, [key]: input[key] }), {});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Rate Limiting
|
|
199
|
+
|
|
200
|
+
### Token Bucket Algorithm (Industry Standard)
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
import rateLimit from 'express-rate-limit';
|
|
204
|
+
|
|
205
|
+
const limiter = rateLimit({
|
|
206
|
+
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
207
|
+
max: 100, // 100 requests per window
|
|
208
|
+
standardHeaders: true,
|
|
209
|
+
legacyHeaders: false,
|
|
210
|
+
message: 'Too many requests, please try again later',
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
app.use('/api/', limiter);
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### API-Specific Limits
|
|
217
|
+
|
|
218
|
+
- **Authentication:** 10 attempts/15 min
|
|
219
|
+
- **Public APIs:** 100 requests/15 min
|
|
220
|
+
- **Authenticated APIs:** 1000 requests/15 min
|
|
221
|
+
- **Admin endpoints:** 50 requests/15 min
|
|
222
|
+
|
|
223
|
+
## Security Headers
|
|
224
|
+
|
|
225
|
+
```typescript
|
|
226
|
+
// Essential security headers (2025)
|
|
227
|
+
{
|
|
228
|
+
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
|
|
229
|
+
'Content-Security-Policy': "default-src 'self'",
|
|
230
|
+
'X-Frame-Options': 'DENY',
|
|
231
|
+
'X-Content-Type-Options': 'nosniff',
|
|
232
|
+
'Referrer-Policy': 'strict-origin-when-cross-origin',
|
|
233
|
+
'Permissions-Policy': 'geolocation=(), microphone=()',
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
## Secrets Management
|
|
238
|
+
|
|
239
|
+
### Best Practices
|
|
240
|
+
|
|
241
|
+
1. **Never commit secrets** - Use .env files (gitignored)
|
|
242
|
+
2. **Environment-specific** - Different secrets per environment
|
|
243
|
+
3. **Rotation policy** - Rotate secrets every 90 days
|
|
244
|
+
4. **Encryption at rest** - Encrypt secrets in secret managers
|
|
245
|
+
5. **Least privilege** - Minimal permissions per secret
|
|
246
|
+
|
|
247
|
+
### Tools
|
|
248
|
+
|
|
249
|
+
- **HashiCorp Vault** - Multi-cloud, dynamic secrets
|
|
250
|
+
- **AWS Secrets Manager** - Managed service, auto-rotation
|
|
251
|
+
- **Azure Key Vault** - Integrated with Azure services
|
|
252
|
+
- **Pulumi ESC** - Unified secrets orchestration (2025 trend)
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
// Good: Secrets from environment
|
|
256
|
+
const dbPassword = process.env.DB_PASSWORD;
|
|
257
|
+
if (!dbPassword) throw new Error('DB_PASSWORD not set');
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## API Security Checklist
|
|
261
|
+
|
|
262
|
+
- [ ] Use HTTPS/TLS 1.3 only
|
|
263
|
+
- [ ] Implement OAuth 2.1 + JWT for authentication
|
|
264
|
+
- [ ] Rate limiting on all endpoints
|
|
265
|
+
- [ ] Input validation on all inputs
|
|
266
|
+
- [ ] Parameterized queries (prevent SQL injection)
|
|
267
|
+
- [ ] Security headers configured
|
|
268
|
+
- [ ] CORS properly configured (not `*` in production)
|
|
269
|
+
- [ ] API versioning implemented
|
|
270
|
+
- [ ] Error messages don't leak system info
|
|
271
|
+
- [ ] Logging authentication events
|
|
272
|
+
- [ ] MFA for admin accounts
|
|
273
|
+
- [ ] Regular security audits (quarterly)
|
|
274
|
+
|
|
275
|
+
## Common Security Pitfalls
|
|
276
|
+
|
|
277
|
+
1. **Client-side validation only** - Always validate on server
|
|
278
|
+
2. **Using Math.random() for tokens** - Use crypto.randomBytes()
|
|
279
|
+
3. **Storing passwords with bcrypt** - Use Argon2id (2025 standard)
|
|
280
|
+
4. **Trusting user input** - Validate and sanitize everything
|
|
281
|
+
5. **Weak CORS configuration** - Don't use `*` in production
|
|
282
|
+
6. **Insufficient logging** - Log all authentication/authorization events
|
|
283
|
+
7. **No rate limiting** - Implement on all public endpoints
|
|
284
|
+
|
|
285
|
+
## Resources
|
|
286
|
+
|
|
287
|
+
- **OWASP Top 10 (2025):** https://owasp.org/www-project-top-ten/
|
|
288
|
+
- **OWASP Cheat Sheets:** https://cheatsheetseries.owasp.org/
|
|
289
|
+
- **CWE Top 25:** https://cwe.mitre.org/top25/
|
|
290
|
+
- **NIST Guidelines:** https://www.nist.gov/cybersecurity
|