Communitygithub.com

bucai2417/secure-system-development

Security and engineering red lines for designing, writing, or reviewing any website, backend, or API: hardened auth, injection prevention, business-logic and race-condition defense, high-concurrency database design, async-first architecture, API integrity and anti-tampering, secrets and operations, AI/LLM security, mobile and mini-program security, CORS and security headers, and scenario-aware 404 and indexing rules. 系统与网站开发的安全与工程红线:登录认证、注入与 XSS/CSRF/SSRF 防护、越权、业务逻辑与竞态、数据库高并发、异步架构、接口防抓包改包与重放、密钥运

secure-system-development 是什么?

secure-system-development is a Claude Code agent skill that security and engineering red lines for designing, writing, or reviewing any website, backend, or API: hardened auth, injection prevention, business-logic and race-condition defense, high-concurrency database design, async-first architecture, API integrity and anti-tampering, secrets and operations, AI/LLM security, mobile and mini-program security, CORS and security headers, and scenario-aware 404 and indexing rules. 系统与网站开发的安全与工程红线:登录认证、注入与 XSS/CSRF/SSRF 防护、越权、业务逻辑与竞态、数据库高并发、异步架构、接口防抓包改包与重放、密钥运.

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/bucai2417/secure-system-development/tree/HEAD

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Secure System Development Specification / 安全系统开发规范

If the runtime environment has a global asset prohibition (forbidding attacks/scans on certain owned assets), the global configuration takes precedence; this skill does not override it. For generic templates, see references/internal-policy.example.md (the release version contains no real internal addresses).

Usage

Read the "Red Line Checklist" before writing any code, and self-check after finishing. Read "Phase 1: Design" when designing or reviewing. When a specific module is involved, open the corresponding file under references/ as indicated by the pointer. Run the "Pre-Release Review" before committing. For runtime and zero-day situations, see "Phase 4: Runtime & 0-Day Mitigation".

If a task involves only one area (e.g., writing just a login endpoint, or designing just an orders table), read only that section and its corresponding reference. Do not memorize everything.

Executable Self-Check (Recommended to Run First)

python scripts/scan_redlines.py <target_directory> --format text            # Human-readable
python scripts/scan_redlines.py <target_directory> --format sarif --fail-on high   # CI blocking
python scripts/scan_redlines.py <target_directory> --code-only              # Skip docs, scan code only

Pure Python standard library, no installation dependencies required. Covers 18 rule categories including SQL injection via concatenation, innerHTML/eval, CORS wildcard and reflection, global fallback to homepage, hardcoded secrets, MD5 password storage, command injection, disabled certificate verification, debug toggles, sensitive fields in logs, and unvalidated upload paths. Results will point to the relevant reference.

False Positive Handling: Add a comment redline: ignore at the end of the line (ignores the entire line) or redline: ignore SQL001 (ignores only the specified rule). Do not disable an entire rule just to silence alerts—document the reason and explain during review.

Two templates are available: assets/threat-model-template.md (for design-time threat modeling) and assets/review-checklist.md (a pre-release checklist by project type).

1. Determine Project Type (Decides Which Rules Apply)

ScenarioTypical FormSecurity RulesIntegrity RequirementsIndexing (SEO)
Public SiteOfficial site, landing page, blog, docs, e-commerce frontendFull setLow (public content)Mandatory: real 404, sitemap, canonical, structured data
Logged-in ProductSaaS, tool site, community user-facing appFull set + complete account systemMedium (sensitive operations need signing)Only submit public pages (marketing/help center); private pages: noindex
Admin Paneladmin, operations backend, customer service/review systemFull set + separate entry point + MFA + audit logHigh (all write operations signed + audited)Prohibited: full site noindex + mandatory authentication
Internal/Personal SystemInternal platform, personal tools, script panel, home NASAuthentication + minimal exposure + rate limiting + timely updatesMedium (depending on exposure)Prohibited: do not place on public network default paths; do not rely on "obscurity" for security
Pure APIREST / GraphQL / Service-to-service callsAuthentication + input validation + rate limiting + version managementPer business (mandatory high for payments/funds)Not applicable (no pages generated)

There is only one determination question: Should this URL appear in search engines?

  • Yes → Execute as a public site; all SEO chapter rules apply.
  • No → Execute "Prohibit Indexing": full site X-Robots-Tag: noindex, robots block crawling, mandatory authentication. Do not apply SEO optimizations (sitemap, canonical, structured data) to admin panels or internal systems—it's wasteful and exposes attack surface.
  • Regardless of the scenario, return a true 404 for non-existent paths must be followed—it's HTTP correctness, not just SEO.

2. Five Fundamental Principles

  1. All Input is Untrusted: URL, query, body, header, cookie, uploaded files, webhooks, message queues, third-party API responses, and even historical dirty data in databases.
  2. Fail Closed by Default: When authentication/validation/parsing fails, return a rejection, not a grant; exceptional paths must not reach a "skip validation" branch.
  3. Least Privilege: Database accounts should be scoped by function (read/write separation, no DDL), cloud IAM/object storage by prefix, processes run as non-root, container filesystems read-only.
  4. Defense in Depth: When one layer fails, the next is still active. Frontend validation is for user experience; server-side validation is security. WAF is a safety net, not a replacement.
  5. Limit Blast Radius: Zero-days cannot be prevented by code conventions. Mitigate via isolation, privilege restriction, outbound allowlisting, and a fast patch channel to minimize damage.

3. Red Line Checklist (Mandatory, Self-Check Each Item)

Authentication & Sessions

  • Passwords hashed with Argon2id/bcrypt(cost≥12)/scrypt; prohibit MD5/SHA1/reversible encryption
  • Login failure rate limiting on both account+IP dimensions, with progressive delay, CAPTCHA/temporary lockout when necessary
  • Response text and timing consistent for login/registration/password reset; do not reveal if an account exists
  • Rotate session ID after successful login (prevent session fixation); Cookies set with HttpOnly + Secure + SameSite
  • JWT: fixed algorithm allowlist on the server; reject alg:none and algorithm confusion; short expiry + refresh rotation + revocability
  • Authentication ≠ Authorization: Explicitly check at each endpoint if the current user can operate on the specific object (prevent IDOR/privilege escalation)

Injection & Output

  • All SQL uses parameterized queries or ORM binding; prohibit string concatenation; table names/sort columns use allowlist mapping
  • Prohibit concatenating user input into shell/commands; use execFile series with parameter arrays
  • Output encode based on context; dangerouslySetInnerHTML/v-html/innerHTML must pass through a sanitizer like DOMPurify
  • Rich text, Markdown, URL parameters: always allowlist; do not trust any frontend filtering
  • Outbound requests (SSRF): allowlist only; do not follow arbitrary redirects; block internal/metadata addresses (169.254.169.254, 127.0.0.1, 10/8, 172.16/12, 192.168/16, ::1, file://, gopher://)
  • File paths: validate prefix after path.resolve; reject ..; uploaded files: random naming, MIME-type sniffing, isolated storage, no execution permissions

Data & Concurrency

  • Core write operations are idempotent (unique index / idempotency key); ordering, payment, callbacks must be idempotent
  • Stock, balance, usage counter fields: use conditional update UPDATE ... WHERE remaining >= ?; prohibit read-then-write
  • Transactions are short; do not perform network calls, send messages, or render templates inside a transaction
  • All new queries must have an EXPLAIN plan; prohibit large OFFSET pagination, SELECT *, and N+1 queries
  • Monetary values use integer cents or DECIMAL; prohibit float/double

Async & Stability

  • All external calls (HTTP/DB/Redis/MQ) have explicit timeouts; prohibit infinite waits
  • Retries only for idempotent operations; exponential backoff + jitter + max retry count
  • Message consumption is idempotent (message_id deduplication table); failures go to DLQ with alerting
  • Persist critical state changes to the database before sending messages (Outbox / transactional outbox); prohibit dual writes

Business Logic & Race Conditions (Most Frequently Overlooked)

  • Prices, amounts, discounts, permission levels: always calculated server-side; client-submitted values are display-only
  • Coupons/redeem codes/invitation codes: bind to user and usage count; atomic redemption (conditional update or unique constraint)
  • State machine: explicit transitions; illegal transitions rejected (e.g., pending bypassing payment callback to become paid)
  • Payment/fund/callback endpoints: validate signature + timestamp + idempotency key; prevent replay and forgery
  • Purchase limits, rate limits: judge by user + device + IP combination; cannot be bypassed by only one dimension
  • Export, batch, search endpoints: rate limited + data volume cap + audit trail

Secrets & Operations

  • Secrets only in environment variables or a secrets management service; prohibit them in code repositories, Docker image layers, frontend bundles, logs, and error reports
  • CI/CD credentials with least privilege; production deployments require approval; third-party dependencies: lock version + scan
  • Sensitive operations (login, permission change, export, delete, refund): write audit logs that cannot be tampered with by application code

API Integrity (Anti-Packet-Capture, Anti-Tampering, Anti-Replay, Anti-Forgery)

  • Sensitive requests (payment, funds, authorization, password change) use signing: HMAC(secret, method+path+sortedQuery+sha256(body)+timestamp+nonce); server recalculates
  • Nonce storage for deduplication (TTL = time window); time window ±300s; reject expired and replayed nonces
  • Sensitive responses (payment result, authorization result, balance) include server-side signature; client validates; but the ultimate truth is always re-verified server-side
  • Any "validated" flag, price, or role submitted by the client is not a source of truth; server must recalculate/re-verify
  • Mobile: certificate pinning; release builds must not trust user certificates; debug and packet capture toggles must be disabled
  • Client-side hardening (obfuscation/anti-debugging) only raises the cost of attack, not a security boundary; keys must not be sent to the client

AI / LLM Applications

  • Model output is treated as untrusted input: do not eval, do not directly concatenate into HTML/SQL/commands, do not directly execute tool arguments
  • Tool/function calls: least privilege + parameter schema validation + human confirmation for high-risk actions
  • Documents retrieved by RAG are treated as untrusted content, isolated from system prompts, to prevent indirect prompt injection
  • System prompts and user input are separated; do not place secrets or internal rules in positions that can be extracted via prompt injection
  • Rate limit per user/tenant based on cost and frequency; log sanitization (do not record sensitive data from full prompts)

Mobile / Mini-Programs

  • Sensitive data stored in Keychain (iOS) / Keystore (Android); prohibit plaintext SharedPreferences
  • Transport forced TLS with certificate pinning; InsecureSkipVerify/verify=False is strictly prohibited
  • WebView: disable file access and JS bridge exposure surface; onShouldStartLoadWithRequest with domain allowlist
  • Mini-program session_key only used server-side; never sent to the frontend; issue your own session after code2session
  • Root/jailbreak detection only as a risk signal, not as an authentication basis

HTTP & Routing (All Scenarios)

  • Non-existent paths return a real HTTP 404 with a 404 page; prohibit 302/200 redirect to homepage
  • SPA history fallback only applies to known frontend routes; /api and static resources with extensions always return 404
  • CORS: use exact Origin allowlist; prohibit Access-Control-Allow-Origin: * with credentials; prohibit echoing any Origin back
  • Production: enable security response headers: HSTS, CSP, X-Content-Type-Options, Referrer-Policy, frame-ancestors
  • Authentication/sensitive endpoint responses include Cache-Control: no-store
  • Error responses: do not return stack traces, SQL, framework versions, or internal paths

Indexing (Public Sites Only; Admin/Internal Systems Do the Opposite)

  • Public site: sitemap lists only 200 pages; canonical deduplication; robots does not leak admin paths; staging environment: full site noindex
  • Admin/Internal/Personal systems: full site X-Robots-Tag: noindex + robots Disallow: /; do not generate a sitemap; and require authentication (robots.txt is not access control)

Phase 1: Design Time

Spend 5 minutes on a lightweight threat model before starting:

  1. Define the scenario: Refer to the project type table above. Confirm if it's a public site, admin panel, internal system, or API. Decide whether to execute the SEO chapter and what the attack surface is.
  2. Draw the data flow: User → Gateway → Service → Database/Cache/MQ/Third Party. Mark every cross-trust-boundary point.
  3. List and classify assets: Accounts, credentials, payments, personal data, admin panel. For each, ask: "Who can read it? Who can write it? What is the impact of tampering? How long should it be retained?"
  4. At each boundary, ask three questions: Who can reach it? Is the input validated? Does failure result in a default deny?
  5. Define the authorization model: Role → Resource → Action; enforce server-side; hiding buttons on the frontend does not count. For multi-tenant systems, additionally define isolation policies.
  6. Define async boundaries: Which operations must be synchronous (login, payment confirmation) and which can be asynchronous (notifications, reports, exports).

Design documents must at least specify: project type & indexing strategy, authentication method, authorization model, sensitive data classification & encryption, rate limiting strategy, idempotency keys, graceful degradation on failure, and log/audit scope.

Phase 2: Implementation

Authentication & Login (Highest Priority)

Login is the most common entry point for brute force, credential stuffing, and bypass attacks. Full rules in references/auth-and-session.md. Core non-negotiables:

  • Layered rate limiting: per IP, per account, per device fingerprint; use Redis expiring keys for failure counters; do not rely solely on in-memory state.
  • Unify error messages to "Incorrect account or password"; align response time (even if the account does not exist, run a fake hash to prevent timing enumeration).
  • After successful login, regenerate the session identifier; invalidate old sessions.
  • Sensitive operations (password change, binding change, withdrawal, delete) require secondary verification or check the time since last authentication (re-auth window).
  • Password reset token: high entropy, one-time, short TTL (≤15 minutes), bound to the user and purpose.
  • Admin panel: separate entry point, separate domain or IP allowlist; do not share sessions with the user-facing side.

Input, Injection & Output

See references/web-vulnerability-prevention.md. Principle: Unified input validation (schema), context-aware output encoding.

// Input: validate with schema; reject unknown fields instead of "taking what's needed"
const LoginBody = z.object({ email: z.string().email(), password: z.string().min(8).max(128) }).strict();

// SQL: parameterized; never concatenate
await db.query('SELECT id, password_hash FROM users WHERE email = $1', [email]);
// For positions that cannot be parameterized (ORDER BY, table names): use allowlist
const orderBy = { created_at: 'created_at', amount: 'amount_cents' }[sort] ?? 'created_at';
  • XSS: React/Vue default escaping is sufficient; dangerous APIs must be sanitized; CSP as a second line of defense.
  • IDOR: Include owner_id = $currentUser in query conditions; do not "query all then filter on the frontend".
  • Deserialization/Template injection: no eval; do not concatenate user input into templates/expressions/regex.
  • Upload: limit size and type (detect by magic bytes), use random filenames, store in object storage, re-encode images.

Database & High Concurrency

See references/database-concurrency.md. Key points:

  • Indexes before optimization: run EXPLAIN on new queries before deployment; watch for type=ALL, filesort, temporary tables.
  • Pagination: use cursor (keyset), not deep OFFSET; list endpoints must have a stable sort order and an upper limit.
  • Hotspot writes: use "conditional update + row lock". Stock deduction example:
UPDATE sku SET stock = stock - $1, version = version + 1
WHERE id = $2 AND stock >= $1;
-- Affected rows = 0 → insufficient stock or concurrency conflict; retry or fail per business logic
  • Cache triad: prevent penetration (empty-value cache / Bloom filter), prevent hotkey breakdown (mutex lock / single-flight), prevent avalanche (add random jitter to TTL).
  • Connection pool upper limit must be less than database max_connections divided by number of instances; configure acquisition timeouts.
  • Revisit sharding/partitioning only when scale demands it; first do indexes, caching, read replicas, hot/cold data separation.

Business Logic & Race Conditions

See references/business-logic-and-race-conditions.md. This type of vulnerability has no universal scanner; it must be thought through one item at a time during design: prices/amounts calculated server-side, coupon atomic redemption, state machine validation, replay prevention, multi-dimensional purchase limits, export rate limiting. All concurrent "read-then-write" patterns must be converted to conditional updates or locking + idempotency.

Async-First Architecture

See references/async-architecture.md. The system defaults to async design:

  • All I/O is non-blocking; in Node.js, prohibit synchronous fs/crypto and CPU-heavy operations on the request path (use worker_threads).
  • Every external call must have a timeout; propagate trace IDs across the call chain.
  • Queue consumption = at-least-once delivery, so consumption must be idempotent; retries have an upper limit; exceed → DLQ + alert.
  • Cross-service consistency: use Outbox/CDC; do not perform dual writes.
  • Long tasks (exports, batch, reviews): enqueue, immediately return a task ID to the frontend; frontend polls or uses SSE for status pushes.
  • Graceful shutdown: stop accepting new requests → await in-flight completions → close queue consumers → close connections.

HTTP, Routing, CORS & SEO

See references/http-routing-cors-seo.md. The three most common pitfalls:

  1. 404 must be truly 404. Do not globally fallback to the homepage: SPA only falls back to index.html for known build-time routes; /api/* and paths with extensions return 404 directly.
  2. CORS with an exact allowlist: Compare the Origin to the configured value as a set equality; do not use includes, prefix matching, or directly echo the request header.
  3. Correct status codes: 401 for unauthenticated, 403 for unauthorized, 404 for not found, 409 for conflict, 422 for validation failure, 429 for rate limited.

SEO applies only to public sites; for admin panels and internal systems, follow the "Prohibit Indexing" rules in the scenario table above. Do not add sitemaps, canonical, or structured data to them—that gives crawlers an attack surface.

Secrets, Operations & Email

See references/operations-and-secrets.md. Key points: layered secret storage and rotation; CI/CD least privilege; containers as non-root; object storage and cloud IAM minimalization; tamper-proof audit logs; email domain SPF/DKIM/DMARC configuration to prevent forgery; data retention and deletion procedures.

API Integrity & Anti-Tampering

See references/api-integrity-and-tampering.md. Packet capture and tampering is the #1 problem for mobile apps and open APIs: request signing (HMAC + timestamp + nonce + body hash), server-side recalculation, signed sensitive responses, nonce deduplication, time windows, certificate pinning. Remember: everything the client can modify is untrustworthy; signing only raises the barrier; server-side recalculation is the truth.

AI / LLM Security

See references/ai-llm-security.md. Model output is equivalent to external input: do not execute, do not concatenate directly, do not use as SQL/commands; tool calls require least privilege + schema validation + human confirmation for high-risk actions; RAG content is untrusted; rate limit per tenant to control cost.

Mobile & Mini-Programs

See references/mobile-and-miniprogram.md. Keychain/Keystore, certificate pinning, WebView hardening, mini-program session_key not sent to the frontend, root detection as a signal only.

Phase 3: Pre-Release Review

Go through in order; mark any "unsure" item as failed:

  1. Red line checklist 100% checked. Then cross-check by project type: public site checks SEO items; admin/internal system checks noindex and entry isolation; sensitive business checks API integrity.
  2. Run python scripts/scan_redlines.py <directory> --fail-on high; high-severity findings must be zeroed out.
  3. Dependency scanning (npm audit / pip-audit / govulncheck / OWASP Dependency-Check); high-severity vulnerabilities must be addressed.
  4. Secrets check: no secrets in the repository, image, logs, or frontend bundle; .env must not be version-controlled; CI logs must also be checked.
  5. Container/host: non-root user, read-only root filesystem, minimal port exposure, outbound allowlist.
  6. Monitoring and alerting: login failure rate, 5xx errors, queue backlogs, slow queries, abnormal outbound requests.
  7. Backup and recovery drill; database accounts with least privilege.
  8. Load test critical paths (login, order, list) to confirm rate limiting and caching are effective.
  9. Email domain: SPF/DKIM/DMARC configured, sending endpoint rate limited, to prevent abuse for phishing or being blacklisted as a spam source.
  10. Data lifecycle: define minimum collection, retention period, export & deletion procedure; sanitize logs before retention.
  11. Incident response plan: who is responsible, how to isolate, how to notify users, how to conduct post-mortem.
  12. Compliance mapping (if needed): check against OWASP/ASVS/等保/PIPL items using references/compliance-mapping.md.

Phase 4: Runtime & Zero-Day Mitigation

Code conventions cannot prevent unknown vulnerabilities. Mitigate impact using the following:

  • Outbound traffic: default deny + allowlist (first wall against SSRF and supply-chain callbacks).
  • Critical services: sandbox/container isolation, process privilege reduction, seccomp/AppArmor as needed.
  • Dependency lock + fast image rebuild process; monitor security advisories and reserve an emergency patch channel.
  • WAF/gateway: generic signature blocking and rate limiting, but do not rely on it exclusively.
  • Behavioral monitoring: abnormal login geo/device changes, batch reads/writes, abnormal outbound traffic.
  • Data classification: encrypt sensitive fields at rest (AES-GCM/KMS), sanitize logs, require approval for exports.

References Index

FileWhen to Read
references/auth-and-session.mdLogin, registration, passwords, JWT, 2FA, password reset, CSRF, IDOR, admin panel
references/web-vulnerability-prevention.mdSQL injection, XSS, SSRF, file upload, path traversal, deserialization, response headers, API-specific risks
references/business-logic-and-race-conditions.mdPrices/amounts, coupons, inventory, state machines, TOCTOU race conditions, purchase limits, export abuse
references/database-concurrency.mdTable design, indexes, transactions, locks, idempotency, caching, read replicas, sharding
references/async-architecture.mdTimeouts, retries, queue consumption, Outbox, backpressure, graceful shutdown, observability
references/http-routing-cors-seo.md404, status codes, CORS, caching, robots/sitemap, indexing separation for public vs. admin sites
references/operations-and-secrets.mdSecrets, CI/CD, containers/cloud, email domains, audit logs, data lifecycle, incident response
references/api-integrity-and-tampering.mdPacket capture/tampering, request/response signing, replay protection, certificate pinning, client hardening boundaries
references/ai-llm-security.mdPrompt injection, tool call permissions, RAG poisoning, model output handling, cost rate limiting
references/mobile-and-miniprogram.mdLocal storage, certificate pinning, WebView, mini-program login state, root detection
references/compliance-mapping.mdOWASP Top 10 / ASVS / 等保 2.0 / PIPL mapping, for audit or review presentations
references/internal-policy.example.mdWhen a custom asset prohibition template is needed (placeholder domain, no real addresses)

Delivery Conventions

  • In every code delivery, include a 3–6 line summary of the security decisions made for that iteration (validation points, authorization points, idempotency keys, rate limiting, error handling). Do not skip this.
  • First specify the project type: if delivering an admin panel or internal system, explicitly state "No SEO, full site noindex". Only public sites get indexing-related configurations.
  • When existing code violates a red line, point out the exact location and provide a fix; do not just say "consider hardening".
  • For parts that cannot be verified (e.g., not having actually executed an attack test), explicitly state "Not verified"; do not claim the code has passed security testing.

相关技能