AGENT SKILL

ts-security

ACTIVATE when conducting security assessments, code review for vulnerabilities, or CVSS scoring in TypeScript/Node.js/NestJS projects. ACTIVATE for 'security audit', 'vulnerability', 'injection', 'XSS', 'OWASP' in a TS context. Provides TS/NestJS-specific security patterns (Drizzle parameterized queries, JWT setup, bcrypt rounds, execFile over exec, path traversal, Zod env validation, CSRF). Loads alongside security-audit:security-audit (comprehensive baseline) and audit:security-overrides (personal conventions). DO NOT use for: general code quality, performance optimization, authentication flow design.

License 许可
MIT
最近更新
2026-10-13
Stars
★ 9
Forks
2

01 前言 Front Matter

name
ts-security
description
ACTIVATE when conducting security assessments, code review for vulnerabilities, or CVSS scoring in TypeScript/Node.js/NestJS projects. ACTIVATE for 'security audit', 'vulnerability', 'injection', 'XSS', 'OWASP' in a TS context. Provides TS/NestJS-specific security patterns (Drizzle parameterized queries, JWT setup, bcrypt rounds, execFile over exec, path traversal, Zod env validation, CSRF). Loads alongside security-audit:security-audit (comprehensive baseline) and audit:security-overrides (personal conventions). DO NOT use for: general code quality, performance optimization, authentication flow design.

03 SKILL.md 正文

Security — TypeScript / Node.js Examples

Part of the audit overlay pattern. Companion skills:

  • security-audit:security-audit (upstream baseline — OWASP/CWE/CVSS, 61 references)
  • audit:security-overrides (personal conventions: stack scope, FP filters, output format)

This skill provides TS-specific code examples for the patterns the upstream covers conceptually.

Standards

  • OWASP Top 10 (2021)
  • CWE Top 25 (2025)
  • CVSS v3.1 / v4.0 for risk scoring

SQL Injection Prevention

Always use Drizzle parameterized queries. Never interpolate user input into SQL.

// ❌ AVOID - String interpolation in SQL
const result = await db.execute(
  `SELECT * FROM tenants WHERE email = '${email}'`
);

// ✅ CORRECT - Drizzle parameterized query
const result = await db
  .select()
  .from(tenants)
  .where(eq(tenants.email, email));

// ✅ CORRECT - Raw SQL with placeholder
import { sql } from 'drizzle-orm';
const result = await db.execute(
  sql`SELECT * FROM tenants WHERE email = ${email}`
);

XSS Prevention

// ✅ React/JSX auto-escapes by default — safe
return <p>{userInput}</p>;

// ❌ AVOID - Bypasses auto-escaping
return <div dangerouslySetInnerHTML={{ __html: userInput }} />;

// ✅ CORRECT - If HTML rendering needed, sanitize first
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userInput);
return <div dangerouslySetInnerHTML={{ __html: clean }} />;

JWT Security

// ❌ AVOID - No expiration, weak secret
const token = jwt.sign(payload, 'secret');

// ✅ CORRECT - Strong secret, expiration, algorithm specified
const token = jwt.sign(payload, process.env.JWT_SECRET, {
  expiresIn: '1h',
  algorithm: 'HS256',
});

// ✅ CORRECT - Validate with explicit algorithms
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
  algorithms: ['HS256'],
});

Password Hashing

import * as bcrypt from 'bcrypt';

// ✅ CORRECT - bcrypt with sufficient rounds
const SALT_ROUNDS = 12;
const hash = await bcrypt.hash(password, SALT_ROUNDS);
const isValid = await bcrypt.compare(password, hash);

// ❌ AVOID - MD5, SHA-1, SHA-256 without salt
import { createHash } from 'crypto';
const hash = createHash('sha256').update(password).digest('hex');

Command Injection Prevention

// ❌ AVOID - Shell injection via child_process.exec
// exec(`convert ${userInput} output.png`);
// exec() spawns a shell, allowing injection via metacharacters

// ✅ CORRECT - execFile prevents shell injection (no shell involved)
import { execFile } from 'child_process';

execFile('convert', [userInput, 'output.png'], (error, stdout) => {
  // Arguments are passed as array, not interpolated into a shell command
});

Path Traversal Prevention

import { resolve, normalize } from 'path';

// ❌ AVOID - User input directly in path
const filePath = `./uploads/${req.params.filename}`;

// ✅ CORRECT - Normalize and verify containment
const UPLOAD_DIR = resolve('./uploads');
const requested = resolve(UPLOAD_DIR, req.params.filename);

if (!requested.startsWith(UPLOAD_DIR)) {
  throw new ForbiddenException('Path traversal detected');
}

Environment & Secrets

// ❌ AVOID - Secrets hardcoded
const API_KEY = 'sk-1234567890abcdef';

// ✅ CORRECT - From environment, validated at startup
import { z } from 'zod';

const EnvSchema = z.object({
  JWT_SECRET: z.string().min(32),
  DATABASE_URL: z.string().url(),
  API_KEY: z.string().min(16),
});

const env = EnvSchema.parse(process.env);

CSRF Protection

// ✅ NestJS - Use CSRF middleware for state-changing endpoints
// For API-only (JWT auth): CSRF is not needed (no cookies)
// For session-based auth: enable CSRF tokens

// ✅ SameSite cookies
response.cookie('session', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
});

Security Tooling

# Dependency audit
pnpm audit

# ESLint security rules
pnpm add -D eslint-plugin-security

# Snyk scanning
npx snyk test

Security Checklist

  • [ ] bcrypt (12+ rounds) for passwords
  • [ ] Drizzle parameterized queries everywhere (no string interpolation)
  • [ ] JWT with expiration, strong secret, explicit algorithm
  • [ ] No dangerouslySetInnerHTML without DOMPurify
  • [ ] execFile instead of exec for system commands
  • [ ] Path traversal check on all file operations
  • [ ] Secrets in environment variables, validated with Zod at startup
  • [ ] httpOnly, secure, sameSite: 'strict' on cookies
  • [ ] pnpm audit in CI pipeline
  • [ ] Security headers (HSTS, CSP, X-Content-Type-Options) via Helmet

Quick Reference

Vulnerability Mitigation
SQL Injection Drizzle queries, sql template tag
XSS JSX auto-escaping, DOMPurify if needed
JWT flaws Expiration, strong secret, explicit algorithm
Weak passwords bcrypt 12+ rounds
Command injection execFile (no shell)
Path traversal resolve + startsWith check
Secrets in code Env vars + Zod validation
CSRF SameSite cookies, CSRF tokens for sessions

04 同仓库更多 Skills

FabienSalles
FabienSalles/claude-marketplace

vitest-test-conventions

ACTIVATE when writing Vitest tests, creating test files, using vi.fn()/vi.mock()/vi.spyOn(), or test factories. ACTIVATE for 'Vitest', 'it.each', 'NestJS testing module', 'supertest', 'vi.fn', 'vi.mock', 'spyOn'. Provides Vitest/NestJS-specific testing patterns; cross-language testing principles (DAMP, AAA, spy over mock, what NOT to test) live in craft:testing-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), TDD workflow/iterations (see vitest:vitest-tdd-workflow), PHP/PHPUnit tests (see phpunit:php-test-conventions).

★ 9
FabienSalles
FabienSalles/claude-marketplace

vitest-tdd-workflow

ACTIVATE when building new features, endpoints, or user stories using TDD with Vitest in a TypeScript/NestJS context. ACTIVATE for '/feature-tdd-dev', 'TDD', 'red-green-refactor' in TS context. Provides Vitest/NestJS-specific TDD examples and commands; cross-language TDD workflow (cross-layer iterations, RED-GREEN-REFACTOR, working app, bug-fix-first-test, mocks-hiding-bugs) lives in craft:tdd-workflow-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), test writing conventions (see vitest:vitest-test-conventions), PHP TDD (see phpunit:php-tdd-workflow).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-refactoring

ACTIVATE when refactoring TypeScript code. ACTIVATE for 'refactor', 'extract', 'redesign', 'simplify', or 'clean up' in a TypeScript / Node / NestJS context. This skill provides TS-specific examples for the cross-language refactoring rules defined in craft:refactoring-principles. DO NOT use for: writing new features from scratch, general OOP patterns (see ts-oop).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-ports-adapters

ACTIVATE when a TypeScript codebase with no dependency-injection container has to declare a port and wire its adapter — a repository, a clock, an id generator, an event dispatcher the domain depends on. ACTIVATE for 'port', 'adapter', 'SPI', 'dependency inversion' or 'composition root' in a codebase that wires its dependencies by hand. Covers: the port as a type of functions in the domain layer, the adapter as an object literal annotated with it, the handler that takes its dependencies first and its data second, the composition root in the infrastructure layer, and the in-memory stub that substitutes for the adapter in a unit test. DO NOT use for: NestJS, or any container-based DI with decorators and tokens (see nest-ddd-conventions), aggregate operations and smart constructors (see ddd-ts-fp), the Result type itself (see ts-functional).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-oop

ACTIVATE when designing TypeScript classes, and the value objects or collections modelled as classes, or when the user asks about object design, encapsulation, Tell Don't Ask, or Symbol.iterator. Provides TS-specific examples for the cross-language OOP rules defined in craft:oop-principles, plus TS-specific patterns (Symbol.iterator, branded types for primitive identifiers). DO NOT use for: a value object or an aggregate modelled as an immutable record rather than a class (see ddd-ts-fp), refactoring methodology (see ts-refactoring).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-layer-boundaries

ACTIVATE when wiring a Worker entry point, a Router, a controller, or a domain event consumer in a TypeScript CQRS codebase, or when deciding where a port belongs. ACTIVATE for 'composition root', 'layer boundary', 'ESLint zones', 'domain must not import infrastructure'. Covers: the *Worker.ts composition root, the curried consumer, Router wiring of command endpoints, the five-gesture controller, the domain-to-infrastructure import boundary enforced by ESLint, infrastructure-only ports, in-memory doubles for every port, the read-can-reach-write asymmetry, and read endpoints going through a domain handler. DO NOT use for: the port's own shape and adapter binding (see ts-ports-adapters), the Result type (see ts-functional), domain event structure (see ts-ddd-events).

★ 9