api-security-checker
Audit API security for OWASP Top 10 vulnerabilities, authentication issues, and authorization flaws. Use when securing APIs, fixing security vulnerabilities, or implementing security best practices.
What this skill does
# API Security Checker
Audit API security and identify vulnerabilities based on OWASP Top 10.
## Quick Start
Check authentication, validate inputs, prevent SQL injection, implement rate limiting, use HTTPS.
## Instructions
### OWASP Top 10 for APIs
**1. Broken Object Level Authorization:**
```javascript
// Bad: No authorization check
app.get('/api/users/:id', (req, res) => {
const user = await User.findById(req.params.id);
res.json(user);
});
// Good: Check ownership
app.get('/api/users/:id', auth, async (req, res) => {
if (req.user.id !== req.params.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
const user = await User.findById(req.params.id);
res.json(user);
});
```
**2. Broken Authentication:**
```javascript
// Bad: Weak password requirements
const isValidPassword = (password) => password.length >= 6;
// Good: Strong requirements
const isValidPassword = (password) => {
return password.length >= 12 &&
/[A-Z]/.test(password) &&
/[a-z]/.test(password) &&
/[0-9]/.test(password) &&
/[^A-Za-z0-9]/.test(password);
};
// Implement rate limiting
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts
message: 'Too many login attempts'
});
app.post('/api/login', loginLimiter, loginHandler);
```
**3. Excessive Data Exposure:**
```javascript
// Bad: Exposing sensitive data
app.get('/api/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
res.json(user); // Includes password hash, email, etc.
});
// Good: Return only necessary fields
app.get('/api/users/:id', async (req, res) => {
const user = await User.findById(req.params.id)
.select('id username avatar');
res.json(user);
});
```
**4. Lack of Resources & Rate Limiting:**
```javascript
const rateLimit = require('express-rate-limit');
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', apiLimiter);
```
**5. Broken Function Level Authorization:**
```javascript
// Bad: No role check
app.delete('/api/users/:id', auth, deleteUser);
// Good: Check admin role
app.delete('/api/users/:id', auth, requireAdmin, deleteUser);
function requireAdmin(req, res, next) {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Admin access required' });
}
next();
}
```
**6. Mass Assignment:**
```javascript
// Bad: Accepting all fields
app.put('/api/users/:id', async (req, res) => {
await User.update(req.params.id, req.body); // Can set isAdmin!
});
// Good: Whitelist fields
app.put('/api/users/:id', async (req, res) => {
const { name, email, avatar } = req.body;
await User.update(req.params.id, { name, email, avatar });
});
```
**7. Security Misconfiguration:**
```javascript
// Set security headers
const helmet = require('helmet');
app.use(helmet());
// Disable X-Powered-By
app.disable('x-powered-by');
// CORS configuration
const cors = require('cors');
app.use(cors({
origin: process.env.ALLOWED_ORIGINS.split(','),
credentials: true
}));
```
**8. Injection:**
```javascript
// Bad: SQL injection vulnerable
const query = `SELECT * FROM users WHERE email = '${email}'`;
// Good: Parameterized query
const query = 'SELECT * FROM users WHERE email = $1';
const result = await db.query(query, [email]);
// Input validation
const { body, validationResult } = require('express-validator');
app.post('/api/users',
body('email').isEmail().normalizeEmail(),
body('name').trim().escape(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process request
}
);
```
**9. Improper Assets Management:**
```javascript
// Document API versions
// Deprecate old versions
// Remove unused endpoints
// Version API
app.use('/api/v1', v1Routes);
app.use('/api/v2', v2Routes);
// Deprecation header
app.use('/api/v1', (req, res, next) => {
res.set('Deprecation', 'true');
res.set('Sunset', 'Sat, 31 Dec 2024 23:59:59 GMT');
next();
});
```
**10. Insufficient Logging & Monitoring:**
```javascript
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Log security events
app.post('/api/login', async (req, res) => {
try {
const user = await authenticate(req.body);
logger.info('Login successful', { userId: user.id, ip: req.ip });
res.json({ token: generateToken(user) });
} catch (error) {
logger.warn('Login failed', { email: req.body.email, ip: req.ip });
res.status(401).json({ error: 'Invalid credentials' });
}
});
```
### Authentication Security
**JWT best practices:**
```javascript
const jwt = require('jsonwebtoken');
// Generate token
const generateToken = (user) => {
return jwt.sign(
{ id: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '15m' } // Short expiry
);
};
// Generate refresh token
const generateRefreshToken = (user) => {
return jwt.sign(
{ id: user.id },
process.env.REFRESH_SECRET,
{ expiresIn: '7d' }
);
};
// Verify token
const verifyToken = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
```
**Password hashing:**
```javascript
const bcrypt = require('bcrypt');
// Hash password
const hashPassword = async (password) => {
const salt = await bcrypt.genSalt(12);
return bcrypt.hash(password, salt);
};
// Verify password
const verifyPassword = async (password, hash) => {
return bcrypt.compare(password, hash);
};
```
### Input Validation
**Sanitize inputs:**
```javascript
const validator = require('validator');
// Email validation
if (!validator.isEmail(email)) {
return res.status(400).json({ error: 'Invalid email' });
}
// URL validation
if (!validator.isURL(url)) {
return res.status(400).json({ error: 'Invalid URL' });
}
// Escape HTML
const sanitized = validator.escape(userInput);
```
**Schema validation:**
```javascript
const Joi = require('joi');
const userSchema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(12).required(),
name: Joi.string().min(2).max(50).required()
});
app.post('/api/users', async (req, res) => {
const { error, value } = userSchema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
// Process validated data
});
```
### Authorization
**Role-Based Access Control (RBAC):**
```javascript
const roles = {
user: ['read:own'],
admin: ['read:any', 'write:any', 'delete:any']
};
const checkPermission = (permission) => {
return (req, res, next) => {
const userPermissions = roles[req.user.role] || [];
if (!userPermissions.includes(permission)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
};
app.delete('/api/users/:id',
auth,
checkPermission('delete:any'),
deleteUser
);
```
### HTTPS and Transport Security
**Force HTTPS:**
```javascript
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https' && process.env.NODE_ENV === 'production') {
res.redirect(`https://${req.header('host')}${req.url}`);
} else {
next();
}
});
```
**Security headers:**
```javascript
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],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.