Epic Security 标志

Epic Security

组织热门
epicweb-dev
epic-security

Epic Stack 安全实践指南,包括 CSP、速率限制和会话安全

Add to TypingMind

概览

发布者epicweb-dev
代码仓库epic-stack
技能名称epic-security
星标数
5.5K
复刻数
461
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 epicweb-dev 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Epic Security AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/epicweb-dev/epic-stack/tree/main/docs/skills/epic-security
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/epicweb-dev/epic-stack.git /tmp/epic-stack
mkdir -p .claude/skills
cp -r /tmp/epic-stack/docs/skills/epic-security .claude/skills/epic-security
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Epic Security,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Epic Security。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Epic Security 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

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:

typescript
// ✅ 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:

typescript
// ✅ 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:

typescript
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:

typescript
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):

typescript
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:

typescript
// 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:

typescript
// 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:

typescript
// 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:

typescript
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:

typescript
// 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 production
  • sameSite: 'lax' - CSRF protection
  • Secret rotation using array

Password Security

Hashing de passwords:

typescript
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):

typescript
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:

typescript
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:

typescript
// ❌ 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:

typescript
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:

typescript
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:

bash
# .env
SESSION_SECRET=secret1,secret2,secret3 # Secret rotation
HONEYPOT_SECRET=your-honeypot-secret
DATABASE_URL=file:./data/db.sqlite

En Fly.io:

bash
fly secrets set SESSION_SECRET="secret1,secret2,secret3"
fly secrets set HONEYPOT_SECRET="your-secret"

Never commit secrets:

  • Use .env.example to document required variables
  • .env is in .gitignore
  • Use fly secrets for production

Validación de Session Expiration (Fail Fast)

Always verify expiration early:

typescript
export async function getUserId(request: Request) {
	const authSession = await authSessionStorage.getSession(
		request.headers.get('cookie'),
	)
	const sessionId = authSession.get(sessionKey)

	// Fail fast - return null immediately if no session
	if (!sessionId) return null

	// Verify expiration early - fail fast if expired
	const session = await prisma.session.findUnique({
		select: { userId: true },
		where: {
			id: sessionId,
			expirationDate: { gt: new Date() }, // Verify expiration
		},
	})

	// Fail fast - destroy invalid session immediately
	if (!session?.userId) {
		throw redirect('/', {
			headers: {
				'set-cookie': await authSessionStorage.destroySession(authSession),
			},
		})
	}
	return session.userId
}

Common examples

Example 1: Public form with honeypot

typescript
// app/routes/_auth/signup.tsx
import { HoneypotInputs } from 'remix-utils/honeypot/react'
import { checkHoneypot } from '#app/utils/honeypot.server.ts'

export async function action({ request }: Route.ActionArgs) {
	const formData = await request.formData()

	await checkHoneypot(formData) // Spam protection

	const submission = await parseWithZod(formData, {
		schema: SignupSchema,
	})

	// ... rest of code
}

export default function SignupRoute({ actionData }: Route.ComponentProps) {
	return (
		<Form method="POST" {...getFormProps(form)}>
			<HoneypotInputs /> {/* Include in form */}
			{/* Rest of fields */}
		</Form>
	)
}

Example 2: Custom rate limiting

typescript
// server/index.ts
const apiRateLimit = rateLimit({
	...rateLimitDefault,
	windowMs: 60 * 1000,
	limit: 100, // 100 requests per minute for API
	keyGenerator: (req) => {
		const apiKey = req.get('X-API-Key')
		return apiKey ?? req.get('fly-client-ip') ?? req.ip
	},
})

app.use('/api', apiRateLimit)

Example 3: Strict input validation

typescript
// app/utils/user-validation.ts
import { z } from 'zod'

export const EmailSchema = z
	.string({ required_error: 'Email is required' })
	.email({ message: 'Email is invalid' })
	.min(3, { message: 'Email is too short' })
	.max(100, { message: 'Email is too long' })
	.transform((value) => value.toLowerCase().trim()) // Sanitization

export const UsernameSchema = z
	.string({ required_error: 'Username is required' })
	.min(3, { message: 'Username is too short' })
	.max(20, { message: 'Username is too long' })
	.regex(/^[a-zA-Z0-9_]+$/, {
		message: 'Username can only include letters, numbers, and underscores',
	})
	.transform((value) => value.toLowerCase().trim()) // Sanitization

export const PasswordSchema = z
	.string({ required_error: 'Password is required' })
	.min(6, { message: 'Password is too short' })
	.refine((val) => new TextEncoder().encode(val).length <= 72, {
		message: 'Password is too long', // bcrypt limit
	})

Example 4: Permission verification before actions

typescript
export async function action({ request }: Route.ActionArgs) {
	const userId = await requireUserId(request)

	// Validate that user has permission
	await requireUserWithPermission(request, 'delete:note:own')

	// Only after validating permissions
	await prisma.note.delete({ where: { id: noteId } })

	return redirect('/notes')
}

Common mistakes to avoid

  • ❌ Delayed security checks: Validate authentication, authorization, and input as early as possible - fail fast
  • ❌ Generic error messages: Provide clear, actionable error messages that help with debugging (without exposing sensitive data)
  • ❌ Forgetting honeypot in public forms: Always include HoneypotInputs in forms accessible without authentication
  • ❌ Not validating session expiration: Always verify expirationDate when getting sessions - check early
  • ❌ Using dangerouslySetInnerHTML with user data: Never render user HTML without sanitizing
  • ❌ Not using rate limiting: Protect sensitive routes with rate limiting
  • ❌ Secrets in code: Never hardcode secrets, use environment variables
  • ❌ Not sanitizing inputs: Always sanitize inputs with .transform() from Zod
  • ❌ Not validating common passwords: Check passwords against Have I Been Pwned
  • ❌ Sessions without httpOnly: Always use httpOnly: true in session cookies
  • ❌ Not using HTTPS in production: Make sure to redirect HTTP to HTTPS
  • ❌ CSP too permissive: Review and adjust CSP according to your needs
  • ❌ Not logging security events: Log security failures with context for debugging (without sensitive data)

References

常见问题

Epic Security AI 技能有什么作用?

Epic Stack 安全实践指南,包括 CSP、速率限制和会话安全

为什么在 TypingMind 中使用 Epic Security?

因为您只需安装一次,就能搭配任何模型使用。Epic Security 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Epic Security?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/epicweb-dev/epic-stack/tree/main/docs/skills/epic-security。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Epic Security?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Epic Security 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Epic Security 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Epic Security AI 技能免费吗?

是的。epicweb-dev 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇