SkillAtlasSkill 详情

security-and-hardening

Production-grade engineering skills for AI coding agents.

审核状态:已审核Quality 72Security 70

复制安装命令

用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。

复制前请先查看来源、License 和安全提示。

项目 README

来源文件:README.md

抓取于 2026年7月29日

Agent Skills

Production-grade engineering skills for AI coding agents.

Skills encode the workflows, quality gates, and best practices that senior engineers use when building software. These ones are packaged so AI agents follow them consistently across every phase of development.

addyosmani%2Fagent-skills | Trendshift

Addy's Agent Skills

  DEFINE          PLAN           BUILD          VERIFY         REVIEW          SHIP
 ┌──────┐      ┌──────┐      ┌──────┐      ┌──────┐      ┌──────┐      ┌──────┐
 │ Idea │ ───▶ │ Spec │ ───▶ │ Code │ ───▶ │ Test │ ───▶ │  QA  │ ───▶ │  Go  │
 │Refine│      │  PRD │      │ Impl │      │Debug │      │ Gate │      │ Live │
 └──────┘      └──────┘      └──────┘      └──────┘      └──────┘      └──────┘
  /spec          /plan          /build        /test         /review       /ship

Commands

8 slash commands that map to the development lifecycle. Each one activates the right skills automatically.

What you're doingCommandKey principle
Define what to build/specSpec before code
Plan how to build it/planSmall, atomic tasks
Build incrementally/buildOne slice at a time
Prove it works/testTests are proof
Review before merge/reviewImprove code health
Audit web performance/webperfMeasure before you optimize
Simplify the code/code-simplifyClarity over cleverness
Ship to production/shipFaster is safer

Want fewer manual steps once the spec exists? /build auto generates the plan and implements every task in a single approved pass — you approve the plan once, then it runs autonomously. It removes the human stepping between tasks, not the verification: every task is still test-driven and committed individually, and it pauses on failures or risky steps.

Skills also activate automatically based on what you're doing — designing an API triggers api-and-interface-design, building UI triggers frontend-ui-engineering, and so on.


Quick Start

Fastest path — any agent, one command. The open skills CLI installs into 70+ agents (Claude Code, Cursor, Codex, Copilot, Cline, and more):

npx skills add addyosmani/agent-skills            # install all 24 skills
npx skills add addyosmani/agent-skills --list     # browse before installing

Or grab individual skills:

npx skills add addyosmani/agent-skills --skill code-review-and-quality   # five-axis review before merge
npx skills add addyosmani/agent-skills --skill interview-me              # requirements interrogation, one question at a time
npx skills add addyosmani/agent-skills --skill test-driven-development   # red-green-refactor, enforced

Prefer a native integration? Pick your tool below.

Claude Code (recommended)

Marketplace install:

/plugin marketplace add addyosmani/agent-skills
/plugin install agent-skills@addy-agent-skills

SSH errors? The marketplace clones repos via SSH. If you don't have SSH keys set up on GitHub, either add your SSH key or use the full HTTPS URL to force HTTPS cloning during the marketplace-add step:

/plugin marketplace add https://github.com/addyosmani/agent-skills.git
/plugin install agent-skills@addy-agent-skills

If /plugin install still fails with git@github.com: Permission denied (publickey) on Windows or macOS, the recommended workaround is to configure Git once to rewrite GitHub SSH URLs to HTTPS for subprocess clones:

git config --global url."https://github.com/".insteadOf git@github.com:

Local / development:

git clone https://github.com/addyosmani/agent-skills.git
claude --plugin-dir /path/to/agent-skills
Cursor

Put workflow skills under .cursor/skills/ (sync from agent-skills/skills/) and short policies in .cursor/rules/*.mdc — do not paste full skills into rules. See docs/cursor-setup.md.

Antigravity CLI

Install as a native plugin for skills, subagents, and slash commands. See docs/antigravity-setup.md.

Install from the repo:

agy plugin install https://github.com/addyosmani/agent-skills.git

Install from a local clone:

git clone https://github.com/addyosmani/agent-skills.git
agy plugin install ./agent-skills
Gemini CLI

Install as native skills for auto-discovery, or add to GEMINI.md for persistent context. See docs/gemini-cli-setup.md.

Install from the repo:

gemini skills install https://github.com/addyosmani/agent-skills.git --path skills

Install from a local clone:

gemini skills install ./agent-skills/skills/
Windsurf

Add skill contents to your Windsurf rules configuration. See docs/windsurf-setup.md.

OpenCode

Uses agent-driven skill execution via AGENTS.md and the skill tool.

See docs/opencode-setup.md.

GitHub Copilot

Use agent definitions from agents/ as Copilot personas and skill content in .github/copilot-instructions.md. See docs/copilot-setup.md.

Kiro IDE & CLI Skills for Kiro reside under ".kiro/skills/" and can be stored under Project or Global level. Kiro also supports Agents.md. See Kiro docs at https://kiro.dev/docs/skills/
Codex

Install as a native Codex plugin (Codex CLI v0.122+):

codex plugin marketplace add addyosmani/agent-skills

Codex reads the root skills/ directory directly through .codex-plugin/plugin.json. Once installed, invoke skills in chat using @ (e.g., @spec-driven-development). See docs/codex-setup.md for local installation and troubleshooting.

Other Agents

Skills are plain Markdown - they work with any agent that accepts system prompts or instruction files. See docs/getting-started.md.


Adoption

Already installed? How you roll the pack out depends on your codebase. The Adoption Guide covers two paths: the full lifecycle from day one for a greenfield project, or an incremental, verification-first rollout for an established codebase.


All 24 Skills

The commands above are entry points. The pack includes 24 skills total — 23 lifecycle skills plus the using-agent-skills meta-skill. Each skill is a structured workflow with steps, verification gates, and anti-rationalization tables. You can also reference any skill directly.

Meta - Discover which skill applies

SkillWhat It DoesUse When
using-agent-skillsMaps incoming work to the right skill workflow and defines shared operating rulesStarting a session or deciding which skill applies

Define - Clarify what to build

SkillWhat It DoesUse When
interview-meOne-question-at-a-time interview that extracts what the user actually wants instead of what they think they should want, until ~95% confidenceThe ask is underspecified, or the user invokes "interview me" / "grill me"
idea-refineStructured divergent/convergent thinking to turn vague ideas into concrete proposalsYou have a rough concept that needs exploration
spec-driven-developmentWrite a PRD covering objectives, commands, structure, code style, testing, and boundaries before any codeStarting a new project, feature, or significant change

Plan - Break it down

SkillWhat It DoesUse When
planning-and-task-breakdownDecompose specs into small, verifiable tasks with acceptance criteria and dependency orderingYou have a spec and need implementable units

Build - Write the code

SkillWhat It DoesUse When
incremental-implementationThin vertical slices - implement, test, verify, commit. Feature flags, safe defaults, rollback-friendly changesAny change touching more than one file
test-driven-developmentRed-Green-Refactor, test pyramid (80/15/5), test sizes, DAMP over DRY, Beyonce Rule, browser testingImplementing logic, fixing bugs, or changing behavior
context-engineeringFeed agents the right information at the right time - rules files, context packing, MCP integrationsStarting a session, switching tasks, or when output quality drops
source-driven-developmentGround every framework decision in official documentation - verify, cite sources, flag what's unverifiedYou want authoritative, source-cited code for any framework or library
doubt-driven-developmentAdversarial fresh-context review of every non-trivial decision in-flight - CLAIM → EXTRACT → DOUBT → RECONCILE → STOP, with optional user-authorized cross-model escalationStakes are high (production, security, irreversible), working in unfamiliar code, or a confident output is cheaper to verify now than to debug later
frontend-ui-engineeringComponent architecture, design systems, state management, responsive design, WCAG 2.1 AA accessibilityBuilding or modifying user-facing interfaces
api-and-interface-designContract-first design, Hyrum's Law, One-Version Rule, error semantics, boundary validationDesigning APIs, module boundaries, or public interfaces

Verify - Prove it works

SkillWhat It DoesUse When
browser-testing-with-devtoolsChrome DevTools MCP for live runtime data - DOM inspection, console logs, network traces, performance profilingBuilding or debugging anything that runs in a browser
debugging-and-error-recoveryFive-step triage: reproduce, localize, reduce, fix, guard. Stop-the-line rule, safe fallbacksTests fail, builds break, or behavior is unexpected

Review - Quality gates before merge

SkillWhat It DoesUse When
code-review-and-qualityFive-axis review, change sizing (~100 lines), severity labels (Nit/Optional/FYI), review speed norms, splitting strategiesBefore merging any change
code-simplificationChesterton's Fence, Rule of 500, reduce complexity while preserving exact behaviorCode works but is harder to read or maintain than it should be
security-and-hardeningOWASP Top 10 prevention, auth patterns, secrets management, dependency auditing, three-tier boundary systemHandling user input, auth, data storage, or external integrations
performance-optimizationMeasure-first approach - Core Web Vitals targets, profiling workflows, bundle analysis, anti-pattern detectionPerformance requirements exist or you suspect regressions

Ship - Deploy with confidence

SkillWhat It DoesUse When
git-workflow-and-versioningTrunk-based development, atomic commits, change sizing (~100 lines), the commit-as-save-point patternMaking any code change (always)
ci-cd-and-automationShift Left, Faster is Safer, feature flags, quality gate pipelines, failure feedback loopsSetting up or modifying build and deploy pipelines
deprecation-and-migrationCode-as-liability mindset, compulsory vs advisory deprecation, migration patterns, zombie code removalRemoving old systems, migrating users, or sunsetting features
documentation-and-adrsArchitecture Decision Records, API docs, inline documentation standards - document the whyMaking architectural decisions, changing APIs, or shipping features
observability-and-instrumentationStructured logging, RED metrics, OpenTelemetry tracing, symptom-based alerting - instrument as you buildAdding telemetry, or shipping anything that runs in production
shipping-and-launchPre-launch checklists, feature flag lifecycle, staged rollouts, rollback procedures, monitoring setupPreparing to deploy to production

Agent Personas

Pre-configured specialist personas for targeted reviews:

AgentRolePerspective
code-reviewerSenior Staff EngineerFive-axis code review with "would a staff engineer approve this?" standard
test-engineerQA SpecialistTest strategy, coverage analysis, and the Prove-It pattern
security-auditorSecurity EngineerVulnerability detection, threat modeling, OWASP assessment
web-performance-auditorWeb Performance EngineerCore Web Vitals audit with Quick/Deep modes and a metric-honesty rule; run it via /webperf

See docs/agents.md for the decision matrix, orchestration rules, and how personas compose with skills and slash commands.


Reference Checklists

Quick-reference material that skills pull in when needed:

ReferenceCovers
definition-of-done.mdProject-wide standing bar every change clears, contrasted with per-task acceptance criteria
testing-patterns.mdTest structure, naming, mocking, React/API/E2E examples, anti-patterns (JavaScript/TypeScript)
security-checklist.mdPre-commit checks, auth, input validation, headers, CORS, OWASP Top 10
performance-checklist.mdCore Web Vitals targets, frontend/backend checklists, measurement commands
accessibility-checklist.mdKeyboard nav, screen readers, visual design, ARIA, testing tools
observability-checklist.mdOn-call questions, structured logging, RED/USE metrics, tracing, symptom-based alerting, pre-launch gate
orchestration-patterns.mdEndorsed multi-persona orchestration patterns, anti-patterns, and the "personas don't invoke personas" rule

How Skills Work

Every skill follows a consistent anatomy:

┌─────────────────────────────────────────────────┐
│  SKILL.md                                       │
│                                                 │
│  ┌─ Frontmatter ─────────────────────────────┐  │
│  │ name: lowercase-hyphen-name               │  │
│  │ description: Guides agents through [task].│  │
│  │              Use when…                    │  │
│  └───────────────────────────────────────────┘  │                                                                                                
│  Overview         → What this skill does        │
│  When to Use      → Triggering conditions       │
│  Process          → Step-by-step workflow       │
│  Rationalizations → Excuses + rebuttals         │
│  Red Flags        → Signs something's wrong     │
│  Verification     → Evidence requirements       │
└─────────────────────────────────────────────────┘

Key design choices:

  • Process, not prose. Skills are workflows agents follow, not reference docs they read. Each has steps, checkpoints, and exit criteria.
  • Anti-rationalization. Every skill includes a table of common excuses agents use to skip steps (e.g., "I'll add tests later") with documented counter-arguments.
  • Verification is non-negotiable. Every skill ends with evidence requirements - tests passing, build output, runtime data. "Seems right" is never sufficient.
  • Progressive disclosure. The SKILL.md is the entry point. Supporting references load only when needed, keeping token usage minimal.

Project Structure

agent-skills/
├── skills/                            # 24 skills (23 lifecycle + 1 meta)
│   ├── interview-me/                  #   Define
│   ├── idea-refine/                   #   Define
│   ├── spec-driven-development/       #   Define
│   ├── planning-and-task-breakdown/   #   Plan
│   ├── incremental-implementation/    #   Build
│   ├── context-engineering/           #   Build
│   ├── source-driven-development/     #   Build
│   ├── doubt-driven-development/      #   Build
│   ├── frontend-ui-engineering/       #   Build
│   ├── test-driven-development/       #   Build
│   ├── api-and-interface-design/      #   Build
│   ├── browser-testing-with-devtools/ #   Verify
│   ├── debugging-and-error-recovery/  #   Verify
│   ├── code-review-and-quality/       #   Review
│   ├── code-simplification/           #   Review
│   ├── security-and-hardening/        #   Review
│   ├── performance-optimization/      #   Review
│   ├── git-workflow-and-versioning/   #   Ship
│   ├── ci-cd-and-automation/          #   Ship
│   ├── deprecation-and-migration/     #   Ship
│   ├── documentation-and-adrs/        #   Ship
│   ├── observability-and-instrumentation/ # Ship
│   ├── shipping-and-launch/           #   Ship
│   └── using-agent-skills/            #   Meta: how to use this pack
├── agents/                            # 4 specialist personas
├── references/                        # 7 supplementary checklists
├── hooks/                             # Session lifecycle hooks
├── .claude/commands/                  # 8 slash commands (Claude Code)
├── .gemini/commands/                  # 8 slash commands (Gemini CLI)
├── commands/                          # 8 slash commands (Antigravity CLI)
├── plugin.json                        # Antigravity plugin manifest
└── docs/                              # Setup guides per tool

Why Agent Skills?

AI coding agents default to the shortest path - which often means skipping specs, tests, security reviews, and the practices that make software reliable. Agent Skills gives agents structured workflows that enforce the same discipline senior engineers bring to production code.

Each skill encodes hard-won engineering judgment: when to write a spec, what to test, how to review, and when to ship. These aren't generic prompts - they're the kind of opinionated, process-driven workflows that separate production-quality work from prototype-quality work.

Skills bake in best practices from Google's engineering culture — including concepts from Software Engineering at Google and Google's engineering practices guide. You'll find Hyrum's Law in API design, the Beyonce Rule and test pyramid in testing, change sizing and review speed norms in code review, Chesterton's Fence in simplification, trunk-based development in git workflow, Shift Left and feature flags in CI/CD, and a dedicated deprecation skill treating code as a liability. These aren't abstract principles — they're embedded directly into the step-by-step workflows agents follow.


How it compares

Wondering how this stacks up against Superpowers or Matt Pocock's skills? See docs/comparison.md for an honest, side-by-side look at how the three are shaped differently and when to reach for each — including a link to a controlled head-to-head experiment.


Contributing

Skills should be specific (actionable steps, not vague advice), verifiable (clear exit criteria with evidence requirements), battle-tested (based on real workflows), and minimal (only what's needed to guide the agent).

See docs/skill-anatomy.md for the format specification and CONTRIBUTING.md for guidelines.


Team

agent-skills is built and maintained by:

NameGitHubRole
Addy OsmaniAddy Osmani@addyosmaniCreator
Federico BartoliFederico Bartoli@federicobartoliCollaborator
Joan LeónJoan León@nucliwebCollaborator

License

MIT - use these skills in your projects, teams, and tools.

开发与工程数据与 AI

中风险

  • 来源需自行核对维护者身份。
  • 包含脚本或命令调用,安装前请复核。
  • 可能需要外部 token、网络权限或第三方服务。
  • 未检测到高风险命令。
  • 扫描发现:3 条。

Codex — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/addyosmani/agent-skills.git
  3. 将 "skills/security-and-hardening" 文件夹复制到 Codex 的 skills 目录中。
  4. 重启 Codex 让新的 skill 生效。

Codex — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Codex 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Codex 让新的 skill 生效。

Claude Code — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/addyosmani/agent-skills.git
  3. 将 "skills/security-and-hardening" 文件夹复制到 Claude Code 的 skills 目录中。
  4. 重启 Claude Code 让新的 skill 生效。

Claude Code — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Claude Code 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Claude Code 让新的 skill 生效。

Cursor — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/addyosmani/agent-skills.git
  3. 将 "skills/security-and-hardening" 文件夹复制到 Cursor 的 skills 目录中。
  4. 重启 Cursor 让新的 skill 生效。

Cursor — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Cursor 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Cursor 让新的 skill 生效。

GitHub Copilot — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/addyosmani/agent-skills.git
  3. 将 "skills/security-and-hardening" 文件夹复制到 GitHub Copilot 的 skills 目录中。
  4. 重启 GitHub Copilot 让新的 skill 生效。

GitHub Copilot — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 GitHub Copilot 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 GitHub Copilot 让新的 skill 生效。

Windsurf — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/addyosmani/agent-skills.git
  3. 将 "skills/security-and-hardening" 文件夹复制到 Windsurf 的 skills 目录中。
  4. 重启 Windsurf 让新的 skill 生效。

Windsurf — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Windsurf 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Windsurf 让新的 skill 生效。
查看 SKILL.md 原文
name: security-and-hardening
description: Hardens code against vulnerabilities. Use when handling user input, authentication, data storage, or external integrations. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services.

Security and Hardening

Overview

Security-first development practices for web applications. Treat every external input as hostile, every secret as sacred, and every authorization check as mandatory. Security isn't a phase — it's a constraint on every line of code that touches user data, authentication, or external systems.

When to Use

  • Building anything that accepts user input
  • Implementing authentication or authorization
  • Storing or transmitting sensitive data
  • Integrating with external APIs or services
  • Adding file uploads, webhooks, or callbacks
  • Handling payment or PII data

Process: Threat Model First

Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:

  1. Map the trust boundaries. Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and LLM output. Every boundary is attack surface.
  2. Name the assets. What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.
  3. Run STRIDE over each boundary — a quick lens, not a ceremony:
ThreatAskTypical mitigation
SpoofingCan someone impersonate a user/service?Authentication, signature verification
TamperingCan data be altered in transit or at rest?Integrity checks, parameterized queries, HTTPS
RepudiationCan an action be denied later?Audit logging of security events
Information disclosureCan data leak?Encryption, field allowlists, generic errors
Denial of serviceCan it be overwhelmed?Rate limiting, input size caps, timeouts
Elevation of privilegeCan a user gain rights they shouldn't?Authorization checks, least privilege
  1. Write abuse cases next to use cases. For each feature, ask "how would I misuse this?" — then make that your first test.

If you can't name the trust boundaries for a feature, you're not ready to secure it. This is OWASP A04: Insecure Design — most breaches begin in design, not code.

The Three-Tier Boundary System

Always Do (No Exceptions)

  • Validate all external input at the system boundary (API routes, form handlers)
  • Parameterize all database queries — never concatenate user input into SQL
  • Encode output to prevent XSS (use framework auto-escaping, don't bypass it)
  • Use HTTPS for all external communication
  • Hash passwords with bcrypt/scrypt/argon2 (never store plaintext)
  • Set security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
  • Use httpOnly, secure, sameSite cookies for sessions
  • Run the detected package manager's native audit against the committed lockfile before every release

Ask First (Requires Human Approval)

  • Adding new authentication flows or changing auth logic
  • Storing new categories of sensitive data (PII, payment info)
  • Adding new external service integrations
  • Changing CORS configuration
  • Adding file upload handlers
  • Modifying rate limiting or throttling
  • Granting elevated permissions or roles

Never Do

  • Never commit secrets to version control (API keys, passwords, tokens)
  • Never log sensitive data (passwords, tokens, full credit card numbers)
  • Never trust client-side validation as a security boundary
  • Never disable security headers for convenience
  • Never use eval() or innerHTML with user-provided data
  • Never store sessions in client-accessible storage (localStorage for auth tokens)
  • Never expose stack traces or internal error details to users

OWASP Top 10 Prevention Patterns

These are prevention patterns, not a ranking. For the 2021 ordering, see the quick-reference table in references/security-checklist.md.

Injection (SQL, NoSQL, OS Command)

// BAD: SQL injection via string concatenation
const query = `SELECT * FROM users WHERE id = '${userId}'`;

// GOOD: Parameterized query
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);

// GOOD: ORM with parameterized input
const user = await prisma.user.findUnique({ where: { id: userId } });

Broken Authentication

// Password hashing
import { hash, compare } from 'bcrypt';

const SALT_ROUNDS = 12;
const hashedPassword = await hash(plaintext, SALT_ROUNDS);
const isValid = await compare(plaintext, hashedPassword);

// Session management
app.use(session({
  secret: process.env.SESSION_SECRET,  // From environment, not code
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,     // Not accessible via JavaScript
    secure: true,       // HTTPS only
    sameSite: 'lax',    // CSRF protection
    maxAge: 24 * 60 * 60 * 1000,  // 24 hours
  },
}));

Cross-Site Scripting (XSS)

// BAD: Rendering user input as HTML
element.innerHTML = userInput;

// GOOD: Use framework auto-escaping (React does this by default)
return <div>{userInput}</div>;

// If you MUST render HTML, sanitize first
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userInput);

Broken Access Control

// Always check authorization, not just authentication
app.patch('/api/tasks/:id', authenticate, async (req, res) => {
  const task = await taskService.findById(req.params.id);

  // Check that the authenticated user owns this resource
  if (task.ownerId !== req.user.id) {
    return res.status(403).json({
      error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' }
    });
  }

  // Proceed with update
  const updated = await taskService.update(req.params.id, req.body);
  return res.json(updated);
});

Security Misconfiguration

// Security headers (use helmet for Express)
import helmet from 'helmet';
app.use(helmet());

// Content Security Policy
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],
    styleSrc: ["'self'", "'unsafe-inline'"],  // Tighten if possible
    imgSrc: ["'self'", 'data:', 'https:'],
    connectSrc: ["'self'"],
  },
}));

// CORS — restrict to known origins
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000',
  credentials: true,
}));

Sensitive Data Exposure

// Never return sensitive fields in API responses
function sanitizeUser(user: UserRecord): PublicUser {
  const { passwordHash, resetToken, ...publicFields } = user;
  return publicFields;
}

// Use environment variables for secrets
const API_KEY = process.env.STRIPE_API_KEY;
if (!API_KEY) throw new Error('STRIPE_API_KEY not configured');

Server-Side Request Forgery (SSRF)

Any time the server fetches a URL the user influenced — webhooks, "import from URL", image proxies, link previews — an attacker can aim it at internal services (cloud metadata, localhost, private IPs).

// BAD: fetch whatever the user gives you
await fetch(req.body.webhookUrl);

// GOOD: allowlist scheme + host, reject if ANY resolved IP is private, forbid redirects
import { lookup } from 'node:dns/promises';
import ipaddr from 'ipaddr.js';

const ALLOWED_HOSTS = new Set(['hooks.example.com']);

async function assertSafeUrl(raw: string): Promise<URL> {
  const url = new URL(raw);
  if (url.protocol !== 'https:') throw new Error('https only');
  if (!ALLOWED_HOSTS.has(url.hostname)) throw new Error('host not allowed');
  // Resolve ALL records; a single private/reserved address fails the check.
  const addrs = await lookup(url.hostname, { all: true });
  if (addrs.some((a) => ipaddr.parse(a.address).range() !== 'unicast')) {
    throw new Error('private/reserved IP');
  }
  return url;
}

await fetch(await assertSafeUrl(req.body.webhookUrl), { redirect: 'error' });

The range() !== 'unicast' check covers loopback, link-local 169.254.169.254 (cloud metadata, the #1 SSRF target), private, and unique-local ranges across IPv4 and IPv6.

Caveat — this still has a TOCTOU gap. fetch resolves DNS again after the check, so an attacker using a short-TTL record can rebind to an internal IP between validation and connection. For high-risk surfaces, resolve once and connect to the pinned IP, or put a filtering agent in front (request-filtering-agent / ssrf-req-filter).

Input Validation Patterns

Schema Validation at Boundaries

import { z } from 'zod';

const CreateTaskSchema = z.object({
  title: z.string().min(1).max(200).trim(),
  description: z.string().max(2000).optional(),
  priority: z.enum(['low', 'medium', 'high']).default('medium'),
  dueDate: z.string().datetime().optional(),
});

// Validate at the route handler
app.post('/api/tasks', async (req, res) => {
  const result = CreateTaskSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(422).json({
      error: {
        code: 'VALIDATION_ERROR',
        message: 'Invalid input',
        details: result.error.flatten(),
      },
    });
  }
  // result.data is now typed and validated
  const task = await taskService.create(result.data);
  return res.status(201).json(task);
});

File Upload Safety

// Restrict file types and sizes
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const MAX_SIZE = 5 * 1024 * 1024; // 5MB

function validateUpload(file: UploadedFile) {
  if (!ALLOWED_TYPES.includes(file.mimetype)) {
    throw new ValidationError('File type not allowed');
  }
  if (file.size > MAX_SIZE) {
    throw new ValidationError('File too large (max 5MB)');
  }
  // Don't trust the file extension — check magic bytes if critical
}

Triaging Dependency Audit Results

Package-manager audits report known advisories; they do not prove a package is trustworthy or that vulnerable code is reachable. Use this decision tree:

The native package-manager audit reports a vulnerability
├── Severity: critical or high
│   ├── Is the vulnerable code reachable in runtime, build, test, or deployment paths?
│   │   ├── YES --> Fix immediately (update, patch, or replace the dependency)
│   │   └── NO (confirmed unused across those paths) --> Fix soon, but not a blocker
│   └── Is a fix available?
│       ├── YES --> Update to the patched version
│       └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date
├── Severity: moderate
│   ├── Reachable in production? --> Fix in the next release cycle
│   └── Dev-only? --> Fix when convenient, track in backlog
└── Severity: low
    └── Track and fix during regular dependency updates

Key questions:

  • Is the vulnerable function actually called in your code path?
  • Is the dependency a runtime dependency or dev-only?
  • Is the vulnerability exploitable given your deployment context (e.g., a server-side vulnerability in a client-only app)?

When you defer a fix, document the reason and set a review date.

Supply-Chain Hygiene

Do not assume npm or treat the nearest manifest as the install root. Apply this order:

  1. Find the installation boundary and manager. Use the workspace root that owns the lockfile, or an independent nested project only when it is outside that workspace. There, corroborate packageManager (when present), the lockfile, and CI; stop on disagreement or competing lockfiles. Pin the manager version and use the matrix in references/security-checklist.md.
  2. Block dependency scripts before first execution. Bootstrap with scripts disabled or a documented fail-closed policy, inspect the pending script source, approve only the minimum required packages, commit the policy, then verify with a clean frozen/immutable install. Never blanket-approve scripts.

Audits only find known advisories; they do not catch a newly malicious or typosquatted package. Therefore:

  • Never apply forced audit remediation automatically (npm audit fix --force or equivalent). Preview the remediation, read changelogs, and test each resulting upgrade; forced fixes may cross declared dependency ranges.
  • Verify registry signatures and provenance where supported (npm audit signatures, pnpm audit signatures) and treat absence as a signal to investigate, not automatic proof of compromise.
  • Review new dependencies, lockfile diffs, and script-policy changes together — ownership, maintenance, release age, provenance, transitive graph, and typosquats such as cross-env vs crossenv (OWASP A06, LLM03).

Rate Limiting

import rateLimit from 'express-rate-limit';

// General API rate limit
app.use('/api/', rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100,                   // 100 requests per window
  standardHeaders: true,
  legacyHeaders: false,
}));

// Stricter limit for auth endpoints
app.use('/api/auth/', rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 10,  // 10 attempts per 15 minutes
}));

Secrets Management

.env files:
  ├── .env.example  → Committed (template with placeholder values)
  ├── .env          → NOT committed (contains real secrets)
  └── .env.local    → NOT committed (local overrides)

.gitignore must include:
  .env
  .env.local
  .env.*.local
  *.pem
  *.key

Always check before committing:

# Check for accidentally staged secrets
git diff --cached | grep -i "password\|secret\|api_key\|token"

If a secret is ever committed, rotate it. Deleting the line or rewriting history is not enough — assume it's compromised the moment it reaches a remote. Revoke and reissue the key first, then purge it from history.

Securing AI / LLM Features

If your app calls an LLM — chatbots, summarizers, agents, RAG — it inherits a new attack surface. Map it to the OWASP Top 10 for LLM Applications (2025):

  • Treat all model output as untrusted input (LLM05: Improper Output Handling). Never pass LLM output straight into eval, SQL, a shell, innerHTML, or a file path. Validate and encode it exactly as you would raw user input.
  • Assume prompts can be hijacked (LLM01: Prompt Injection). Untrusted text in the context window — a user message, a fetched web page, a PDF — can carry instructions. The system prompt is not a security boundary; enforce permissions in code, not in the prompt.
  • Keep secrets and other users' data out of prompts (LLM02 / LLM07). Anything in the context can be echoed back. Don't put API keys, cross-tenant data, or the full system prompt where the model can repeat it.
  • Constrain tool and agent permissions (LLM06: Excessive Agency). Scope tools to the minimum, require confirmation for destructive or irreversible actions, and validate every tool argument.
  • Bound consumption (LLM10: Unbounded Consumption). Cap tokens, request rate, and loop/recursion depth so a crafted input can't run up cost or hang the system.
  • Isolate retrieval data (LLM08: Vector and Embedding Weaknesses). In RAG, treat the vector store as a trust boundary: partition embeddings per tenant so one user can't retrieve another's data, and validate documents before indexing so poisoned content can't steer answers.
// BAD: trusting model output as a command or as markup
const sql = await llm.generate(`Write SQL for: ${userQuestion}`);
await db.query(sql);                                   // arbitrary query execution
container.innerHTML = await llm.reply(userMessage);   // stored XSS, via the model

// GOOD: model output is data — parse defensively, then validate, then encode
let intent;
try {
  intent = CommandSchema.parse(JSON.parse(await llm.replyJson(userMessage)));
} catch {
  throw new ValidationError('unexpected model output'); // JSON.parse or schema failed
}
await runAllowlistedAction(intent.action, intent.params);
container.textContent = await llm.reply(userMessage);

Security Review Checklist

### Authentication
- [ ] Passwords hashed with bcrypt/scrypt/argon2 (salt rounds ≥ 12)
- [ ] Session tokens are httpOnly, secure, sameSite
- [ ] Login has rate limiting
- [ ] Password reset tokens expire

### Authorization
- [ ] Every endpoint checks user permissions
- [ ] Users can only access their own resources
- [ ] Admin actions require admin role verification

### Input
- [ ] All user input validated at the boundary
- [ ] SQL queries are parameterized
- [ ] HTML output is encoded/escaped
- [ ] Server-side URL fetches are allowlisted (no SSRF to internal services)

### Data
- [ ] No secrets in code or version control
- [ ] Sensitive fields excluded from API responses
- [ ] PII encrypted at rest (if applicable)

### Infrastructure
- [ ] Security headers configured (CSP, HSTS, etc.)
- [ ] CORS restricted to known origins
- [ ] Dependencies audited for vulnerabilities
- [ ] Error messages don't expose internals

### Supply Chain
- [ ] One authoritative lockfile committed; CI uses that manager's frozen/immutable install
- [ ] Native audit triaged by reachability and fix risk; dependency install scripts blocked unless explicitly approved
- [ ] New dependencies reviewed (ownership, provenance, release age, transitive graph)

### AI / LLM (if used)
- [ ] Model output treated as untrusted (no eval/SQL/innerHTML/shell)
- [ ] Secrets and other users' data kept out of prompts
- [ ] Tool/agent permissions scoped; destructive actions require confirmation

See Also

For detailed security checklists and pre-commit verification steps, see references/security-checklist.md.

Common Rationalizations

RationalizationReality
"This is an internal tool, security doesn't matter"Internal tools get compromised. Attackers target the weakest link.
"We'll add security later"Security retrofitting is 10x harder than building it in. Add it now.
"No one would try to exploit this"Automated scanners will find it. Security by obscurity is not security.
"The framework handles security"Frameworks provide tools, not guarantees. You still need to use them correctly.
"It's just a prototype"Prototypes become production. Security habits from day one.
"Threat modeling is overkill here"Five minutes of "how would I attack this?" prevents the design flaws no control can patch later.
"It's just LLM output, it's only text"That "text" can be a SQL statement, a script tag, or a shell command. Treat it like any untrusted input.
"The audit passed, so the dependency is safe"Audits match known advisories. They do not detect a newly malicious package or make unreviewed install scripts safe to execute.

Red Flags

  • User input passed directly to database queries, shell commands, or HTML rendering
  • Secrets in source code or commit history
  • API endpoints without authentication or authorization checks
  • Missing CORS configuration or wildcard (*) origins
  • No rate limiting on authentication endpoints
  • Stack traces or internal errors exposed to users
  • Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts
  • Server fetches user-supplied URLs without an allowlist (SSRF)
  • LLM/model output passed into a query, the DOM, a shell, or eval
  • Secrets, PII, or the full system prompt placed inside an LLM context window

Verification

After implementing security-relevant code:

  • The native audit has no unmitigated reachable critical/high findings; CI preserves the authoritative lockfile and blocks unreviewed dependency scripts
  • No secrets in source code or git history
  • All user input validated at system boundaries
  • Authentication and authorization checked on every protected endpoint
  • Security headers present in response (check with browser DevTools)
  • Error responses don't expose internal details
  • Rate limiting active on auth endpoints
  • Server-side URL fetches validated against an allowlist (no SSRF)
  • LLM/model output validated and encoded before use (if AI features present)

发现问题?提交给管理员复核

评分:

评论 (0)

暂无评论,成为第一个评论者吧!