Token导航 LogoToken导航

Agent Skill · 研究检索

vibe-security(氛围安全)

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

vibe-security 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 43,099。

总安装 1,011周安装 43GitHub Stars 15下载 354核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:vibe-security(氛围安全)
来源仓库:https://github.com/nickcrew/claude-ctx-plugin
仓库路径:skills/vibe-security
安装命令:
npx skills add https://github.com/nickcrew/claude-ctx-plugin --skill vibe-security
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/nickcrew/claude-ctx-plugin --skill vibe-security

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于辅助安全审计、权限检查、凭据风险和认证流程排查。适合梳理敏感配置、分析鉴权逻辑或生成安全复核清单。使用时不能将工具输出直接当作最终结论。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。涉及密钥、令牌或生产系统时,应先确认最小权限和操作边界。

vibe-security 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/vibe-security

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/nickcrew/claude-ctx-plugin --skill vibe-securi…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

vibe-security 怎么安装?

在终端执行 npx skills add https://github.com/nickcrew/claude-ctx-plugin --skill vibe-security。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

vibe-security 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

vibe-security 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

vibe-security 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

vibe-security 用的人多吗?

公开数据是累计安装 1,011 次,近一周安装 43 次,下载 354 次,GitHub 15 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

vibe-security 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
vibe-security

氛围安全 · 本页

1,01115接触敏感数据未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Secure Coding Guide for Web Applications

Comprehensive secure coding practices for web applications. Approach code from a bug hunter's perspective and make applications as secure as possible without breaking functionality.

When to Use This Skill

  • Writing new web application endpoints or API routes
  • Reviewing PRs that handle user input, authentication, or file uploads
  • Implementing authentication, authorization, or session management
  • Working with file uploads, redirects, or URL-based features
  • Adding security headers or CSP policies
  • Avoid using for infrastructure/network security — use defense-in-depth instead

Workflow

Step 1: Identify Attack Surface

Determine which security domains apply to the code under review:

DomainTrigger
Access ControlAny authenticated endpoint, multi-tenant data
XSSUser input rendered in HTML, JavaScript, or CSS
CSRFState-changing endpoints (POST, PUT, DELETE)
SSRFServer makes requests to user-provided URLs
SQL InjectionDynamic database queries
File UploadAny file upload functionality
Path TraversalUser input in file paths

Step 2: Apply Domain-Specific Checks

Use the relevant sections below as checklists for each identified domain.

Step 3: Verify Security Headers

Ensure all responses include the required headers (see Security Headers Checklist).

Step 4: Review and Test

  • Verify fixes don't break functionality
  • Test with bypass techniques listed in each section
  • Run automated security scanning if available

Key Principles:

  • Defense in depth: Never rely on a single security control
  • Fail securely: When something fails, fail closed (deny access)
  • Least privilege: Grant minimum permissions necessary
  • Input validation: Never trust user input, validate everything server-side
  • Output encoding: Encode data appropriately for the context it's rendered in

Access Control Issues

Access control vulnerabilities occur when users can access resources or perform actions beyond their intended permissions.

Core Requirements

For every data point and action that requires authentication:

  1. User-Level Authorization

- Each user must only access/modify their own data - No user should access data from other users or organizations - Always verify ownership at the data layer, not just the route level

  1. Use UUIDs Instead of Sequential IDs

- Use UUIDv4 or similar non-guessable identifiers - Exception: Only use sequential IDs if explicitly requested by user

  1. Account Lifecycle Handling

- When a user is removed from an organization: immediately revoke all access tokens and sessions - When an account is deleted/deactivated: invalidate all active sessions and API keys - Implement token revocation lists or short-lived tokens with refresh mechanisms

Authorization Checks Checklist

  • Verify user owns the resource on every request (don't trust client-side data)
  • Check organization membership for multi-tenant apps
  • Validate role permissions for role-based actions
  • Re-validate permissions after any privilege change
  • Check parent resource ownership (e.g., if accessing a comment, verify user owns the parent post)

Common Pitfalls to Avoid

  • IDOR (Insecure Direct Object Reference): Always verify the requesting user has permission to access the requested resource ID
  • Privilege Escalation: Validate role changes server-side; never trust role info from client
  • Horizontal Access: User A accessing User B's resources with the same privilege level
  • Vertical Access: Regular user accessing admin functionality
  • Mass Assignment: Filter which fields users can update; don't blindly accept all request body fields

Implementation Pattern

# Pseudocode for secure resource access
function getResource(resourceId, currentUser):
    resource = database.find(resourceId)

    if resource is null:
        return 404  # Don't reveal if resource exists

    if resource.ownerId != currentUser.id:
        if not currentUser.hasOrgAccess(resource.orgId):
            return 404  # Return 404, not 403, to prevent enumeration

    return resource

Client-Side Bugs

Cross-Site Scripting (XSS)

Every input controllable by the user—whether directly or indirectly—must be sanitized against XSS.

Input Sources to Protect

Direct Inputs:

  • Form fields (email, name, bio, comments, etc.)
  • Search queries
  • File names during upload
  • Rich text editors / WYSIWYG content

Indirect Inputs:

  • URL parameters and query strings
  • URL fragments (hash values)
  • HTTP headers used in the application (Referer, User-Agent if displayed)
  • Data from third-party APIs displayed to users
  • WebSocket messages
  • postMessage data from iframes
  • LocalStorage/SessionStorage values if rendered

Often Overlooked:

  • Error messages that reflect user input
  • PDF/document generators that accept HTML
  • Email templates with user data
  • Log viewers in admin panels
  • JSON responses rendered as HTML
  • SVG file uploads (can contain JavaScript)
  • Markdown rendering (if allowing HTML)
Protection Strategies
  1. Output Encoding (Context-Specific)

- HTML context: HTML entity encode (< → <) - JavaScript context: JavaScript escape - URL context: URL encode - CSS context: CSS escape - Use framework's built-in escaping (React's JSX, Vue's {{}}, etc.)

  1. Content Security Policy (CSP) Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' https://api.yourdomain.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self';

- Avoid 'unsafe-inline' and 'unsafe-eval' for scripts - Use nonces or hashes for inline scripts when necessary - Report violations: report-uri /csp-report

  1. Input Sanitization

- Use established libraries (DOMPurify for HTML) - Whitelist allowed tags/attributes for rich text - Strip or encode dangerous patterns

  1. Additional Headers

- X-Content-Type-Options: nosniff - X-Frame-Options: DENY (or use CSP frame-ancestors)


Cross-Site Request Forgery (CSRF)

Every state-changing endpoint must be protected against CSRF attacks.

Endpoints Requiring CSRF Protection

Authenticated Actions:

  • All POST, PUT, PATCH, DELETE requests
  • Any GET request that changes state (fix these to use proper HTTP methods)
  • File uploads
  • Settings changes
  • Payment/transaction endpoints

Pre-Authentication Actions:

  • Login endpoints (prevent login CSRF)
  • Signup endpoints
  • Password reset request endpoints
  • Password change endpoints
  • Email/phone verification endpoints
  • OAuth callback endpoints
Protection Mechanisms
  1. CSRF Tokens

- Generate cryptographically random tokens - Tie token to user session - Validate on every state-changing request - Regenerate after login (prevent session fixation combo)

  1. SameSite Cookies Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly

- Strict: Cookie never sent cross-site (best security) - Lax: Cookie sent on top-level navigations (good balance) - Always combine with CSRF tokens for defense in depth

  1. Double Submit Cookie Pattern

- Send CSRF token in both cookie and request body/header - Server validates they match

Edge Cases and Common Mistakes
  • Token presence check: CSRF validation must NOT depend on whether the token is present, always require it
  • Token per form: Consider unique tokens per form for sensitive operations
  • JSON APIs: Don't assume JSON content-type prevents CSRF; validate Origin/Referer headers AND use tokens
  • CORS misconfiguration: Overly permissive CORS can bypass SameSite cookies
  • Subdomains: CSRF tokens should be scoped because subdomain takeover can lead to CSRF
  • Flash/PDF uploads: Legacy browser plugins could bypass SameSite
  • GET requests with side effects: Never perform state changes on GET
  • Token leakage: Don't include CSRF tokens in URLs
  • Token in URL vs Header: Prefer custom headers (X-CSRF-Token) over URL parameters
Verification Checklist
  • Token is cryptographically random (use secure random generator)
  • Token is tied to user session
  • Token is validated server-side on all state-changing requests
  • Missing token = rejected request
  • Token regenerated on authentication state change
  • SameSite cookie attribute is set
  • Secure and HttpOnly flags on session cookies

Secret Keys and Sensitive Data Exposure

No secrets or sensitive information should be accessible to client-side code.

Never Expose in Client-Side Code

API Keys and Secrets:

  • Third-party API keys (Stripe, AWS, etc.)
  • Database connection strings
  • JWT signing secrets
  • Encryption keys
  • OAuth client secrets
  • Internal service URLs/credentials

Sensitive User Data:

  • Full credit card numbers
  • Social Security Numbers
  • Passwords (even hashed)
  • Security questions/answers
  • Full phone numbers (mask them: *-*-1234)
  • Sensitive PII that isn't needed for display

Infrastructure Details:

  • Internal IP addresses
  • Database schemas
  • Debug information
  • Stack traces in production
  • Server software versions
Where Secrets Hide (Check These!)
  • JavaScript bundles (including source maps)
  • HTML comments
  • Hidden form fields
  • Data attributes
  • LocalStorage/SessionStorage
  • Initial state/hydration data in SSR apps
  • Environment variables exposed via build tools (NEXT_PUBLIC_*, REACT_APP_*)
Best Practices
  1. Environment Variables: Store secrets in .env files
  2. Server-Side Only: Make API calls requiring secrets from backend only

Open Redirect

Any endpoint accepting a URL for redirection must be protected against open redirect attacks.

Protection Strategies

  1. Allowlist Validation allowed_domains = ['yourdomain.com', 'app.yourdomain.com'] function isValidRedirect(url): parsed = parseUrl(url) return parsed.hostname in allowed_domains
  2. Relative URLs Only

- Only accept paths (e.g., /dashboard) not full URLs - Validate the path starts with / and doesn't contain //

  1. Indirect References

- Use a mapping instead of raw URLs: ?redirect=dashboard → lookup to /dashboard

Bypass Techniques to Block

TechniqueExampleWhy It Works
@ symbolhttps://legit.com@evil.comBrowser navigates to evil.com with legit.com as username
Subdomain abusehttps://legit.com.evil.comevil.com owns the subdomain
Protocol tricksjavascript:alert(1)XSS via redirect
Double URL encoding%252f%252fevil.comDecodes to //evil.com after double decode
Backslashhttps://legit.com\@evil.comSome parsers normalize \ to /
Null bytehttps://legit.com%00.evil.comSome parsers truncate at null
Tab/newlinehttps://legit.com%09.evil.comWhitespace confusion
Unicode normalizationhttps://legіt.com (Cyrillic і)IDN homograph attack
Data URLsdata:text/html,<script>...Direct payload execution
Protocol-relative//evil.comUses current page's protocol
Fragment abusehttps://legit.com#@evil.comParsed differently by different libraries

IDN Homograph Attack Protection

  • Convert URLs to Punycode before validation
  • Consider blocking non-ASCII domains entirely for sensitive redirects

Password Security

Password Requirements
  • Minimum 8 characters (12+ recommended)
  • No maximum length (or very high, e.g., 128 chars)
  • Allow all characters including special chars
  • Don't require specific character types (let users choose strong passwords)
Storage
  • Use Argon2id, bcrypt, or scrypt
  • Never MD5, SHA1, or plain SHA256

Server-Side Bugs

Server-Side Request Forgery (SSRF)

Any functionality where the server makes requests to URLs provided or influenced by users must be protected.

Potential Vulnerable Features
  • Webhooks (user provides callback URL)
  • URL previews
  • PDF generators from URLs
  • Image/file fetching from URLs
  • Import from URL features
  • RSS/feed readers
  • API integrations with user-provided endpoints
  • Proxy functionality
  • HTML to PDF/image converters
Protection Strategies
  1. Allowlist Approach (Preferred)

- Only allow requests to pre-approved domains - Maintain a strict allowlist for integrations

  1. Network Segmentation

- Run URL-fetching services in isolated network - Block access to internal network, cloud metadata

IP and DNS Bypass Techniques to Block
TechniqueExampleDescription
Decimal IPhttp://2130706433127.0.0.1 as decimal
Octal IPhttp://0177.0.0.1Octal representation
Hex IPhttp://0x7f.0x0.0x0.0x1Hexadecimal
IPv6 localhosthttp://[::1]IPv6 loopback
IPv6 mapped IPv4http://[::ffff:127.0.0.1]IPv4-mapped IPv6
Short IPv6http://[::]All zeros
DNS rebindingAttacker's DNS returns internal IPFirst request resolves to external IP, second to internal
CNAME to internalAttacker domain CNAMEs to internalDNS points to internal hostname
URL parser confusionhttp://attacker.com#@internalDifferent parsing behaviors
Redirect chainsExternal URL redirects to internalFollow redirects carefully
IPv6 scope IDhttp://[fe80::1%25eth0]Interface-scoped IPv6
Rare IP formatshttp://127.1Shortened IP notation
DNS Rebinding Prevention
  1. Resolve DNS before making request
  2. Validate resolved IP is not internal
  3. Pin the resolved IP for the request (don't re-resolve)
  4. Or: Resolve twice with delay, ensure both resolve to same external IP
Cloud Metadata Protection

Block access to cloud metadata endpoints:

  • AWS: 169.254.169.254
  • GCP: metadata.google.internal, 169.254.169.254, http://metadata
  • Azure: 169.254.169.254
  • DigitalOcean: 169.254.169.254
Implementation Checklist
  • Validate URL scheme is HTTP/HTTPS only
  • Resolve DNS and validate IP is not private/internal
  • Block cloud metadata IPs explicitly
  • Limit or disable redirect following
  • If following redirects, validate each hop
  • Set timeout on requests
  • Limit response size
  • Use network isolation where possible

Insecure File Upload

File uploads must validate type, content, and size to prevent various attacks.

Validation Requirements

1. File Type Validation

  • Check file extension against allowlist
  • Validate magic bytes/file signature match expected type
  • Never rely on just one check

2. File Content Validation

  • Read and verify magic bytes
  • For images: attempt to process with image library (detects malformed files)
  • For documents: scan for macros, embedded objects
  • Check for polyglot files (files valid as multiple types)

3. File Size Limits

  • Set maximum file size server-side
  • Configure web server/proxy limits as well
  • Consider per-file-type limits (images smaller than videos)
Common Bypasses and Attacks
AttackDescriptionPrevention
Extension bypassshell.php.jpgCheck full extension, use allowlist
Null byteshell.php%00.jpgSanitize filename, check for null bytes
Double extensionshell.jpg.phpOnly allow single extension
MIME type spoofingSet Content-Type to image/jpegValidate magic bytes
Magic byte injectionPrepend valid magic bytes to malicious fileCheck entire file structure, not just header
Polyglot filesFile valid as both JPEG and JavaScriptParse file as expected type, reject if invalid
SVG with JavaScript<svg onload="alert(1)">Sanitize SVG or disallow entirely
XXE via file uploadMalicious DOCX, XLSX (which are XML)Disable external entities in parser
ZIP slip../../../etc/passwd in archiveValidate extracted paths
ImageMagick exploitsSpecially crafted imagesKeep ImageMagick updated, use policy.xml
Filename injection; rm -rf / in filenameSanitize filenames, use random names
Content-type confusionBrowser MIME sniffingSet X-Content-Type-Options: nosniff
Magic Bytes Reference
TypeMagic Bytes (hex)
JPEGFF D8 FF
PNG89 50 4E 47 0D 0A 1A 0A
GIF47 49 46 38
PDF25 50 44 46
ZIP50 4B 03 04
DOCX/XLSX50 4B 03 04 (ZIP-based)
Secure Upload Handling
  1. Rename files: Use random UUID names, discard original
  2. Store outside webroot: Or use separate domain for uploads
  3. Serve with correct headers:

- Content-Disposition: attachment (forces download) - X-Content-Type-Options: nosniff - Content-Type matching actual file type

  1. Use CDN/separate domain: Isolate uploaded content from main app
  2. Set restrictive permissions: Uploaded files should not be executable

SQL Injection

SQL injection occurs when user input is incorporated into SQL queries without proper handling.

Prevention Methods

1. Parameterized Queries (Prepared Statements) — PRIMARY DEFENSE

-- VULNERABLE
query = "SELECT * FROM users WHERE id = " + userId

-- SECURE
query = "SELECT * FROM users WHERE id = ?"
execute(query, [userId])

2. ORM Usage

  • Use ORM methods that automatically parameterize
  • Be cautious with raw query methods in ORMs
  • Watch for ORM-specific injection points

3. Input Validation

  • Validate data types (integer should be integer)
  • Whitelist allowed values where applicable
  • This is defense-in-depth, not primary defense
Injection Points to Watch
  • WHERE clauses
  • ORDER BY clauses (often overlooked—can't use parameters, must whitelist)
  • LIMIT/OFFSET values
  • Table and column names (can't parameterize—must whitelist)
  • INSERT values
  • UPDATE SET values
  • IN clauses with dynamic lists
  • LIKE patterns (also escape wildcards: %, _)
Additional Defenses
  • Least privilege: Database user should have minimum required permissions
  • Disable dangerous functions: Like xp_cmdshell in SQL Server
  • Error handling: Never expose SQL errors to users

XML External Entity (XXE)

XXE vulnerabilities occur when XML parsers process external entity references in user-supplied XML.

Vulnerable Scenarios

Direct XML Input:

  • SOAP APIs
  • XML-RPC
  • XML file uploads
  • Configuration file parsing
  • RSS/Atom feed processing

Indirect XML:

  • JSON/other format converted to XML server-side
  • Office documents (DOCX, XLSX, PPTX are ZIP with XML)
  • SVG files (XML-based)
  • SAML assertions
  • PDF with XFA forms
Prevention by Language/Parser

Java:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setExpandEntityReferences(false);

Python (lxml):

from lxml import etree
parser = etree.XMLParser(resolve_entities=False, no_network=True)
# Or use defusedxml library

PHP:

libxml_disable_entity_loader(true);
// Or use XMLReader with proper settings

Node.js:

// Use libraries that disable DTD processing by default
// If using libxmljs, set { noent: false, dtdload: false }

.NET:

XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.XmlResolver = null;
XXE Prevention Checklist
  • Disable DTD processing entirely if possible
  • Disable external entity resolution
  • Disable external DTD loading
  • Disable XInclude processing
  • Use latest patched XML parser versions
  • Validate/sanitize XML before parsing if DTD needed
  • Consider using JSON instead of XML where possible

Path Traversal

Path traversal vulnerabilities occur when user input controls file paths, allowing access to files outside intended directories.

Vulnerable Patterns
# VULNERABLE
file_path = "/uploads/" + user_input
file_path = base_dir + request.params['file']
template = "templates/" + user_provided_template
Prevention Strategies

1. Avoid User Input in Paths

# Instead of using user input directly
# Use indirect references
files = {'report': '/reports/q1.pdf', 'invoice': '/invoices/2024.pdf'}
file_path = files.get(user_input)  # Returns None if invalid

2. Canonicalization and Validation

import os

def safe_join(base_directory, user_path):
    # Ensure base is absolute and normalized
    base = os.path.abspath(os.path.realpath(base_directory))

    # Join and then resolve the result
    target = os.path.abspath(os.path.realpath(os.path.join(base, user_path)))

    # Ensure the commonpath is the base directory
    if os.path.commonpath([base, target]) != base:
        raise ValueError("Error!")

    return target

3. Input Sanitization

  • Remove or reject .. sequences
  • Remove or reject absolute path indicators (/, C:)
  • Whitelist allowed characters (alphanumeric, dash, underscore)
  • Validate file extension if applicable
Path Traversal Checklist
  • Never use user input directly in file paths
  • Canonicalize paths and validate against base directory
  • Restrict file extensions if applicable
  • Test with various encoding and bypass techniques

Security Headers Checklist

Include these headers in all responses:

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Content-Security-Policy: [see XSS section]
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Cache-Control: no-store (for sensitive pages)

JWT Security

JWT misconfigurations can lead to full authentication bypass and token forgery.

Vulnerabilities

VulnerabilityPrevention
alg: none attackAlways verify algorithm server-side, reject none
Algorithm confusionExplicitly specify expected algorithm, never derive from token
Weak HMAC secretsUse 256+ bit cryptographically random secrets
Missing expirationAlways set exp claim
Token in localStorageStore in httpOnly, Secure, SameSite=Strict cookies, never localStorage

Secure Implementation

// 1. SIGNING
// Always use environment variables for secrets
const secret = process.env.JWT_SECRET;

const token = jwt.sign({
  sub: userId,
  iat: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + (15 * 60), // 15 mins (Short-lived)
  jti: crypto.randomUUID() // Unique ID for revocation/blacklisting
}, secret, {
  algorithm: 'HS256'
});

// 2. SENDING (Cookie Best Practices)
// Protect against XSS and CSRF
res.cookie('token', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict'
});

// 3. VERIFYING
// CRITICAL: Whitelist the allowed algorithm
jwt.verify(token, secret, { algorithms: ['HS256'] }, (err, decoded) => {
  if (err) {
    // Handle invalid token
  }
  // Trust the payload
});

JWT Checklist

  • Algorithm explicitly specified on verification (never trust token header)
  • alg: none rejected
  • Secret is 256+ bits of random data (not a password or phrase)
  • exp claim always set and validated
  • Tokens stored in httpOnly cookies (not localStorage/sessionStorage)
  • Refresh token rotation implemented (old refresh token invalidated on use)

API Security

Mass Assignment

Accepting unfiltered request bodies can lead to privilege escalation.

// VULNERABLE — user can set { role: "admin" } in request body
User.update(req.body)

// SECURE — whitelist allowed fields
const allowed = ['name', 'email', 'avatar']
const updates = pick(req.body, allowed)
User.update(updates)

This applies to any ORM/framework — always explicitly define which fields a request can modify.

GraphQL

VulnerabilityPrevention
Introspection in productionDisable introspection in production environments.
Query depth attackImplement query depth limiting (e.g., maximum of 10 levels).
Query complexity attackCalculate and enforce strict query cost limits.
Batching attackLimit the number of operations allowed per single request.
const server = new ApolloServer({
  introspection: process.env.NODE_ENV !== 'production',
  validationRules: [
    depthLimit(10),
    costAnalysis({ maximumCost: 1000 })
  ]
})

General Security Principles

When generating code, always:

  1. Validate all input server-side — Never trust client-side validation alone
  2. Use parameterized queries — Never concatenate user input into queries
  3. Encode output contextually — HTML, JS, URL, CSS contexts need different encoding
  4. Apply authentication checks — On every endpoint, not just at routing
  5. Apply authorization checks — Verify the user can access the specific resource
  6. Use secure defaults
  7. Handle errors securely — Don't leak stack traces or internal details to users
  8. Keep dependencies updated — Use tools to track vulnerable dependencies

When unsure, choose the more restrictive/secure option and document the security consideration in comments.

平台分布

Codex

33.6%
按下载量换算119

Claude

27.93%
按下载量换算99

Cursor

18.76%
按下载量换算66

Gemini CLI

10.17%
按下载量换算36

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills