Skill站外收录 @skilllib/skill-2014279426358325251
exa-known-pitfalls
提供 Exa 集成代码审查能力,识别同步阻塞、限流缺失、密钥泄露、非幂等操作、未验签 webhook、异常处理不足、配置硬编码、熔断缺失、敏感日志和降级失效等十大典型问题,并给出安全、可靠、可维护的改进方案。
测试与安全 AI 技能
Skills.MD
# Exa Known Pitfalls
## Overview
Common mistakes and anti-patterns when integrating with Exa.
## Prerequisites
- Access to Exa codebase for review
- Understanding of async/await patterns
- Knowledge of security best practices
- Familiarity with rate limiting concepts
## Pitfall #1: Synchronous API Calls in Request Path
### ❌ Anti-Pattern
```typescript
// User waits for Exa API call
app.post('/checkout', async (req, res) => {
const payment = await exaClient.processPayment(req.body); // 2-5s latency
const notification = await exaClient.sendEmail(payment); // Another 1-2s
res.json({ success: true }); // User waited 3-7s
});
```
### ✅ Better Approach
```typescript
// Return immediately, process async
app.post('/checkout', async (req, res) => {
const jobId = await queue.enqueue('process-checkout', req.body);
res.json({ jobId, status: 'processing' }); // 50ms response
});
// Background job
async function processCheckout(data) {
const payment = await exaClient.processPayment(data);
await exaClient.sendEmail(payment);
}
```
---
## Pitfall #2: Not Handling Rate Limits
### ❌ Anti-Pattern
```typescript
// Blast requests, crash on 429
for (const item of items) {
await exaClient.process(item); // Will hit rate limit
}
```
### ✅ Better Approach
```typescript
import pLimit from 'p-limit';
const limit = pLimit(5); // Max 5 concurrent
const rateLimiter = new RateLimiter({ tokensPerSecond: 10 });
for (const item of items) {
await rateLimiter.acquire();
await limit(() => exaClient.process(item));
}
```
---
## Pitfall #3: Leaking API Keys
### ❌ Anti-Pattern
```typescript
// In frontend code (visible to users!)
const client = new ExaClient({
apiKey: 'sk_live_ACTUAL_KEY_HERE', // Anyone can see this
});
// In git history
git commit -m "add API key" // Exposed forever
```
### ✅ Better Approach
```typescript
// Backend only, environment variable
const client = new ExaClient({
apiKey: process.env.EXA_API_KEY,
});
// Use .gitignore
.env
.env.local
.env.*.local
```
---
## Pitfall #4: Ignoring Idempotency
### ❌ Anti-Pattern
```typescript
// Network error on response = duplicate charge!
try {
await exaClient.charge(order);
} catch (error) {
if (error.code === 'NETWORK_ERROR') {
await exaClient.charge(order); // Charged twice!
}
}
```
### ✅ Better Approach
```typescript
const idempotencyKey = `order-${order.id}-${Date.now()}`;
await exaClient.charge(order, {
idempotencyKey, // Safe to retry
});
```
---
## Pitfall #5: Not Validating Webhooks
### ❌ Anti-Pattern
```typescript
// Trust any incoming request
app.post('/webhook', (req, res) => {
processWebhook(req.body); // Attacker can send fake events
res.sendStatus(200);
});
```
### ✅ Better Approach
```typescript
app.post('/webhook',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-exa-signature'];
if (!verifyExaSignature(req.body, signature)) {
return res.sendStatus(401);
}
processWebhook(JSON.parse(req.body));
res.sendStatus(200);
}
);
```
---
## Pitfall #6: Missing Error Handling
### ❌ Anti-Pattern
```typescript
// Crashes on any error
const result = await exaClient.get(id);
console.log(result.data.nested.value); // TypeError if missing
```
### ✅ Better Approach
```typescript
try {
const result = await exaClient.get(id);
console.log(result?.data?.nested?.value ?? 'default');
} catch (error) {
if (error instanceof ExaNotFoundError) {
return null;
}
if (error instanceof ExaRateLimitError) {
await sleep(error.retryAfter);
return this.get(id); // Retry
}
throw error; // Rethrow unknown errors
}
```
---
## Pitfall #7: Hardcoding Configuration
### ❌ Anti-Pattern
```typescript
const client = new ExaClient({
timeout: 5000, // Too short for some operations
baseUrl: 'https://api.exa.com', // Can't change for staging
});
```
### ✅ Better Approach
```typescript
const client = new ExaClient({
timeout: parseInt(process.env.EXA_TIMEOUT || '30000'),
baseUrl: process.env.EXA_BASE_URL || 'https://api.exa.com',
});
```
---
## Pitfall #8: Not Implementing Circuit Breaker
### ❌ Anti-Pattern
```typescript
// When Exa is down, every request hangs
for (const user of users) {
await exaClient.sync(user); // All timeout sequentially
}
```
### ✅ Better Approach
```typescript
import CircuitBreaker from 'opossum';
const breaker = new CircuitBreaker(exaClient.sync, {
timeout: 10000,
errorThresholdPercentage: 50,
resetTimeout: 30000,
});
// Fails fast when circuit is open
for (const user of users) {
await breaker.fire(user).catch(handleFailure);
}
```
---
## Pitfall #9: Logging Sensitive Data
### ❌ Anti-Pattern
```typescript
console.log('Request:', JSON.stringify(request)); // Logs API key, PII
console.log('User:', user); // Logs email, phone
```
### ✅ Better Approach
```typescript
const redacted = {
...request,
apiKey: '[REDACTED]',
user: { id: user.id }, // Only non-sensitive fields
};
console.log('Request:', JSON.stringify(redacted));
```
---
## Pitfall #10: No Graceful Degradation
### ❌ Anti-Pattern
```typescript
// Entire feature broken if Exa is down
const recommendations = await exaClient.getRecommendations(userId);
return renderPage({ recommendations }); // Page crashes
```
### ✅ Better Approach
```typescript
let recommendations;
try {
recommendations = await exaClient.getRecommendations(userId);
} catch (error) {
recommendations = await getFallbackRecommendations(userId);
reportDegradedService('exa', error);
}
return renderPage({ recommendations, degraded: !recommendations });
```
---
## Instructions
### Step 1: Review for Anti-Patterns
Scan codebase for each pitfall pattern.
### Step 2: Prioritize Fixes
Address security issues first, then performance.
### Step 3: Implement Better Approach
Replace anti-patterns with recommended patterns.
### Step 4: Add Prevention
Set up linting and CI checks to prevent recurrence.
## Output
- Anti-patterns identified
- Fixes prioritized and implemented
- Prevention measures in place
- Code quality improved
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Too many findings | Legacy codebase | Prioritize security first |
| Pattern not detected | Complex code | Manual review |
| False positive | Similar code | Whitelist exceptions |
| Fix breaks tests | Behavior change | Update tests |
## Examples
### Quick Pitfall Scan
```bash
# Check for common pitfalls
grep -r "sk_live_" --include="*.ts" src/ # Key leakage
grep -r "console.log" --include="*.ts" src/ # Potential PII logging
```
## Resources
- [Exa Security Guide](https://docs.exa.com/security)
- [Exa Best Practices](https://docs.exa.com/best-practices)
## Quick Reference Card
| Pitfall | Detection | Prevention |
|---------|-----------|------------|
| Sync in request | High latency | Use queues |
| Rate limit ignore | 429 errors | Implement backoff |
| Key leakage | Git history scan | Env vars, .gitignore |
| No idempotency | Duplicate records | Idempotency keys |
| Unverified webhooks | Security audit | Signature verification |
| Missing error handling | Crashes | Try-catch, types |
| Hardcoded config | Code review | Environment variables |
| No circuit breaker | Cascading failures | opossum, resilience4j |
| Logging PII | Log audit | Redaction middleware |
| No degradation | Total outages | Fallback systems |
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「exa-known-pitfalls」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次