fix: harden unicode safety checks

This commit is contained in:
Affaan Mustafa
2026-03-29 08:59:06 -04:00
parent dd675d4258
commit 866d9ebb53
239 changed files with 3780 additions and 3962 deletions

View File

@@ -23,7 +23,7 @@ Backend architecture patterns and best practices for scalable server-side applic
### RESTful API Structure
```typescript
// Resource-based URLs
// PASS: Resource-based URLs
GET /api/markets # List resources
GET /api/markets/:id # Get single resource
POST /api/markets # Create resource
@@ -31,7 +31,7 @@ PUT /api/markets/:id # Replace resource
PATCH /api/markets/:id # Update resource
DELETE /api/markets/:id # Delete resource
// Query parameters for filtering, sorting, pagination
// PASS: Query parameters for filtering, sorting, pagination
GET /api/markets?status=active&sort=volume&limit=20&offset=0
```
@@ -131,7 +131,7 @@ export default withAuth(async (req, res) => {
### Query Optimization
```typescript
// GOOD: Select only needed columns
// PASS: GOOD: Select only needed columns
const { data } = await supabase
.from('markets')
.select('id, name, status, volume')
@@ -139,7 +139,7 @@ const { data } = await supabase
.order('volume', { ascending: false })
.limit(10)
// BAD: Select everything
// FAIL: BAD: Select everything
const { data } = await supabase
.from('markets')
.select('*')
@@ -148,13 +148,13 @@ const { data } = await supabase
### N+1 Query Prevention
```typescript
// BAD: N+1 query problem
// FAIL: BAD: N+1 query problem
const markets = await getMarkets()
for (const market of markets) {
market.creator = await getUser(market.creator_id) // N queries
}
// GOOD: Batch fetch
// PASS: GOOD: Batch fetch
const markets = await getMarkets()
const creatorIds = markets.map(m => m.creator_id)
const creators = await getUsers(creatorIds) // 1 query

View File

@@ -48,12 +48,12 @@ Universal coding standards applicable across all projects.
### Variable Naming
```typescript
// GOOD: Descriptive names
// PASS: GOOD: Descriptive names
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
// BAD: Unclear names
// FAIL: BAD: Unclear names
const q = 'election'
const flag = true
const x = 1000
@@ -62,12 +62,12 @@ const x = 1000
### Function Naming
```typescript
// GOOD: Verb-noun pattern
// PASS: GOOD: Verb-noun pattern
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }
// BAD: Unclear or noun-only
// FAIL: BAD: Unclear or noun-only
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
@@ -76,7 +76,7 @@ function email(e) { }
### Immutability Pattern (CRITICAL)
```typescript
// ALWAYS use spread operator
// PASS: ALWAYS use spread operator
const updatedUser = {
...user,
name: 'New Name'
@@ -84,7 +84,7 @@ const updatedUser = {
const updatedArray = [...items, newItem]
// NEVER mutate directly
// FAIL: NEVER mutate directly
user.name = 'New Name' // BAD
items.push(newItem) // BAD
```
@@ -92,7 +92,7 @@ items.push(newItem) // BAD
### Error Handling
```typescript
// GOOD: Comprehensive error handling
// PASS: GOOD: Comprehensive error handling
async function fetchData(url: string) {
try {
const response = await fetch(url)
@@ -108,7 +108,7 @@ async function fetchData(url: string) {
}
}
// BAD: No error handling
// FAIL: BAD: No error handling
async function fetchData(url) {
const response = await fetch(url)
return response.json()
@@ -118,14 +118,14 @@ async function fetchData(url) {
### Async/Await Best Practices
```typescript
// GOOD: Parallel execution when possible
// PASS: GOOD: Parallel execution when possible
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats()
])
// BAD: Sequential when unnecessary
// FAIL: BAD: Sequential when unnecessary
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
@@ -134,7 +134,7 @@ const stats = await fetchStats()
### Type Safety
```typescript
// GOOD: Proper types
// PASS: GOOD: Proper types
interface Market {
id: string
name: string
@@ -146,7 +146,7 @@ function getMarket(id: string): Promise<Market> {
// Implementation
}
// BAD: Using 'any'
// FAIL: BAD: Using 'any'
function getMarket(id: any): Promise<any> {
// Implementation
}
@@ -157,7 +157,7 @@ function getMarket(id: any): Promise<any> {
### Component Structure
```typescript
// GOOD: Functional component with types
// PASS: GOOD: Functional component with types
interface ButtonProps {
children: React.ReactNode
onClick: () => void
@@ -182,7 +182,7 @@ export function Button({
)
}
// BAD: No types, unclear structure
// FAIL: BAD: No types, unclear structure
export function Button(props) {
return <button onClick={props.onClick}>{props.children}</button>
}
@@ -191,7 +191,7 @@ export function Button(props) {
### Custom Hooks
```typescript
// GOOD: Reusable custom hook
// PASS: GOOD: Reusable custom hook
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
@@ -213,25 +213,25 @@ const debouncedQuery = useDebounce(searchQuery, 500)
### State Management
```typescript
// GOOD: Proper state updates
// PASS: GOOD: Proper state updates
const [count, setCount] = useState(0)
// Functional update for state based on previous state
setCount(prev => prev + 1)
// BAD: Direct state reference
// FAIL: BAD: Direct state reference
setCount(count + 1) // Can be stale in async scenarios
```
### Conditional Rendering
```typescript
// GOOD: Clear conditional rendering
// PASS: GOOD: Clear conditional rendering
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}
// BAD: Ternary hell
// FAIL: BAD: Ternary hell
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}
```
@@ -254,7 +254,7 @@ GET /api/markets?status=active&limit=10&offset=0
### Response Format
```typescript
// GOOD: Consistent response structure
// PASS: GOOD: Consistent response structure
interface ApiResponse<T> {
success: boolean
data?: T
@@ -285,7 +285,7 @@ return NextResponse.json({
```typescript
import { z } from 'zod'
// GOOD: Schema validation
// PASS: GOOD: Schema validation
const CreateMarketSchema = z.object({
name: z.string().min(1).max(200),
description: z.string().min(1).max(2000),
@@ -348,14 +348,14 @@ types/market.types.ts # camelCase with .types suffix
### When to Comment
```typescript
// GOOD: Explain WHY, not WHAT
// PASS: GOOD: Explain WHY, not WHAT
// Use exponential backoff to avoid overwhelming the API during outages
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)
// Deliberately using mutation here for performance with large arrays
items.push(newItem)
// BAD: Stating the obvious
// FAIL: BAD: Stating the obvious
// Increment counter by 1
count++
@@ -395,12 +395,12 @@ export async function searchMarkets(
```typescript
import { useMemo, useCallback } from 'react'
// GOOD: Memoize expensive computations
// PASS: GOOD: Memoize expensive computations
const sortedMarkets = useMemo(() => {
return markets.sort((a, b) => b.volume - a.volume)
}, [markets])
// GOOD: Memoize callbacks
// PASS: GOOD: Memoize callbacks
const handleSearch = useCallback((query: string) => {
setSearchQuery(query)
}, [])
@@ -411,7 +411,7 @@ const handleSearch = useCallback((query: string) => {
```typescript
import { lazy, Suspense } from 'react'
// GOOD: Lazy load heavy components
// PASS: GOOD: Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'))
export function Dashboard() {
@@ -426,13 +426,13 @@ export function Dashboard() {
### Database Queries
```typescript
// GOOD: Select only needed columns
// PASS: GOOD: Select only needed columns
const { data } = await supabase
.from('markets')
.select('id, name, status')
.limit(10)
// BAD: Select everything
// FAIL: BAD: Select everything
const { data } = await supabase
.from('markets')
.select('*')
@@ -459,12 +459,12 @@ test('calculates similarity correctly', () => {
### Test Naming
```typescript
// GOOD: Descriptive test names
// PASS: GOOD: Descriptive test names
test('returns empty array when no markets match query', () => { })
test('throws error when OpenAI API key is missing', () => { })
test('falls back to substring search when Redis unavailable', () => { })
// BAD: Vague test names
// FAIL: BAD: Vague test names
test('works', () => { })
test('test search', () => { })
```
@@ -475,12 +475,12 @@ Watch for these anti-patterns:
### 1. Long Functions
```typescript
// BAD: Function > 50 lines
// FAIL: BAD: Function > 50 lines
function processMarketData() {
// 100 lines of code
}
// GOOD: Split into smaller functions
// PASS: GOOD: Split into smaller functions
function processMarketData() {
const validated = validateData()
const transformed = transformData(validated)
@@ -490,7 +490,7 @@ function processMarketData() {
### 2. Deep Nesting
```typescript
// BAD: 5+ levels of nesting
// FAIL: BAD: 5+ levels of nesting
if (user) {
if (user.isAdmin) {
if (market) {
@@ -503,7 +503,7 @@ if (user) {
}
}
// GOOD: Early returns
// PASS: GOOD: Early returns
if (!user) return
if (!user.isAdmin) return
if (!market) return
@@ -515,11 +515,11 @@ if (!hasPermission) return
### 3. Magic Numbers
```typescript
// BAD: Unexplained numbers
// FAIL: BAD: Unexplained numbers
if (retryCount > 3) { }
setTimeout(callback, 500)
// GOOD: Named constants
// PASS: GOOD: Named constants
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500

View File

@@ -23,7 +23,7 @@ Modern frontend patterns for React, Next.js, and performant user interfaces.
### Composition Over Inheritance
```typescript
// GOOD: Component composition
// PASS: GOOD: Component composition
interface CardProps {
children: React.ReactNode
variant?: 'default' | 'outlined'
@@ -294,17 +294,17 @@ export function useMarkets() {
### Memoization
```typescript
// useMemo for expensive computations
// PASS: useMemo for expensive computations
const sortedMarkets = useMemo(() => {
return markets.sort((a, b) => b.volume - a.volume)
}, [markets])
// useCallback for functions passed to children
// PASS: useCallback for functions passed to children
const handleSearch = useCallback((query: string) => {
setSearchQuery(query)
}, [])
// React.memo for pure components
// PASS: React.memo for pure components
export const MarketCard = React.memo<MarketCardProps>(({ market }) => {
return (
<div className="market-card">
@@ -320,7 +320,7 @@ export const MarketCard = React.memo<MarketCardProps>(({ market }) => {
```typescript
import { lazy, Suspense } from 'react'
// Lazy load heavy components
// PASS: Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'))
const ThreeJsBackground = lazy(() => import('./ThreeJsBackground'))
@@ -515,7 +515,7 @@ export class ErrorBoundary extends React.Component<
```typescript
import { motion, AnimatePresence } from 'framer-motion'
// List animations
// PASS: List animations
export function AnimatedMarketList({ markets }: { markets: Market[] }) {
return (
<AnimatePresence>
@@ -534,7 +534,7 @@ export function AnimatedMarketList({ markets }: { markets: Market[] }) {
)
}
// Modal animations
// PASS: Modal animations
export function Modal({ isOpen, onClose, children }: ModalProps) {
return (
<AnimatePresence>

View File

@@ -22,13 +22,13 @@ This skill ensures all code follows security best practices and identifies poten
### 1. Secrets Management
#### NEVER Do This
#### FAIL: NEVER Do This
```typescript
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
const dbPassword = "password123" // In source code
```
#### ALWAYS Do This
#### PASS: ALWAYS Do This
```typescript
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
@@ -108,14 +108,14 @@ function validateFileUpload(file: File) {
### 3. SQL Injection Prevention
#### NEVER Concatenate SQL
#### FAIL: NEVER Concatenate SQL
```typescript
// DANGEROUS - SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
```
#### ALWAYS Use Parameterized Queries
#### PASS: ALWAYS Use Parameterized Queries
```typescript
// Safe - parameterized query
const { data } = await supabase
@@ -140,10 +140,10 @@ await db.query(
#### JWT Token Handling
```typescript
// WRONG: localStorage (vulnerable to XSS)
// FAIL: WRONG: localStorage (vulnerable to XSS)
localStorage.setItem('token', token)
// CORRECT: httpOnly cookies
// PASS: CORRECT: httpOnly cookies
res.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
```
@@ -300,18 +300,18 @@ app.use('/api/search', searchLimiter)
#### Logging
```typescript
// WRONG: Logging sensitive data
// FAIL: WRONG: Logging sensitive data
console.log('User login:', { email, password })
console.log('Payment:', { cardNumber, cvv })
// CORRECT: Redact sensitive data
// PASS: CORRECT: Redact sensitive data
console.log('User login:', { email, userId })
console.log('Payment:', { last4: card.last4, userId })
```
#### Error Messages
```typescript
// WRONG: Exposing internal details
// FAIL: WRONG: Exposing internal details
catch (error) {
return NextResponse.json(
{ error: error.message, stack: error.stack },
@@ -319,7 +319,7 @@ catch (error) {
)
}
// CORRECT: Generic error messages
// PASS: CORRECT: Generic error messages
catch (error) {
console.error('Internal error:', error)
return NextResponse.json(

View File

@@ -314,39 +314,39 @@ npm run test:coverage
## Common Testing Mistakes to Avoid
### WRONG: Testing Implementation Details
### FAIL: WRONG: Testing Implementation Details
```typescript
// Don't test internal state
expect(component.state.count).toBe(5)
```
### CORRECT: Test User-Visible Behavior
### PASS: CORRECT: Test User-Visible Behavior
```typescript
// Test what users see
expect(screen.getByText('Count: 5')).toBeInTheDocument()
```
### WRONG: Brittle Selectors
### FAIL: WRONG: Brittle Selectors
```typescript
// Breaks easily
await page.click('.css-class-xyz')
```
### CORRECT: Semantic Selectors
### PASS: CORRECT: Semantic Selectors
```typescript
// Resilient to changes
await page.click('button:has-text("Submit")')
await page.click('[data-testid="submit-button"]')
```
### WRONG: No Test Isolation
### FAIL: WRONG: No Test Isolation
```typescript
// Tests depend on each other
test('creates user', () => { /* ... */ })
test('updates same user', () => { /* depends on previous test */ })
```
### CORRECT: Independent Tests
### PASS: CORRECT: Independent Tests
```typescript
// Each test sets up its own data
test('creates user', () => {