security
Application security patterns - authentication, secrets management, input validation, OWASP Top 10. Use when: auth, JWT, secrets, API keys, SQL injection, XSS, CSRF, RLS, security audit, pen testing basics.
What this skill does
<objective>
Comprehensive security skill covering authentication patterns, secrets management, input validation, and common vulnerability prevention. Focuses on practical patterns for web applications with Supabase, Next.js, and Python backends.
Security is not optional - it's a fundamental requirement. This skill helps you build secure applications from the start, not bolt on security as an afterthought.
</objective>
<quick_start>
**Security essentials for any new project:**
1. **Secrets**: Never commit to git, validate at startup
```typescript
// .env (gitignored) + envSchema.parse(process.env)
```
2. **Auth**: Short-lived JWTs + httpOnly cookies
```typescript
jwt.sign(payload, secret, { expiresIn: '15m' })
```
3. **Input**: Validate everything with schemas
```typescript
const data = z.object({ email: z.string().email() }).parse(input)
```
4. **SQL**: Always use parameterized queries (ORMs handle this)
5. **RLS**: Enable on all Supabase tables with user-scoped policies
</quick_start>
<success_criteria>
Security implementation is successful when:
- All secrets in environment variables, validated at startup
- No secrets in version control (verified with gitleaks)
- JWT tokens short-lived (≤15 min) with refresh token rotation
- All user input validated with Zod or similar schema validation
- RLS enabled on all database tables with appropriate policies
- CSP headers configured (no unsafe-inline where possible)
- Security checklist completed before deployment
</success_criteria>
<security_mindset>
## The Security Mindset
### Core Principles
1. **Defense in depth** - Multiple layers of security, not one wall
2. **Least privilege** - Grant minimum access required
3. **Never trust input** - Validate everything from users and external systems
4. **Fail secure** - Errors should deny access, not grant it
5. **Keep secrets secret** - API keys never in code or logs
### Security Questions to Ask
Before shipping any feature:
- [ ] What data does this expose?
- [ ] Who can access this endpoint/page?
- [ ] What happens if the user sends malicious input?
- [ ] Are secrets properly protected?
- [ ] Is sensitive data logged?
</security_mindset>
<authentication>
## Authentication Patterns
### JWT vs Session
| Aspect | JWT | Session |
|--------|-----|---------|
| Storage | Client (localStorage/cookie) | Server (DB/Redis) |
| Scalability | Stateless, easy to scale | Requires shared session store |
| Revocation | Hard (need blacklist) | Easy (delete from store) |
| Size | Larger (contains claims) | Small (just session ID) |
| Best for | APIs, microservices | Traditional web apps |
### JWT Best Practices
```typescript
// DO: Short-lived access tokens + refresh tokens
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m' } // Short-lived!
);
const refreshToken = jwt.sign(
{ userId: user.id },
process.env.JWT_REFRESH_SECRET,
{ expiresIn: '7d' }
);
// DON'T: Long-lived tokens with sensitive data
// Bad example - never do this:
// { expiresIn: '365d' } // Too long!
// Including PII like SSN in token payload
```
### Token Storage
| Method | XSS Safe | CSRF Safe | Recommendation |
|--------|----------|-----------|----------------|
| localStorage | No | Yes | Avoid for auth |
| httpOnly cookie | Yes | No (needs CSRF token) | Recommended |
| Memory (variable) | Yes | Yes | Best for SPAs |
### Refresh Token Flow
```
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Client │ │ Server │ │ DB │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
│ Login (email, password) │ │
│─────────────────────────────>│ │
│ │ Verify credentials │
│ │─────────────────────────────>│
│ │<─────────────────────────────│
│ Access token (15m) │ │
│ Refresh token (7d) │ Store refresh token hash │
│<─────────────────────────────│─────────────────────────────>│
│ │ │
│ API call + access token │ │
│─────────────────────────────>│ │
│ Response │ │
│<─────────────────────────────│ │
│ │ │
│ [Access token expired] │ │
│ Refresh token │ │
│─────────────────────────────>│ Verify refresh token │
│ │─────────────────────────────>│
│ New access token │ │
│<─────────────────────────────│ │
```
### Password Handling
```typescript
import bcrypt from 'bcrypt';
// DO: Hash with sufficient rounds
const SALT_ROUNDS = 12; // ~300ms on modern hardware
const hash = await bcrypt.hash(password, SALT_ROUNDS);
// DO: Constant-time comparison
const isValid = await bcrypt.compare(inputPassword, storedHash);
// DON'T: Use weak hashing algorithms like MD5 or SHA1 for passwords
```
### Password Requirements
```typescript
const passwordSchema = z.string()
.min(8, 'Minimum 8 characters')
.max(128, 'Maximum 128 characters')
.regex(/[a-z]/, 'Must contain lowercase')
.regex(/[A-Z]/, 'Must contain uppercase')
.regex(/[0-9]/, 'Must contain number')
.regex(/[^a-zA-Z0-9]/, 'Must contain special character');
// Check against common passwords (haveibeenpwned API)
async function isPasswordPwned(password: string): Promise<boolean> {
const sha1 = crypto.createHash('sha1').update(password).digest('hex').toUpperCase();
const prefix = sha1.slice(0, 5);
const suffix = sha1.slice(5);
const response = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);
const text = await response.text();
return text.includes(suffix);
}
```
</authentication>
<secrets_management>
## Secrets Management
**Golden rule:** Never commit secrets to version control. Use `.env` files (gitignored), validate all env vars at startup with Zod schemas, support rotation with multiple active secrets, and never log sensitive data.
See `reference/secrets-management.md` for gitignore patterns, env var templates, Zod validation, rotation patterns, and log masking.
</secrets_management>
<input_validation>
## Input Validation
### Validate at System Boundaries
```
┌─────────────────────────────────────────────────────────┐
│ Your Application │
│ │
│ ┌──────────┐ VALIDATE ┌──────────────────┐ │
│ │ User │ ───────────────> │ Business Logic │ │
│ │ Input │ │ (trusted data) │ │
│ └──────────┘ └──────────────────┘ │
│ │
│ ┌──────────┐ VALIDATE ┌──────────────────┐ │
│ │ External │ ───────────────> │ Services │ │
│ │ API │ │ │ │
│ └──────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────┘
```
### Schema Validation (Zod)
```typescript
import { z } from 'zod';
// Define schemas
const createUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8).max(128),
name: z.string().min(1).max(100),
age: z.number().int().min(13).max(120).optional(),
});
// Validate input
export async function createUser(input: unknown) {
const data = createUserSchema.parse(input)Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.