api-security-hardener
Hardens API security with rate limiting, input validation, authentication, and protection against common attacks. Use when users request "API security", "secure API", "rate limiting", "input validation", or "API protection".
What this skill does
# API Security Hardener
Implement comprehensive security measures for production APIs.
## Core Workflow
1. **Input validation**: Sanitize and validate all input
2. **Authentication**: Secure identity verification
3. **Authorization**: Role-based access control
4. **Rate limiting**: Prevent abuse
5. **Security headers**: HTTP header protection
6. **Logging & monitoring**: Detect threats
## Input Validation
### Zod Schema Validation
```typescript
// validation/schemas.ts
import { z } from 'zod';
// Common schemas
export const emailSchema = z.string().email().toLowerCase().trim();
export const passwordSchema = z
.string()
.min(8, 'Password must be at least 8 characters')
.max(128, 'Password too long')
.regex(/[A-Z]/, 'Password must contain uppercase letter')
.regex(/[a-z]/, 'Password must contain lowercase letter')
.regex(/[0-9]/, 'Password must contain number')
.regex(/[^A-Za-z0-9]/, 'Password must contain special character');
export const uuidSchema = z.string().uuid();
export const paginationSchema = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
sortBy: z.string().optional(),
sortOrder: z.enum(['asc', 'desc']).default('desc'),
});
// User schemas
export const createUserSchema = z.object({
email: emailSchema,
password: passwordSchema,
name: z.string().min(2).max(100).trim(),
});
export const updateUserSchema = createUserSchema.partial().omit({ password: true });
// Sanitize HTML content
export const sanitizedStringSchema = z.string().transform((val) => {
return val
.replace(/[<>]/g, '') // Remove < and >
.replace(/javascript:/gi, '') // Remove javascript: protocol
.replace(/on\w+=/gi, '') // Remove event handlers
.trim();
});
```
### Validation Middleware
```typescript
// middleware/validate.ts
import { Request, Response, NextFunction } from 'express';
import { z, ZodSchema } from 'zod';
interface ValidationSchemas {
body?: ZodSchema;
query?: ZodSchema;
params?: ZodSchema;
}
export function validate(schemas: ValidationSchemas) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
if (schemas.body) {
req.body = await schemas.body.parseAsync(req.body);
}
if (schemas.query) {
req.query = await schemas.query.parseAsync(req.query);
}
if (schemas.params) {
req.params = await schemas.params.parseAsync(req.params);
}
next();
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({
error: 'Validation Error',
details: error.errors.map((e) => ({
field: e.path.join('.'),
message: e.message,
})),
});
}
next(error);
}
};
}
// Usage
router.post(
'/users',
validate({ body: createUserSchema }),
createUserHandler
);
```
## Rate Limiting
```typescript
// middleware/rate-limit.ts
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL!);
// General API rate limit
export const apiLimiter = rateLimit({
store: new RedisStore({
sendCommand: (...args: string[]) => redis.call(...args),
}),
windowMs: 60 * 1000, // 1 minute
max: 100, // 100 requests per minute
message: {
error: 'Too Many Requests',
message: 'Please try again later',
retryAfter: 60,
},
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
// Use user ID if authenticated, otherwise IP
return req.user?.id || req.ip;
},
skip: (req) => {
// Skip rate limiting for health checks
return req.path === '/health';
},
});
// Stricter limit for authentication endpoints
export const authLimiter = rateLimit({
store: new RedisStore({
sendCommand: (...args: string[]) => redis.call(...args),
}),
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts
message: {
error: 'Too Many Attempts',
message: 'Account temporarily locked. Try again in 15 minutes.',
},
keyGenerator: (req) => `auth:${req.ip}:${req.body?.email}`,
});
// Cost-based rate limiting for expensive operations
export const costLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 1000, // points per hour
keyGenerator: (req) => req.user?.id || req.ip,
handler: (req, res) => {
res.status(429).json({
error: 'Rate Limit Exceeded',
message: 'Hourly quota exceeded',
});
},
});
// Usage with cost assignment
router.post('/expensive-operation', (req, res, next) => {
req.rateLimit = { ...req.rateLimit, current: req.rateLimit.current + 10 };
next();
}, costLimiter, handler);
```
## Authentication Middleware
```typescript
// middleware/auth.ts
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
interface JWTPayload {
sub: string;
email: string;
role: string;
iat: number;
exp: number;
}
declare global {
namespace Express {
interface Request {
user?: JWTPayload;
}
}
}
export function authenticate(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({
error: 'Unauthorized',
message: 'Missing or invalid authorization header',
});
}
const token = authHeader.slice(7);
try {
const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;
// Check token expiration with buffer
if (payload.exp * 1000 < Date.now()) {
return res.status(401).json({
error: 'Token Expired',
message: 'Please re-authenticate',
});
}
req.user = payload;
next();
} catch (error) {
if (error instanceof jwt.TokenExpiredError) {
return res.status(401).json({
error: 'Token Expired',
message: 'Please re-authenticate',
});
}
if (error instanceof jwt.JsonWebTokenError) {
return res.status(401).json({
error: 'Invalid Token',
message: 'Token validation failed',
});
}
next(error);
}
}
// Optional authentication
export function optionalAuth(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return next();
}
const token = authHeader.slice(7);
try {
req.user = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload;
} catch {
// Ignore invalid tokens for optional auth
}
next();
}
```
## Authorization Middleware
```typescript
// middleware/authorize.ts
import { Request, Response, NextFunction } from 'express';
type Role = 'admin' | 'user' | 'guest';
interface Permission {
resource: string;
actions: string[];
}
const rolePermissions: Record<Role, Permission[]> = {
admin: [
{ resource: '*', actions: ['*'] },
],
user: [
{ resource: 'posts', actions: ['read', 'create', 'update:own', 'delete:own'] },
{ resource: 'comments', actions: ['read', 'create', 'update:own', 'delete:own'] },
{ resource: 'profile', actions: ['read', 'update'] },
],
guest: [
{ resource: 'posts', actions: ['read'] },
{ resource: 'comments', actions: ['read'] },
],
};
export function authorize(...roles: Role[]) {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return res.status(401).json({
error: 'Unauthorized',
message: 'Authentication required',
});
}
const userRole = req.user.role as Role;
if (!roles.includes(userRole)) {
return res.status(403).json({
error: 'Forbidden',
message: 'Insufficient permissions',
});
}
next();
};
}
export function hasPermission(resource: string, action: string) {
return (req: Request, res: Response, next: NextFunction) => {
if (!req.user) {
return res.status(401).jsRelated 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.