Security Best Practices for Vibe Coders (Don’t Leak Secrets)
Security Best Practices for Vibe Coders (Don't Leak Secrets)
AI-generated code can introduce security vulnerabilities if you're not careful. From hardcoded API keys to SQL injection, the risks are real.
This guide teaches you how to Vibe Code securely.
The Top 5 Security Risks
1. Hardcoded Secrets
The Risk:
AI might generate code with API keys, passwords, or tokens hardcoded in the source.
Example of Bad AI-Generated Code:
“`javascript
const stripe = require(‘stripe')(‘sk_live_ABC123XYZ'); // NEVER DO THIS
“`
The Fix:
Always use environment variables:
“`javascript
const stripe = require(‘stripe')(process.env.STRIPE_SECRET_KEY);
“`
Prompt to Prevent This:
> “Generate a Stripe integration. Use environment variables for all API keys. Never hardcode secrets.”
2. SQL Injection
The Risk:
AI might concatenate user input into SQL queries.
Example of Vulnerable Code:
“`javascript
const query = `SELECT * FROM users WHERE email = ‘${userEmail}'`;
“`
The Fix:
Use parameterized queries:
“`javascript
const query = ‘SELECT * FROM users WHERE email = ?';
db.query(query, [userEmail]);
“`
Prompt to Prevent This:
> “Generate a database query to find users by email. Use parameterized queries to prevent SQL injection.”
3. XSS (Cross-Site Scripting)
The Risk:
AI might render user input without sanitization.
Example of Vulnerable Code:
“`jsx
The Fix:
Sanitize user input:
“`jsx
import DOMPurify from ‘dompurify';
Prompt to Prevent This:
> “Display user comments. Sanitize all user input to prevent XSS attacks.”
4. Insecure Dependencies
The Risk:
AI might suggest outdated libraries with known vulnerabilities.
The Fix:
Always check for vulnerabilities:
“`bash
npm audit
npm audit fix
“`
Prompt to Prevent This:
> “Use the latest stable version of [library]. Check for security vulnerabilities.”
5. Missing Authentication/Authorization
The Risk:
AI might create API endpoints without proper access control.
Example of Vulnerable Code:
“`javascript
app.delete(‘/api/users/:id', async (req, res) => {
await db.query(‘DELETE FROM users WHERE id = ?', [req.params.id]);
res.json({ success: true });
});
“`
The Fix:
Add authentication and authorization:
“`javascript
app.delete(‘/api/users/:id', authMiddleware, async (req, res) => {
// Check if user is admin
if (req.user.role !== ‘admin') {
return res.status(403).json({ error: ‘Forbidden' });
}
await db.query(‘DELETE FROM users WHERE id = ?', [req.params.id]);
res.json({ success: true });
});
“`
Security Checklist for AI-Generated Code
Before Committing
– [ ] No hardcoded secrets
– [ ] All user input is validated
– [ ] All database queries use parameterized statements
– [ ] All user-generated content is sanitized
– [ ] Authentication is required for protected routes
– [ ] Authorization checks are in place
– [ ] HTTPS is enforced
– [ ] CORS is properly configured
– [ ] Rate limiting is implemented
– [ ] Error messages don't leak sensitive information
Tools to Use
“`bash
Check for secrets
npm install -g secretlint
secretlint “/*”
Security linting
npm install -D eslint-plugin-security
npx eslint –plugin security
Dependency audit
npm audit
SAST (Static Application Security Testing)
npx snyk test
“`
Secure Prompting Patterns
Pattern 1: Explicit Security Requirements
Bad Prompt:
> “Create a login endpoint.”
Good Prompt:
> “Create a login endpoint with these security requirements:
> – Use bcrypt for password hashing (cost factor 12)
> – Implement rate limiting (5 attempts per 15 minutes)
> – Return generic error messages (don't reveal if email exists)
> – Use JWT for session management
> – Set secure, httpOnly cookies”
Pattern 2: Reference Security Standards
Prompt:
> “Create a password reset flow following OWASP best practices.”
Pattern 3: Request Security Review
Prompt:
> “Review this authentication code for security vulnerabilities. Check for:
> – SQL injection
> – XSS
> – CSRF
> – Session fixation
> – Timing attacks”
Environment Variable Management
Development
Use `.env` files (never commit these):
“`env
DATABASE_URL=postgresql://localhost/mydb
STRIPE_SECRET_KEY=sk_test_…
JWT_SECRET=your-secret-key
“`
Production
Use your hosting platform's environment variable system:
* Vercel: Environment Variables in dashboard
* Netlify: Environment Variables in dashboard
* Railway: Environment Variables in dashboard
Best Practices
1. Use different keys for dev/staging/production
2. Rotate secrets regularly
3. Use a secrets manager (AWS Secrets Manager, HashiCorp Vault)
4. Never log secrets
Secure Code Review Process
When reviewing AI-generated code:
1. Check for Secrets
“`bash
git diff | grep -i “api_key\|secret\|password\|token”
“`
2. Check for SQL Injection
Look for string concatenation in database queries.
3. Check for XSS
Look for `dangerouslySetInnerHTML` or direct DOM manipulation.
4. Check Authentication
Verify that protected routes have middleware.
5. Check Authorization
Verify that users can only access their own data.
Common Security Mistakes
Mistake 1: Trusting User Input
Never trust user input. Always validate and sanitize.
“`javascript
// Bad
const age = req.body.age;
// Good
const age = parseInt(req.body.age);
if (isNaN(age) || age < 0 || age > 150) {
return res.status(400).json({ error: ‘Invalid age' });
}
“`
Mistake 2: Weak Password Requirements
Prompt:
> “Implement password validation. Requirements:
> – Minimum 12 characters
> – At least one uppercase letter
> – At least one lowercase letter
> – At least one number
> – At least one special character”
Mistake 3: Not Using HTTPS
Always enforce HTTPS in production:
“`javascript
if (process.env.NODE_ENV === ‘production' && req.headers[‘x-forwarded-proto'] !== ‘https') {
return res.redirect(‘https://' + req.headers.host + req.url);
}
“`
Mistake 4: Exposing Stack Traces
Bad:
“`javascript
app.use((err, req, res, next) => {
res.status(500).json({ error: err.stack }); // Leaks implementation details
});
“`
Good:
“`javascript
app.use((err, req, res, next) => {
console.error(err.stack); // Log internally
res.status(500).json({ error: ‘Internal server error' }); // Generic message
});
“`
Conclusion
Security is not optional. When using AI to generate code, you must be extra vigilant. The AI doesn't understand the security implications of its suggestions—you do.
At BYS Marketing, we have a dedicated security review process for all AI-generated code. We use automated tools and manual reviews to ensure nothing slips through.
—
Need a security audit?
Contact BYS Marketing. We'll review your codebase and fix vulnerabilities.
🚀 Elevate Your Business with BYS Marketing
From AI Coding to Media Production, we deliver excellence.
Contact Us: Get a Quote Today