Token导航 LogoToken导航

Agent Skill · 前端设计

web-security(网络安全)

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

web-security 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描有提醒项,按安装量在前端设计类的 10,216 个 Skill 里排第 6,812。

总安装 451周安装 19GitHub Stars 2下载 158核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/tgautier/dotfiles --skill web-security

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

用于辅助安全审计、权限检查、凭据风险和认证流程分析,帮助识别常见漏洞和敏感配置。适用于安全复核、依赖风险检查和鉴权逻辑梳理等场景。

通过安装命令 npx skills add https://github.com/tgautier/dotfiles --skill web-security 从 GitHub 仓库安装使用。不能将工具输出直接当作最终结论,涉及密钥、令牌或生产系统时应先确认最小权限和操作边界。

适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

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

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/tgautier/dotfiles --skill web-security;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

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

常见问题

6 条

web-security 怎么安装?

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

web-security 支持哪些 AI 工具?

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

web-security 需要什么权限?

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

web-security 是免费的吗?

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

web-security 用的人多吗?

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

web-security 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

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

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

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

适不适合你

更适合

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

不太适合

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

前端设计类 Skill 对比

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

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
web-security

网络安全 · 本页

4512接触敏感数据未明确有提醒

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

SKILL.md 原文

Web Security

Cross-cutting browser-facing security guidance for production web applications. This skill deepens topics that span API design, frontend, and backend — CSRF, XSS, CSP, cookies, sessions, auth, JWT, OAuth 2.1, CORS, headers, SSRF, input validation, and supply chain security.

Based on OWASP cheat sheets (2024), Google BeyondCorp, Stripe security patterns, Cloudflare production configs, Mozilla Web Security Guidelines, Auth0/Okta best practices, the OAuth 2.1 draft (as of January 2025), and the OAuth 2.0 Security BCP (RFC 9700, January 2025).

Scope boundary: This skill covers *what* to enforce and *why*. For implementation: - Rust/Axum middleware and Tower layers → Rust skill (/rust §9, §12) - React patterns, dangerouslySetInnerHTML, href validation → TypeScript skill (/typescript §11) - API contract decisions (error format, status codes, auth headers) → API Design skill (/api-design §10-11)

1. Threat Model

Browser vs API attack surfaces

AttackVectorTarget
CSRFForged cross-origin request with ambient cookiesCookie-authenticated mutations
XSSInjected script in HTML contextSession tokens, user data, DOM
ClickjackingTransparent iframe overlayUser actions on framed page
SSRFServer fetches attacker-controlled URLInternal services, cloud metadata
CORS misconfigurationOverly permissive origin policyCross-origin data leakage
Session fixationAttacker sets victim's session IDAccount takeover
JWT confusionAlgorithm substitution or claim bypassAuthentication bypass

OWASP API Security Top 10 (2023) — quick reference

#RiskKey mitigation
API1Broken Object-Level AuthorizationCheck object ownership in every handler
API2Broken AuthenticationRate limit auth endpoints, enforce MFA
API3Broken Object Property-Level AuthorizationFilter response fields by role
API4Unrestricted Resource ConsumptionRate limiting, pagination limits, payload size caps
API5Broken Function-Level AuthorizationRBAC middleware on every route
API6Unrestricted Access to Sensitive Business FlowsBot detection, CAPTCHA on sensitive actions
API7Server-Side Request ForgeryInput validation, private IP denylist, egress firewall
API8Security MisconfigurationSecurity headers, disable debug endpoints, least privilege
API9Improper Inventory ManagementAPI versioning, deprecation policy, endpoint registry
API10Unsafe Consumption of APIsValidate third-party responses, timeout external calls
See API Design skill (/api-design §10) for contract-level auth patterns.

2. CSRF Protection

When CSRF matters

  • Needed: Cookie-based authentication + state-changing operations (POST/PUT/DELETE)
  • Not needed: Bearer token auth (no ambient credentials), API keys in headers, machine-to-machine

Defense layers (OWASP — implement at least two)

  1. Signed double-submit cookie (primary defense)

- Generate HMAC-signed token bound to the session ID — HMAC(session_id, secret_key) - Send in cookie + require in request header (X-CSRF-Token) or form field - Server verifies HMAC signature matches session — prevents cookie-tossing attacks - Never use unsigned/naive double-submit — OWASP explicitly discourages it (attacker on subdomain can overwrite unsigned cookies)

  1. Fetch Metadata validation (server-side, 98% browser coverage)

- Reject requests where Sec-Fetch-Site: cross-site on state-changing endpoints - Also check Sec-Fetch-Mode and Sec-Fetch-Dest for defense-in-depth - Graceful degradation: allow requests without Fetch Metadata headers (older browsers)

  1. Custom request headers (CORS-based defense)

- Require a custom header (e.g., X-Requested-With) on mutations - CORS preflight blocks cross-origin requests with custom headers unless explicitly allowed - Simple but effective — cross-origin <form> and <img> cannot set custom headers

  1. SameSite cookies (necessary but insufficient alone)

- SameSite=Lax — the correct default for web apps. Blocks cross-site POST while preserving top-level GET navigations (OAuth callbacks, inbound links). Pair with CSRF tokens for full protection - SameSite=Strict — blocks all cross-site cookie sending. Use only for apps with no OAuth, no external redirects, and no inbound authenticated links. Not "more secure" than Lax + CSRF tokens — just more restrictive - Not sufficient alone: subdomain attacks bypass SameSite, method override can convert GET→POST

  1. Origin / Referer verification (secondary check)

- Verify Origin header matches expected domain on mutations - Fall back to Referer if Origin absent - Secondary defense — don't rely on this alone (privacy extensions strip headers)

Key rule

XSS defeats all CSRF protections. If an attacker can execute JavaScript on your origin, they can read CSRF tokens from the DOM or cookies. Fix XSS first.

CSRF in OAuth flows

Stripe pattern: use the state parameter as a CSRF token — bind to the user's session, verify on callback. One-time use, expire after 5 minutes.


3. XSS Prevention

Context-specific output encoding (OWASP 5 rules)

ContextEncodingExample
HTML bodyHTML entity encode & < > " '<p>Hello <script></p>
HTML attributeAttribute encode (all non-alphanumeric as &#xHH;)<input value="&#x22;injected">
JavaScript stringJavaScript hex encode (\xHH)var x = '\x3cscript\x3e'
URL parameterURL encode (%HH)?q=%3Cscript%3E
CSS valueCSS hex encode (\HH)background: \3cscript\3e

Dangerous contexts — never place untrusted data in

  • Inside <script> blocks (even encoded)
  • Event handler attributes (onclick, onerror, onload)
  • eval(), setTimeout(string), new Function(string)
  • CSS expression() or url() with user input
  • javascript: URLs in href or src

Framework-specific

  • React: Auto-escapes JSX curly braces. Risk vectors: dangerouslySetInnerHTML (sanitize with DOMPurify), href attributes (validate against javascript: URLs), ref callbacks with user data
  • Trusted Types API: Enforce via CSP require-trusted-types-for 'script' — prevents DOM XSS at the browser level
  • User-authored HTML: Sanitize with DOMPurify configured with an explicit tag/attribute allowlist
See TypeScript skill (/typescript §11) for React-specific XSS patterns and <SafeHTML> component.

4. Content Security Policy

Strict nonce-based policy (recommended)

Content-Security-Policy:
  default-src 'self';
  script-src 'nonce-{RANDOM}' 'strict-dynamic';
  style-src 'self' 'nonce-{RANDOM}';
  object-src 'none';
  base-uri 'none';
  form-action 'self';
  frame-ancestors 'none';
  • Nonce: Generate a cryptographically random value per response, inject into <script nonce="..."> tags
  • strict-dynamic: Allows scripts loaded by nonced scripts (dynamic imports, trusted loaders) without explicit allowlisting
  • object-src 'none': Blocks Flash/Java plugin abuse
  • base-uri 'none': Prevents <base> tag injection (relative URL hijacking)
  • frame-ancestors 'none': Replaces X-Frame-Options: DENY for clickjacking protection

API-only CSP

Content-Security-Policy: default-src 'none'; frame-ancestors 'none'

APIs serve no HTML — lock everything down. Cloudflare recommends different header sets for API vs HTML responses.

Never use

  • unsafe-inline for scripts (defeats CSP purpose)
  • unsafe-eval (allows eval() — XSS vector)
  • Wildcard * in script-src or default-src

Rollout strategy (all sources agree)

  1. Deploy Content-Security-Policy-Report-Only with report-to / Reporting-Endpoints (optionally add legacy report-uri for older browsers)
  2. Monitor violations for 1-2 weeks
  3. Fix legitimate violations (inline scripts → nonced, eval() → alternatives)
  4. Switch to enforcing Content-Security-Policy
  5. Keep report-to reporting active for ongoing monitoring

5. Cookie Security

Recommended cookie configuration (Mozilla)

__Host-SESSION=<value>; Path=/; Secure; HttpOnly; SameSite=Lax

Cookie prefixes

PrefixRequirementsUse for
__Host-Secure, no Domain, Path=/Session cookies (strictest — prevents subdomain attacks)
__Secure-Secure onlyCookies that need subdomain sharing

Required attributes

AttributeValueWhy
Secure(flag)HTTPS only — prevents network sniffing
HttpOnly(flag)No JavaScript access — mitigates XSS token theft
SameSiteLaxCSRF mitigation — Lax is the correct default for web apps with OAuth or external links. Strict is a niche choice for closed apps with no external auth flows (see §2)
Path/Scope to entire site

Session cookies

  • No Max-Age or Expires — cookie dies with browser session
  • Explicit expiry on the server side via session store TTL

Token storage comparison

LocationProsConsRecommendation
HttpOnly cookieXSS-proof, auto-sentCSRF risk (mitigate per §2)Preferred for auth
localStorageSimple APIXSS reads it directlyNever for auth tokens
sessionStorageTab-scopedXSS reads it, lost on tab closeNever for auth tokens
Web WorkerNo DOM accessComplex setupAcceptable for SPAs

BFF pattern (Auth0)

Backend-for-Frontend: the frontend never sees tokens. The backend holds access/refresh tokens in HttpOnly cookies, proxies API calls with Bearer tokens attached server-side. Eliminates frontend token storage concerns entirely.

See API Design skill (/api-design §10) for token type decisions (JWT vs opaque).

6. Session Management

Session ID requirements (OWASP)

  • 128-bit minimum entropy generated by CSPRNG
  • Regenerate session ID on: login, privilege escalation, switching from HTTP to HTTPS
  • Rename default session cookie (don't use JSESSIONID, PHPSESSID, etc.)

Timeouts

TypeHigh-value appsLow-risk apps
Idle timeout2-5 minutes15-30 minutes
Absolute timeout4-8 hours12-24 hours

Logout

Server-side destruction is mandatory — expiring the cookie alone is insufficient:

  1. Destroy session in server store (database/cache)
  2. Clear session cookie (Set-Cookie with Max-Age=0)
  3. Clear any related tokens (refresh tokens, CSRF tokens)

Session anomaly detection

Session theft is invisible without anomaly detection — a stolen session cookie works silently until it expires. For apps handling financial data, PII, or privileged operations, detecting anomalies is how you catch compromised sessions before damage is done.

Monitor these attributes and trigger step-up authentication (not hard lockout) when they change mid-session:

  • Client IP address (detect IP change → force re-auth)
  • User-Agent string (detect browser change → force re-auth)
  • TLS client certificate (mutual TLS environments)

Why step-up, not hard binding: mobile networks, VPNs, and IPv6 privacy extensions cause legitimate IP changes. Hard binding locks out real users. Step-up auth (re-enter password, second factor) confirms identity without blocking access.

Re-authentication triggers

Require fresh authentication before:

  • Password change
  • Email/phone change
  • Payment method changes
  • New device or unfamiliar IP
  • Elevated privilege actions

7. Authentication

Password rules (NIST SP 800-63B)

RuleValue
Minimum length8 chars (with MFA) / 15 chars (without)
Maximum length64+ characters (never truncate)
Composition rulesNone — no uppercase/special char requirements
RotationNever require periodic rotation
Breached checkCheck against known breached databases (HIBP API)
FeedbackShow real-time strength meter based on entropy

Password storage

  • Argon2id (preferred) — memory-hard, resists GPU/ASIC attacks
  • bcrypt (acceptable) — widely supported, 72-byte input limit
  • scrypt (acceptable) — memory-hard alternative
  • Always use constant-time comparison for hash verification
  • Never use MD5, SHA-1, SHA-256, or PBKDF2-SHA1 for password storage

Brute force protection

  • Track failed attempts per account (not per IP — attackers rotate IPs)
  • Exponential backoff: 1s, 2s, 4s, 8s after consecutive failures
  • Lockout threshold: 5-10 failed attempts → temporary lock (15-30 min)
  • CAPTCHA after 3 failures as an alternative to lockout

User enumeration prevention

All authentication failure responses must be identical in:

  • Error message text ("Invalid credentials" — never "User not found" vs "Wrong password")
  • Response time (add artificial delay to fast-path failures)
  • HTTP status code (same 401 for all failure types)
  • Response body structure
See API Design skill (/api-design §10) for auth header patterns and token types.

8. JWT Security

Algorithm selection

  • RS256 (RSA + SHA-256) — asymmetric, preferred (Auth0/OWASP consensus)
  • ES256 (ECDSA) — smaller keys, equivalent security
  • Never HS256 for multi-party systems — shared secret means any verifier can forge tokens
  • Never alg: none — disable in JWT library configuration
  • Algorithm confusion attack: Server must enforce expected algorithm, never trust the alg header

Required claim validation

ClaimCheckOn failure
iss (issuer)Exact match against known issuerReject
aud (audience)Must contain this service's identifierReject
exp (expiration)Current time < exp (with clock skew tolerance)Reject
nbf (not before)Current time >= nbfReject
iat (issued at)Reasonable recency checkReject
sub (subject)Valid user identifier formatReject

Token lifetimes

TokenLifetimeStorage
Access token15-30 minutesHttpOnly cookie or memory
Refresh token (absolute)30 days maxHttpOnly cookie, server-side record
Refresh token (idle)7 daysRevoke if unused

Token sidejacking prevention (OWASP)

  1. Generate a random fingerprint at authentication
  2. Store fingerprint in a hardened HttpOnly cookie
  3. Hash the fingerprint (SHA-256) and embed in JWT claim
  4. On each request: hash the cookie value, compare to JWT claim
  5. Mismatch → reject (token was stolen but cookie wasn't)

Revocation

  • Maintain a SHA-256 denylist of revoked token identifiers (jti claim)
  • Check denylist on every validation (cache in Redis/memory)
  • Retain denylist entries until the token's exp passes
  • Revoke on: logout, password change, security incident

9. OAuth 2.1 (draft) & OAuth 2.0 Security BCP (RFC 9700)

What OAuth 2.1 (draft) changes

OAuth 2.1 is a draft that consolidates secure OAuth 2.0 patterns. RFC 9700 is a separate document, *OAuth 2.0 Security Best Current Practice*, which provides guidance for existing OAuth 2.0 deployments rather than defining OAuth 2.1 itself.

Removed:

  • Implicit grant (was response_type=token) — tokens in URL fragments are insecure
  • Resource Owner Password Credentials (ROPC) grant — exposes credentials to client
  • Bearer tokens in URL query strings (?access_token=...) — logged in server access logs

Required:

  • PKCE for ALL clients — not just public clients (confidential clients too)
  • Exact redirect URI matching — no wildcards, no partial matching, no path traversal
  • Sender-constrained refresh tokens for public clients — rotation on every use, or DPoP/mTLS binding

PKCE flow (required for all)

  1. Client generates code_verifier (43-128 chars, [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~")
  2. Client computes code_challenge = BASE64URL(SHA256(code_verifier))
  3. Authorization request includes code_challenge + code_challenge_method=S256
  4. Token exchange includes code_verifier — server verifies against stored challenge
  5. Never use plain method — always S256

Refresh token rotation (Auth0)

  • Issue new refresh token on every use, invalidate the old one
  • Reuse detection: If a previously-used refresh token is presented → revoke entire token family (theft signal)
  • 200 token cap per user per application
  • Absolute lifetime: 30 days (re-auth required after)

Security requirements (RFC 9700 specifics)

  • No CORS headers at the authorization endpoint
  • Never use HTTP 307 redirects with credentials (use 302/303)
  • state parameter must be one-time-use CSRF token bound to session
  • Authorization codes: single-use, expire in 10 minutes max

Application-level redirect validation (OWASP Unvalidated Redirects)

OAuth redirect URIs are validated by the provider, but applications often build their own redirect flows (e.g., returnTo after login, post-action redirects). These are equally dangerous if unsanitized.

Rules:

  • Every Location header derived from user input must be validated
  • Allow only relative paths starting with /
  • Reject protocol-relative URLs (//evil.com) and backslash-relative URLs (/\evil.com — some URL parsers normalize \ to /, resolving it as //evil.com)
  • Reject absolute URLs (https://...), javascript: URIs, and data: URIs
  • Fallback to a safe default (/) when validation fails — never echo the invalid input

Defense-in-depth: Sanitize at every trust boundary the value crosses:

  • At the entry point (where user input is first received)
  • At the storage point (before writing to session/cookie/DB)
  • At the exit point (before using as Location header)

Redundant sanitization is cheap. A single missed boundary is an open redirect.

Anti-patterns:

  • Location: ${req.query.returnTo} — raw user input in redirect header
  • Checking startsWith("/") without also checking // and /\ — incomplete guard
  • Sanitizing only at entry, trusting session values at exit — session tampering bypasses the check

10. CORS Hardening

Rules

  • Explicit origin allowlist — never Access-Control-Allow-Origin: * with credentials
  • Validate Origin header against allowlist on every request (not just preflight)
  • Preflight caching: Set Access-Control-Max-Age (e.g., 7200 seconds) to reduce preflight requests
  • Credential requests: Access-Control-Allow-Credentials: true requires a specific origin (not *)

Common mistakes

  • Reflecting the Origin header back as Access-Control-Allow-Origin without validation (allows any origin)
  • Allowing null origin (local files, sandboxed iframes can send Origin: null)
  • Trusting subdomains blindly (XSS on evil.sub.example.com compromises api.example.com)
  • Exposing sensitive headers via Access-Control-Expose-Headers unnecessarily

API vs HTML distinction (Cloudflare)

  • HTML responses: full security header set (CSP, HSTS, X-Frame-Options, etc.)
  • API responses: skip HTML-specific headers (Content-Security-Policy script/style directives, X-Frame-Options, frame-ancestors), but still include: X-Content-Type-Options: nosniff, Strict-Transport-Security, Referrer-Policy, and CORS headers
See Rust skill (/rust §9) for Axum Tower CORS middleware implementation.

11. Security Headers Checklist

Consensus header set (OWASP + Cloudflare + Mozilla)

HeaderValueNotes
Strict-Transport-Securitymax-age=63072000; includeSubDomains2 years, all subdomains. Add preload only after confirming all subdomains support HTTPS — removal from the preload list takes months
X-Content-Type-OptionsnosniffPrevents MIME-type sniffing
X-Frame-OptionsDENYClickjacking defense (pair with CSP frame-ancestors)
Referrer-Policystrict-origin-when-cross-originSend origin only on cross-origin, full URL same-origin
Cross-Origin-Opener-Policysame-originIsolates browsing context from cross-origin popups
Cross-Origin-Embedder-Policyrequire-corpEnables SharedArrayBuffer, cross-origin isolation
Cross-Origin-Resource-Policysame-sitePrevents cross-site embedding of resources
Permissions-Policygeolocation=(), camera=(), microphone=(), interest-cohort=()Disable unused browser features
X-XSS-Protection0Auditor removed from all browsers — disable to avoid false positives
Content-TypeInclude charset: application/json; charset=UTF-8Prevents charset-based XSS

Headers to remove

HeaderWhy
ServerLeaks server software and version
X-Powered-ByLeaks framework (Express, Rails, etc.)
Expect-CTDeprecated — Certificate Transparency is now enforced by default
Public-Key-PinsDeprecated — risk of bricking sites, replaced by CT

12. SSRF Prevention

Application layer (OWASP)

  1. Validate input: Check URL format before processing
  2. Resolve domain: DNS-resolve the hostname before connecting
  3. Check against private IP denylist:

- 10.0.0.0/8 (RFC 1918) - 172.16.0.0/12 (RFC 1918) - 192.168.0.0/16 (RFC 1918) - 127.0.0.0/8 (loopback) - 169.254.0.0/16 (link-local, including cloud metadata at 169.254.169.254) - ::1, fc00::/7, fe80::/10 (IPv6 equivalents)

  1. Disable redirect following — or re-validate after each redirect
  2. Protocol allowlist: HTTP and HTTPS only (block file://, gopher://, dict://)
  3. Response handling: Don't return raw responses to users (information leakage)

Network layer

  • Firewall egress rules: restrict outbound connections from application servers
  • Network segmentation: application servers cannot reach internal services directly
  • Cloud metadata: use IMDSv2 only (AWS) — requires session token, prevents SSRF to metadata endpoint

13. Input Validation

Principles (OWASP)

  • Server-side mandatory — client-side validation is UX only, never a security boundary
  • Allow-list over deny-list — define what IS valid, not what ISN'T
  • Validate syntactically, then semantically — check format first, then business rules

String validation

CheckRule
LengthEnforce min and max (prevent buffer abuse, empty strings)
CharsetAllowlist valid characters for the field
UnicodeNormalize (NFKC) before validation (prevents homograph attacks)
RegexAlways anchor: ^pattern$ (unanchored regex matches substrings)
ReDoSTest regex patterns for catastrophic backtracking — avoid nested quantifiers (a+)+

Email validation

  • Max 254 characters (RFC 5321)
  • Don't over-validate format — send a verification email instead
  • Verification token: single-use, 32+ characters, 8-hour TTL
  • Normalize: lowercase the domain portion (local part is case-sensitive per spec, but lowercase in practice)

File upload validation

CheckRule
ExtensionAllowlist (jpg, png, pdf) — never denylist
FilenameRename to random UUID (prevents path traversal)
Content-TypeVerify magic bytes match declared type
SizeEnforce max file size at web server level (before application)
StorageStore outside web root, serve via controlled endpoint
MalwareScan with antivirus on upload

Pipeline safety (parse, don't validate)

  • Each function in a sanitize→transform pipeline must be independently safe for any input
  • Don't rely on callers invoking pipeline steps in order — make each step idempotent for untrusted input
  • When validating against external formats (OAuth codes, HTTP headers), cite the actual spec grammar, not assumptions from observed values
  • Prototype pollution guard: in JS/TS, use Object.hasOwn() or Map for lookups, never bare record[key]?? fallback — prototype keys like constructor or __proto__ bypass the fallback
See Rust skill (/rust §12) for Diesel parameterized queries (SQL injection prevention). See TypeScript skill (/typescript §11) for framework-level input handling.

14. Dependency & Supply Chain Security

Automated scanning

ToolLanguageRun in CI
yarn auditJavaScript/TypeScriptEvery PR
cargo auditRustEvery PR
cargo denyRust (license + advisory)Every PR

Lock file integrity

  • Commit lock files (yarn.lock, Cargo.lock) — ensures reproducible builds
  • CI should fail if lock file is out of sync with manifest
  • Review lock file diffs on dependency updates (detect supply chain substitution)

API key leak prevention (Stripe pattern)

  • Prefix keys: sk_live_, sk_test_, pk_live_, pk_test_
  • Prefixes enable automated scanning in: git hooks, CI, GitHub secret scanning
  • Rotate immediately on exposure — assume compromised

Subresource Integrity (SRI)

<script src="https://cdn.example.com/lib.js"
        integrity="sha384-{hash}"
        crossorigin="anonymous"></script>
  • Required for all externally-hosted scripts
  • Prevents CDN compromise from injecting malicious code
  • Generate with shasum -b -a 384 lib.js | awk '{print $1}' | xxd -r -p | base64

Minimal dependency philosophy

  • Every dependency is an attack surface — prefer standard library when possible
  • Audit new dependencies before adding: maintenance status, contributor count, known vulnerabilities
  • Pin major versions, allow patch updates only in CI
See TypeScript skill (/typescript §11) for npm-specific patterns. See Rust skill (/rust §12) for cargo-specific patterns.

平台分布

Codex

39.44%
按下载量换算62

Claude

29%
按下载量换算46

Cursor

17.17%
按下载量换算27

Gemini CLI

10.37%
按下载量换算16

安全审计

Gen Agent Trust Hub

通过

Socket

可疑

Snyk

通过

权限和风险

接触敏感数据

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

安装前确认

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

继续浏览同类 Skills