security-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Patterns

安全模式

Comprehensive security patterns for building hardened applications. Each category has individual rule files in
rules/
loaded on-demand.
用于构建高安全性应用的全面安全模式。每个分类在
rules/
目录下都有独立的规则文件,可按需加载。

Quick Reference

快速参考

CategoryRulesImpactWhen to Use
Authentication3CRITICALJWT tokens, OAuth 2.1/PKCE, RBAC/permissions
Defense-in-Depth2CRITICALMulti-layer security, zero-trust architecture
Input Validation3HIGHSchema validation (Zod/Pydantic), output encoding, file uploads
OWASP Top 102CRITICALInjection prevention, broken authentication fixes
LLM Safety3HIGHPrompt injection defense, output guardrails, content filtering
PII Masking2HIGHPII detection/redaction with Presidio, Langfuse, LLM Guard
Scanning3HIGHDependency audit, SAST (Semgrep/Bandit), secret detection
Advanced Guardrails2CRITICALNeMo/Guardrails AI validators, red-teaming, OWASP LLM
Total: 20 rules across 8 categories
分类规则数量影响级别使用场景
身份认证3关键JWT令牌、OAuth 2.1/PKCE、RBAC/权限管理
深度防御2关键多层安全架构、零信任架构
输入验证3Schema验证(Zod/Pydantic)、输出编码、文件上传
OWASP Top 102关键注入攻击预防、身份认证漏洞修复
LLM安全3提示注入防御、输出管控、内容过滤
PII掩码2结合Presidio、Langfuse、LLM Guard的PII检测/脱敏
扫描检测3依赖审计、SAST(Semgrep/Bandit)、密钥检测
高级管控2关键NeMo/Guardrails AI验证器、红队测试、OWASP LLM合规
总计:8个分类共20条规则

Quick Start

快速开始

python
undefined
python
undefined

Argon2id password hashing

Argon2id密码哈希

from argon2 import PasswordHasher ph = PasswordHasher() password_hash = ph.hash(password) ph.verify(password_hash, password)

```python
from argon2 import PasswordHasher ph = PasswordHasher() password_hash = ph.hash(password) ph.verify(password_hash, password)

```python

JWT access token (15-min expiry)

JWT访问令牌(15分钟过期)

import jwt from datetime import datetime, timedelta, timezone payload = { 'sub': user_id, 'type': 'access', 'exp': datetime.now(timezone.utc) + timedelta(minutes=15), } token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

```typescript
// Zod v4 schema validation
import { z } from 'zod';
const UserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  role: z.enum(['user', 'admin']).default('user'),
});
const result = UserSchema.safeParse(req.body);
python
undefined
import jwt from datetime import datetime, timedelta, timezone payload = { 'sub': user_id, 'type': 'access', 'exp': datetime.now(timezone.utc) + timedelta(minutes=15), } token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

```typescript
// Zod v4 Schema验证
import { z } from 'zod';
const UserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  role: z.enum(['user', 'admin']).default('user'),
});
const result = UserSchema.safeParse(req.body);
python
undefined

PII masking with Langfuse

结合Langfuse的PII掩码

import re from langfuse import Langfuse
def mask_pii(data, **kwargs): if isinstance(data, str): data = re.sub(r'\b[\w.-]+@[\w.-]+.\w+\b', '[REDACTED_EMAIL]', data) data = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[REDACTED_SSN]', data) return data
langfuse = Langfuse(mask=mask_pii)
undefined
import re from langfuse import Langfuse
def mask_pii(data, **kwargs): if isinstance(data, str): data = re.sub(r'\b[\w.-]+@[\w.-]+.\w+\b', '[REDACTED_EMAIL]', data) data = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[REDACTED_SSN]', data) return data
langfuse = Langfuse(mask=mask_pii)
undefined

Authentication

身份认证

Secure authentication with OAuth 2.1, Passkeys/WebAuthn, JWT tokens, and role-based access control.
RuleDescription
auth-jwt.md
JWT creation, verification, expiry, refresh token rotation
auth-oauth.md
OAuth 2.1 with PKCE, DPoP, Passkeys/WebAuthn
auth-rbac.md
Role-based access control, permission decorators, MFA
Key Decisions: Argon2id > bcrypt | Access tokens 15 min | PKCE required | Passkeys > TOTP > SMS
采用OAuth 2.1、Passkeys/WebAuthn、JWT令牌及基于角色的访问控制实现安全身份认证。
规则描述
auth-jwt.md
JWT创建、验证、过期处理、刷新令牌轮转
auth-oauth.md
结合PKCE、DPoP、Passkeys/WebAuthn的OAuth 2.1
auth-rbac.md
基于角色的访问控制、权限装饰器、多因素认证(MFA)
核心决策: Argon2id > bcrypt | 访问令牌有效期15分钟 | 强制要求PKCE | Passkeys > TOTP > 短信验证

Defense-in-Depth

深度防御

Multi-layer security architecture with no single point of failure.
RuleDescription
defense-layers.md
8-layer security architecture (edge to observability)
defense-zero-trust.md
Immutable request context, tenant isolation, audit logging
Key Decisions: Immutable dataclass context | Query-level tenant filtering | No IDs in LLM prompts
无单点故障的多层安全架构。
规则描述
defense-layers.md
8层安全架构(从边缘到可观测性)
defense-zero-trust.md
不可变请求上下文、租户隔离、审计日志
核心决策: 不可变数据类上下文 | 查询级租户过滤 | LLM提示中不包含ID

Input Validation

输入验证

Validate and sanitize all untrusted input using Zod v4 and Pydantic.
RuleDescription
validation-input.md
Schema validation with Zod v4 and Pydantic, type coercion
validation-output.md
HTML sanitization, output encoding, XSS prevention
validation-schemas.md
Discriminated unions, file upload validation, URL allowlists
Key Decisions: Allowlist over blocklist | Server-side always | Validate magic bytes not extensions
使用Zod v4和Pydantic验证并清理所有不可信输入。
规则描述
validation-input.md
采用Zod v4和Pydantic的Schema验证、类型转换
validation-output.md
HTML清理、输出编码、XSS预防
validation-schemas.md
可区分联合类型、文件上传验证、URL白名单
核心决策: 优先使用白名单而非黑名单 | 始终在服务端验证 | 验证魔术字节而非文件扩展名

OWASP Top 10

OWASP Top 10

Protection against the most critical web application security risks.
RuleDescription
owasp-injection.md
SQL/command injection, parameterized queries, SSRF prevention
owasp-broken-auth.md
JWT algorithm confusion, CSRF protection, timing attacks
Key Decisions: Parameterized queries only | Hardcode JWT algorithm | SameSite=Strict cookies
针对最关键的Web应用安全风险的防护措施。
规则描述
owasp-injection.md
SQL/命令注入预防、参数化查询、SSRF防护
owasp-broken-auth.md
JWT算法混淆防护、CSRF防护、时序攻击防护
核心决策: 仅使用参数化查询 | 硬编码JWT算法 | SameSite=Strict Cookie

LLM Safety

LLM安全

Security patterns for LLM integrations including context separation and output validation.
RuleDescription
llm-prompt-injection.md
Context separation, prompt auditing, forbidden patterns
llm-guardrails.md
Output validation pipeline: schema, grounding, safety, size
llm-content-filtering.md
Pre-LLM filtering, post-LLM attribution, three-phase pattern
Key Decisions: IDs flow around LLM, never through | Attribution is deterministic | Audit every prompt
适用于LLM集成的安全模式,包括上下文分离和输出验证。
规则描述
llm-prompt-injection.md
上下文分离、提示审计、禁用模式
llm-guardrails.md
输出验证流水线:Schema、事实依据、安全、大小
llm-content-filtering.md
LLM前过滤、LLM后归因、三阶段模式
核心决策: ID绕开LLM传递,而非通过LLM | 归因具有确定性 | 审计所有提示

PII Masking

PII掩码

PII detection and masking for LLM observability pipelines and logging.
RuleDescription
pii-detection.md
Microsoft Presidio, regex patterns, LLM Guard Anonymize
pii-redaction.md
Langfuse mask callback, structlog/loguru processors, Vault deanonymization
Key Decisions: Presidio for enterprise | Replace with type tokens | Use mask callback at init
针对LLM可观测性流水线和日志的PII检测与掩码处理。
规则描述
pii-detection.md
Microsoft Presidio、正则表达式模式、LLM Guard匿名化
pii-redaction.md
Langfuse掩码回调、structlog/loguru处理器、Vault去匿名化
核心决策: 企业级场景使用Presidio | 用类型令牌替换敏感数据 | 初始化时使用掩码回调

Scanning

扫描检测

Automated security scanning for dependencies, code, and secrets.
RuleDescription
scanning-dependency.md
npm audit, pip-audit, Trivy container scanning, CI gating
scanning-sast.md
Semgrep and Bandit static analysis, custom rules, pre-commit
scanning-secrets.md
Gitleaks, TruffleHog, detect-secrets with baseline management
Key Decisions: Pre-commit hooks for shift-left | Block on critical/high | Gitleaks + detect-secrets baseline
针对依赖、代码和密钥的自动化安全扫描。
规则描述
scanning-dependency.md
npm audit、pip-audit、Trivy容器扫描、CI门禁
scanning-sast.md
Semgrep和Bandit静态分析、自定义规则、提交前检查
scanning-secrets.md
Gitleaks、TruffleHog、detect-secrets及基线管理
核心决策: 左移至提交前钩子 | 阻断关键/高危漏洞 | Gitleaks + detect-secrets基线

Advanced Guardrails

高级管控

Production LLM safety with NeMo Guardrails, Guardrails AI validators, and DeepTeam red-teaming.
RuleDescription
guardrails-nemo.md
NeMo Guardrails, Colang 2.0 flows, Guardrails AI validators, layered validation
guardrails-llm-validation.md
DeepTeam red-teaming (40+ vulnerabilities), OWASP LLM Top 10 compliance
Key Decisions: NeMo for flows, Guardrails AI for validators | Toxicity 0.5 threshold | Red-team pre-release + quarterly
采用NeMo Guardrails、Guardrails AI验证器和DeepTeam红队测试的生产级LLM安全措施。
规则描述
guardrails-nemo.md
NeMo Guardrails、Colang 2.0流程、Guardrails AI验证器、分层验证
guardrails-llm-validation.md
DeepTeam红队测试(40+漏洞)、OWASP LLM Top 10合规
核心决策: NeMo用于流程,Guardrails AI用于验证器 | 毒性阈值0.5 | 发布前及每季度进行红队测试

Anti-Patterns (FORBIDDEN)

反模式(禁止使用)

python
undefined
python
undefined

Authentication

身份认证

user.password = request.form['password'] # Plaintext password storage response_type=token # Implicit OAuth grant (deprecated) return "Email not found" # Information disclosure
user.password = request.form['password'] # 明文存储密码 response_type=token # 隐式OAuth授权(已弃用) return "Email not found" # 信息泄露

Input Validation

输入验证

"SELECT * FROM users WHERE name = '" + name + "'" # SQL injection if (file.type === 'image/png') {...} # Trusting Content-Type header
"SELECT * FROM users WHERE name = '" + name + "'" # SQL注入 if (file.type === 'image/png') {...} # 信任Content-Type头

LLM Safety

LLM安全

prompt = f"Analyze for user {user_id}" # ID in prompt artifact.user_id = llm_output["user_id"] # Trusting LLM-generated IDs
prompt = f"Analyze for user {user_id}" # 提示中包含ID artifact.user_id = llm_output["user_id"] # 信任LLM生成的ID

PII

PII

logger.info(f"User email: {user.email}") # Raw PII in logs langfuse.trace(input=raw_prompt) # Unmasked observability data
undefined
logger.info(f"User email: {user.email}") # 日志中包含原始PII langfuse.trace(input=raw_prompt) # 未掩码的可观测性数据
undefined

Detailed Documentation

详细文档

ResourceDescription
references/oauth-2.1-passkeys.mdOAuth 2.1, PKCE, DPoP, Passkeys/WebAuthn
references/request-context-pattern.mdImmutable request context for identity flow
references/tenant-isolation.mdTenant-scoped repository, vector/full-text search
references/audit-logging.mdSanitized structured logging, compliance
references/zod-v4-api.mdZod v4 types, coercion, transforms, refinements
references/vulnerability-demos.mdOWASP vulnerable vs secure code examples
references/context-separation.mdLLM context separation architecture
references/output-guardrails.mdOutput validation pipeline implementation
references/pre-llm-filtering.mdTenant-scoped retrieval, content extraction
references/post-llm-attribution.mdDeterministic attribution pattern
references/prompt-audit.mdPrompt audit patterns, safe prompt builder
references/presidio-integration.mdMicrosoft Presidio setup, custom recognizers
references/langfuse-mask-callback.mdLangfuse SDK mask implementation
references/llm-guard-sanitization.mdLLM Guard Anonymize/Deanonymize with Vault
references/logging-redaction.mdstructlog/loguru pre-logging redaction
资源描述
references/oauth-2.1-passkeys.mdOAuth 2.1、PKCE、DPoP、Passkeys/WebAuthn
references/request-context-pattern.md用于身份流转的不可变请求上下文
references/tenant-isolation.md租户范围的存储库、向量/全文搜索
references/audit-logging.md已清理的结构化日志、合规性
references/zod-v4-api.mdZod v4类型、转换、变换、细化
references/vulnerability-demos.mdOWASP漏洞与安全代码示例对比
references/context-separation.mdLLM上下文分离架构
references/output-guardrails.md输出验证流水线实现
references/pre-llm-filtering.md租户范围的检索、内容提取
references/post-llm-attribution.md确定性归因模式
references/prompt-audit.md提示审计模式、安全提示构建器
references/presidio-integration.mdMicrosoft Presidio设置、自定义识别器
references/langfuse-mask-callback.mdLangfuse SDK掩码实现
references/llm-guard-sanitization.md结合Vault的LLM Guard匿名化/去匿名化
references/logging-redaction.mdstructlog/loguru日志前脱敏

Related Skills

相关技能

  • api-design-framework
    - API security patterns
  • rag-retrieval
    - RAG pipeline patterns requiring tenant-scoped retrieval
  • llm-evaluation
    - Output quality assessment including hallucination detection
  • api-design-framework
    - API安全模式
  • rag-retrieval
    - 需租户范围检索的RAG流水线模式
  • llm-evaluation
    - 输出质量评估,包括幻觉检测

Capability Details

能力详情

authentication

authentication

Keywords: password, hashing, JWT, token, OAuth, PKCE, passkey, WebAuthn, RBAC, session Solves:
  • Implement secure authentication with modern standards
  • JWT token management with proper expiry
  • OAuth 2.1 with PKCE flow
  • Passkeys/WebAuthn registration and login
  • Role-based access control
关键词: password, hashing, JWT, token, OAuth, PKCE, passkey, WebAuthn, RBAC, session 解决问题:
  • 采用现代标准实现安全身份认证
  • 带合理过期时间的JWT令牌管理
  • 结合PKCE的OAuth 2.1流程
  • Passkeys/WebAuthn注册与登录
  • 基于角色的访问控制

defense-in-depth

defense-in-depth

Keywords: defense in depth, security layers, multi-layer, request context, tenant isolation Solves:
  • How to secure AI applications end-to-end
  • Implement 8-layer security architecture
  • Create immutable request context
  • Ensure tenant isolation at query level
关键词: defense in depth, security layers, multi-layer, request context, tenant isolation 解决问题:
  • 如何端到端保护AI应用
  • 实现8层安全架构
  • 创建不可变请求上下文
  • 在查询级确保租户隔离

input-validation

input-validation

Keywords: schema, validate, Zod, Pydantic, sanitize, HTML, XSS, file upload Solves:
  • Validate input against schemas (Zod v4, Pydantic)
  • Prevent injection attacks with allowlists
  • Sanitize HTML and prevent XSS
  • Validate file uploads by magic bytes
关键词: schema, validate, Zod, Pydantic, sanitize, HTML, XSS, file upload 解决问题:
  • 基于Schema验证输入(Zod v4、Pydantic)
  • 用白名单预防注入攻击
  • 清理HTML并预防XSS
  • 通过魔术字节验证文件上传

owasp-top-10

owasp-top-10

Keywords: OWASP, sql injection, broken access control, CSRF, XSS, SSRF Solves:
  • Fix OWASP Top 10 vulnerabilities
  • Prevent SQL and command injection
  • Implement CSRF protection
  • Fix broken authentication
关键词: OWASP, sql injection, broken access control, CSRF, XSS, SSRF 解决问题:
  • 修复OWASP Top 10漏洞
  • 预防SQL和命令注入
  • 实现CSRF防护
  • 修复身份认证漏洞

llm-safety

llm-safety

Keywords: prompt injection, context separation, guardrails, hallucination, LLM output Solves:
  • Prevent prompt injection attacks
  • Implement context separation (IDs around LLM)
  • Validate LLM output with guardrail pipeline
  • Deterministic post-LLM attribution
关键词: prompt injection, context separation, guardrails, hallucination, LLM output 解决问题:
  • 预防提示注入攻击
  • 实现上下文分离(ID绕开LLM)
  • 用管控流水线验证LLM输出
  • 确定性LLM后归因

pii-masking

pii-masking

Keywords: PII, masking, Presidio, Langfuse, redact, GDPR, privacy Solves:
  • Detect and mask PII in LLM pipelines
  • Integrate masking with Langfuse observability
  • Implement pre-logging redaction
  • GDPR-compliant data handling
关键词: PII, masking, Presidio, Langfuse, redact, GDPR, privacy 解决问题:
  • 在LLM流水线中检测并掩码PII
  • 将掩码与Langfuse可观测性集成
  • 实现日志前脱敏
  • GDPR合规的数据处理