epic-security
Guide on security practices including CSP, rate limiting, and session security for Epic Stack
Install
mkdir -p .claude/skills/epic-security && curl -L -o skill.zip "https://mcp.directory/api/skills/download/2294" && unzip -o skill.zip -d .claude/skills/epic-security && rm skill.zipInstalls to .claude/skills/epic-security
About this skill
Epic Stack: Security
When to use this skill
Use this skill when you need to:
- Configure Content Security Policy (CSP)
- Implement spam protection (honeypot)
- Configure rate limiting
- Manage session security
- Implement input validation
- Configure secure headers
- Manage secrets
Patterns and conventions
Security Philosophy
Following Epic Web principles:
Design to fail fast and early - Validate security constraints as early as possible. Check authentication, authorization, and input validation before processing requests. Fail immediately with clear error messages rather than allowing potentially malicious data to flow through the system.
Optimize for the debugging experience - When security checks fail, provide clear, actionable error messages that help developers understand what went wrong. Log security events with enough context to debug issues without exposing sensitive information.
Example - Fail fast validation:
// ✅ Good - Validate security constraints early
export async function action({ request }: Route.ActionArgs) {
// 1. Authenticate immediately - fail fast if not authenticated
const userId = await requireUserId(request)
// 2. Validate input early - fail fast if invalid
const formData = await request.formData()
const submission = await parseWithZod(formData, {
schema: NoteSchema,
})
if (submission.status !== 'success') {
return data({ result: submission.reply() }, { status: 400 })
}
// 3. Check permissions early - fail fast if unauthorized
await requireUserWithPermission(request, 'create:note:own')
// Only proceed if all security checks pass
const { title, content } = submission.value
// ... create note
}
// ❌ Avoid - Security checks scattered or delayed
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData()
// ... process data first
// Security check at the end - too late!
const userId = await getUserId(request)
if (!userId) {
// Already processed potentially malicious data
return json({ error: 'Unauthorized' }, { status: 401 })
}
}
Example - Debugging-friendly error messages:
// ✅ Good - Clear error messages for debugging
export async function checkHoneypot(formData: FormData) {
try {
await honeypot.check(formData)
} catch (error) {
if (error instanceof SpamError) {
// Log with context for debugging
console.error('Honeypot triggered', {
timestamp: new Date().toISOString(),
userAgent: formData.get('user-agent'),
// Don't log sensitive data
})
throw new Response('Form not submitted properly', { status: 400 })
}
throw error
}
}
// ❌ Avoid - Generic or unhelpful errors
export async function checkHoneypot(formData: FormData) {
try {
await honeypot.check(formData)
} catch (error) {
// No context, hard to debug
throw new Response('Error', { status: 400 })
}
}
Content Security Policy (CSP)
Epic Stack uses CSP to prevent XSS and other attacks.
Configuration in server/index.ts:
import { helmet } from '@nichtsam/helmet/node-http'
app.use((_, res, next) => {
helmet(res, { general: { referrerPolicy: false } })
next()
})
Note: By default, CSP is in report-only mode to avoid blocking resources
during development. In production, remove reportOnly: true to enable it fully.
Honeypot Fields
Epic Stack uses honeypot fields to protect against spam bots.
En formularios públicos:
import { HoneypotInputs } from 'remix-utils/honeypot/react'
<Form method="POST" {...getFormProps(form)}>
<HoneypotInputs /> {/* Always include in public forms */}
{/* Resto de campos */}
</Form>
En el action (fail fast):
import { checkHoneypot } from '#app/utils/honeypot.server.ts'
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData()
// Check honeypot first - fail fast if spam detected
await checkHoneypot(formData) // Lanza error si es spam
// Only proceed if honeypot check passes
// ... resto del código
}
Configuration:
// app/utils/honeypot.server.ts
import { Honeypot, SpamError } from 'remix-utils/honeypot/server'
export const honeypot = new Honeypot({
validFromFieldName: process.env.NODE_ENV === 'test' ? null : undefined,
encryptionSeed: process.env.HONEYPOT_SECRET,
})
export async function checkHoneypot(formData: FormData) {
try {
await honeypot.check(formData)
} catch (error) {
if (error instanceof SpamError) {
// Log for debugging (without sensitive data)
console.error('Honeypot triggered', {
timestamp: new Date().toISOString(),
})
throw new Response('Form not submitted properly', { status: 400 })
}
throw error
}
}
Rate Limiting
Epic Stack uses express-rate-limit para prevenir abuso.
Basic configuration:
// server/index.ts
import rateLimit from 'express-rate-limit'
const rateLimitDefault = {
windowMs: 60 * 1000, // 1 minute
limit: 1000, // 1000 requests per minute
standardHeaders: true,
legacyHeaders: false,
validate: { trustProxy: false },
keyGenerator: (req: express.Request) => {
return req.get('fly-client-ip') ?? `${req.ip}`
},
}
const generalRateLimit = rateLimit(rateLimitDefault)
Different levels of rate limiting:
// Stricter rate limit for sensitive routes
const strongestRateLimit = rateLimit({
...rateLimitDefault,
limit: 10, // Only 10 requests per minute
})
// Strong rate limit for important actions
const strongRateLimit = rateLimit({
...rateLimitDefault,
limit: 100, // 100 requests per minute
})
Apply to specific routes:
app.use((req, res, next) => {
const strongPaths = [
'/login',
'/signup',
'/verify',
'/admin',
'/reset-password',
]
if (req.method !== 'GET' && req.method !== 'HEAD') {
if (strongPaths.some((p) => req.path.includes(p))) {
return strongestRateLimit(req, res, next)
}
return strongRateLimit(req, res, next)
}
return generalRateLimit(req, res, next)
})
Note: In tests and development, rate limiting is effectively disabled to allow fast tests.
Session Security
Secure session configuration:
// app/utils/session.server.ts
export const authSessionStorage = createCookieSessionStorage({
cookie: {
name: 'en_session',
sameSite: 'lax', // CSRF protection advised if changing to 'none'
path: '/',
httpOnly: true, // Prevents access from JavaScript
secrets: process.env.SESSION_SECRET.split(','), // Secret rotation
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
},
})
Security features:
httpOnly: true- Prevents access from JavaScript (XSS protection)secure: true- Only sends cookies over HTTPS in productionsameSite: 'lax'- CSRF protection- Secret rotation using array
Password Security
Hashing de passwords:
import bcrypt from 'bcryptjs'
export async function getPasswordHash(password: string) {
const hash = await bcrypt.hash(password, 10) // 10 rounds
return hash
}
export async function verifyUserPassword(
where: Pick<User, 'username'> | Pick<User, 'id'>,
password: string,
) {
const userWithPassword = await prisma.user.findUnique({
where,
select: { id: true, password: { select: { hash: true } } },
})
if (!userWithPassword || !userWithPassword.password) {
return null
}
const isValid = await bcrypt.compare(password, userWithPassword.password.hash)
return isValid ? { id: userWithPassword.id } : null
}
Check common passwords (Have I Been Pwned):
import { checkIsCommonPassword } from '#app/utils/auth.server.ts'
const isCommonPassword = await checkIsCommonPassword(password)
if (isCommonPassword) {
ctx.addIssue({
path: ['password'],
code: 'custom',
message: 'Password is too common',
})
}
Input Validation y Sanitization
Always validate inputs with Zod:
import { z } from 'zod'
const UserSchema = z.object({
email: z
.string()
.email()
.min(3)
.max(100)
.transform((val) => val.toLowerCase()),
username: z
.string()
.min(3)
.max(20)
.regex(/^[a-zA-Z0-9_]+$/),
password: z.string().min(6).max(72), // bcrypt limit
})
// Validate before using
const result = UserSchema.safeParse(data)
if (!result.success) {
return json({ errors: result.error.flatten() }, { status: 400 })
}
Sanitization:
- Use
.transform()from Zod to sanitize data - Normalize emails to lowercase
- Normalize usernames to lowercase
- Clean whitespace
XSS Prevention
React prevents XSS automatically by escaping all values.
Never use dangerouslySetInnerHTML with user data:
// ❌ NEVER do this with user data
<div dangerouslySetInnerHTML={{ __html: userContent }} />
// ✅ React escapa automáticamente
<div>{userContent}</div>
Secure Headers
Epic Stack uses Helmet for secure headers.
Configuration:
import { helmet } from '@nichtsam/helmet/node-http'
app.use((_, res, next) => {
helmet(res, { general: { referrerPolicy: false } })
next()
})
Included headers:
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- X-XSS-Protection: 1; mode=block
- Referrer-Policy (configurable)
HTTPS Only
Redirect HTTP to HTTPS:
app.use((req, res, next) => {
if (req.method !== 'GET') return next()
const proto = req.get('X-Forwarded-Proto')
const host = getHost(req)
if (proto === 'http') {
res.set('X-Forwarded-Proto', 'https')
res.redirect(`https://${host}${req.originalUrl}`)
return
}
next()
})
Secrets Management
Variables de entorno:
# .env
SESSION_SECRET=secret1,secret2,secret3 # Secret rotation
HONEYPOT_SECRET=your-honeypot-secret
DATABASE_URL=file:./data/db.sqlite
En Fly.io:
fly secrets set SESSION_SECRET="secret1,secret2,secret3"
fly secrets set HONEYPOT_SECRET="your-secret"
**Never commit
Content truncated.
More by epicweb-dev
View all skills by epicweb-dev →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
pdf-to-markdown
aliceisjustplaying
Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.
Related MCP Servers
Browse all serversSupercharge AI platforms with Azure MCP Server for seamless Azure API Management and resource automation. Public Preview
Use our random number generator to get a random number, shuffle lists, or generate secure tokens with advanced rng gener
Get expert React Native software guidance with tools for component analysis, performance, debugging, and migration betwe
Access 50+ secure IT tools for developers, with features like bill pay for National Grid, Con Edison, and National Fuel,
Spec-Driven Development integrates with IBM DOORS software to track software licenses, automate requirements, and enforc
SuperAgent is artificial intelligence development software that orchestrates AI agents for efficient, parallel software
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.