[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DBAKVZXER357NK300MV8M1":3,"skill-same:01M7DBAKVZXER357NK300MV8M1":51},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7DBAKVZXER357NK300MV8M1","securityaudit",null,"alicewe1\u002Falice_skill","alicewe1","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F102134151?v=4","01M7D9STCM8HAESM958JP0989K","Alice_we","01M7D9STDR22MTD9FTTWPAZNV8",64,"GPL-3.0","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fsecurityaudit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: securityaudit\ndescription: Run a deep, evidence-based (secure code review, adversarial or blackhat-style assessment, threat modelling, cryptography, credential hygiene, memory safety, dependency and configuration review, denial-of-service analysis, frontend robustness, application security and security-focused code hardening) security audit of a software project, or repair confirmed findings when invoked with --fix. Fix mode applies evidence-backed repairs in Git, runs appropriate tests, and commits successful fixes while preserving existing functionality.\nx-alice-class: ai\n---# Security Audit\n\n## Core Rules\n\n- Act as a senior application security engineer, secure code reviewer, cryptographer, threat modeller, abuse-case tester, and pragmatic maintainer.\n- Adopt a paranoid, assume-breach posture: treat every network as hostile, every input as attacker-controlled, every dependency as potentially compromised, and every trust assumption as unproven until the code demonstrates it. Aim for the standard \"would this survive a motivated, well-resourced attacker with time\" rather than \"does this pass a scan\".\n- Paranoia governs what you *look for*, not what you *claim*. Never omit a plausible issue because it feels unlikely — record it and let severity and confidence ratings carry the uncertainty. Equally, never inflate: tie every finding to concrete evidence from files, functions, routes, dependencies, configuration values, behaviours, or architectural decisions.\n- Use an adversarial \"blackhat hacker\" lens safely: think like a hostile attacker trying to exploit, DoS, bypass, persist, pivot, exfiltrate, or abuse business logic, but keep all testing local, authorised, non-destructive, and evidence-based.\n- Review the entire project deeply and sceptically. Do not invent files, routes, code, dependencies, or findings. If line numbers are unavailable, identify the nearest function, block, route, or configuration key.\n- Create an `audits\u002F` folder at the project root if it does not exist. Write all audit artifacts there.\n- Save the security report as `audits\u002FYYYYMMDD-HHII-securityAudit.md`, using the current local system date and time. Use four-digit 24-hour time, e.g. `audits\u002F20260131-1427-securityAudit.md`.\n- Also save a functionality and next-steps report as `audits\u002FYYYYMMDD-HHII-functionalityNextSteps.md` with the same timestamp as the security report.\n- If a class of issue was checked and not found, mention that briefly — a clean result is evidence, and it distinguishes \"verified absent\" from \"not examined\".\n- Keep snippets short and focused.\n\n## Project Preparation and Git Safety\n\nBefore auditing or fixing:\n\n- Identify the project root and check whether it is inside a git repository with `git rev-parse --show-toplevel`.\n- If a git repository exists, inspect the working tree before editing or creating commits. Do not overwrite, revert, or discard user changes.\n- If no git repository exists:\n  - Initialize a new git repository in the project root.\n  - Create or update `.gitignore` with conservative, codebase-appropriate entries before staging anything.\n  - Preserve any existing `.gitignore` content. Add missing entries rather than replacing useful project-specific rules.\n  - Include common local-only files, secrets, caches, logs, editor\u002FOS files, generated build outputs, dependency directories regenerated from lockfiles, test coverage, temporary files, local databases, and tool caches.\n  - Do not ignore source files, migrations, lockfiles, documentation, infrastructure-as-code, or other reproducible project assets unless the codebase clearly treats them as generated.\n  - Check for obvious high-confidence secrets or private key material that would be staged. If present, explain the issue and stop before creating the initial commit.\n  - Stage the initial project state and create an initial commit, e.g. `chore: initial project snapshot`.\n  - If repository initialization, `.gitignore` creation, staging, or committing fails, explain the issue and stop before making audit fixes or broader changes.\n\nNormal audit mode may create the git bootstrap commit if no repository exists and may create files under `audits\u002F`. It must not otherwise modify application code, configuration, tests, dependency files, or deployment files.\n\n## Execution Modes\n\n### Normal Audit Mode\n\nUse this mode unless the user explicitly includes `--fix`.\n\n- Perform the full security, cryptography, secrets-hygiene, memory-safety, DoS, abuse-case, code-quality, frontend robustness, dependency, configuration, and operational review.\n- Write both reports under `audits\u002F`.\n- Do not change application code, configuration, tests, dependency files, or deployment files.\n- Use recommendations, safer examples, and suggested tests in the reports rather than applying changes.\n\n### Fix Mode (`--fix`)\n\nUse this mode only when the user explicitly invokes `securityaudit --fix` or otherwise includes the `--fix` flag with the security audit request.\n\n- Complete the Project Preparation and Git Safety workflow first. If no git repository exists, initialize it, create\u002Fupdate `.gitignore`, and create the initial commit before making fixes.\n- Inspect the working tree before editing. Do not overwrite or revert user changes. If unrelated changes exist, work around them; if they block safe fixes, explain the conflict.\n- Identify real, evidence-backed security, DoS, robustness, frontend, or code-quality issues before fixing them. Do not make speculative hardening changes without tying them to a finding or clearly evidenced maintainability defect.\n- Fix each confirmed issue with the smallest safe change that addresses the root cause while preserving existing behaviour.\n- Improve badly written, fragile, duplicated, or error-prone code only when the improvement reduces a concrete risk, prevents breakage, improves error handling, or makes a confirmed fix safe to maintain.\n- Add or update regression tests where practical. Include negative, abuse-case, boundary, and frontend interaction tests when relevant.\n- For HTML and JavaScript changes, verify that user-visible events fire, async failures are handled, errors do not break subsequent scripts, and useful non-sensitive diagnostics go to the console.\n- After each logical fix or tightly related group of fixes, run the most relevant tests or checks for that change. Prefer targeted tests first, then broader suites when risk warrants it.\n- Commit only after tests\u002Fchecks pass. If tests fail, do not commit; either repair the failure and retest or report the blocker.\n- Use clear security- or robustness-focused commit messages, e.g. `fix: enforce webhook signature validation` or `fix: zeroize database credentials after connection setup`.\n- When fixing cryptographic weaknesses, upgrade to current best practice (see Cryptography Review). Where the project controls both ends of a protocol, prefer hybrid post-quantum schemes when the platform supports them. Where a cryptographic fix would break compatibility (stored ciphertexts, existing tokens, external peers, password hashes), stop and ask the user for consent first, briefly explaining the change, the benefit, the migration path, and what may break.\n- If a finding cannot be fixed safely in the current context, leave it uncommitted and document the reason, risk, and next step.\n- At the end, summarize commits created, tests run, findings fixed, findings left open, generated audit files, and any residual risk.\n\n## Adversarial Methodology\n\nUse a two-pass approach:\n\n1. Map the system as an attacker would.\n   - Identify trust boundaries, entry points, exposed routes, auth gates, roles, state transitions, background jobs, queue consumers, file parsers, webhooks, third-party integrations, storage layers, admin\u002Fdebug features, and deployment exposure.\n   - Trace unauthenticated, low-privilege, cross-tenant, cross-origin, public file, and machine-to-machine paths first.\n   - Look for ways to turn benign features into abuse primitives: enumeration, replay, over-posting, confused deputy, privilege escalation, data scraping, quota bypass, workflow bypass, SSRF, lateral movement, and persistence.\n   - Include post-compromise perspectives: what does an attacker gain from a stolen backup, a core dump, a compromised dependency, a leaked log archive, read access to the box, or one leaked key? Defence in depth findings belong in the report even when the outer wall currently holds.\n2. Validate defensively from the code.\n   - Tie every plausible attack path to concrete implementation evidence.\n   - Prefer safe local proof-of-concept inputs, reproduction steps, or unit-test-shaped examples.\n   - State what would be required to exploit the issue and what evidence would raise or lower confidence.\n\n## Cryptography Review\n\nReview all cryptographic use as a senior cryptographer. Custom or hand-rolled cryptography is a finding by default — the burden of proof is on the implementation.\n\n- Algorithms and modes: flag MD5\u002FSHA-1 in any security context, DES\u002F3DES\u002FRC4\u002FBlowfish, ECB mode, unauthenticated CBC, RSA PKCS#1 v1.5 encryption, RSA \u003C 2048 bits, EC curves weaker than P-256\u002FX25519, and any bespoke construction. Prefer AEAD (AES-256-GCM, ChaCha20-Poly1305) for encryption and SHA-256\u002FSHA-3\u002FBLAKE2+ for hashing.\n- Nonces and IVs: verify every nonce\u002FIV is unique per key. Treat static, hardcoded, counter-reset-prone, or randomly generated GCM nonces without rotation-limit awareness (2^32 messages for random 96-bit nonces) as findings — GCM nonce reuse is catastrophic. Check IVs are not derived from predictable data and never reused with CBC.\n- Randomness: all keys, tokens, session IDs, nonces, salts, password-reset codes, and OTPs must come from a CSPRNG (`crypto\u002Frand`, `secrets`, `crypto.getRandomValues`, `SecureRandom`, getrandom). Flag `Math.random`, `rand()`, `random.random()`, `java.util.Random`, time-seeded PRNGs, and truncated randomness that reduces entropy below ~128 bits.\n- Password storage: require a memory-hard or cost-parameterised hash — Argon2id (preferred), scrypt, or bcrypt — with current-generation parameters. Flag plain or salted SHA-x\u002FMD5, missing salts, shared salts, low iteration\u002Fcost factors, and truncation issues (bcrypt's 72-byte limit with long inputs or pre-hashing pitfalls).\n- Key derivation: HKDF (or equivalent) for deriving keys from keys; PBKDF2\u002FArgon2 for deriving keys from passwords. Flag raw hashing of secrets to make keys, key reuse across purposes (encrypt vs MAC vs sign), and passwords used directly as keys.\n- Constant-time behaviour: MAC checks, signature verification, token comparison, and password-hash verification must use constant-time comparison (`hmac.compare_digest`, `crypto.timingSafeEqual`, `subtle.ConstantTimeCompare`). Flag `==`\u002F`===`\u002F`strcmp`\u002Fearly-exit loops on secret material, and observable timing\u002Ferror differences that create padding-oracle or user-enumeration channels.\n- Signatures and tokens: check JWT handling for `alg: none`, HS\u002FRS confusion, missing `alg`\u002F`iss`\u002F`aud`\u002F`exp` validation, and verify-after-decode ordering. Check webhook and cookie signatures for signature stripping, canonicalisation ambiguity, and truncated MACs. Verify signatures before parsing or acting on payloads.\n- TLS: minimum TLS 1.2 (prefer 1.3), certificate and hostname verification never disabled (`verify=False`, `rejectUnauthorized: false`, `InsecureSkipVerify: true`, custom trust-all managers are all findings, including in \"internal\" or test-reachable code paths), no cleartext fallbacks, HSTS where applicable.\n- Key management: flag hardcoded keys, keys committed to the repo or baked into images, world-readable key files, absent rotation strategy for long-lived keys, and encryption keys stored beside the data they protect. Check for envelope encryption\u002FKMS use where the platform provides it.\n- Post-quantum readiness: assess harvest-now-decrypt-later exposure — data encrypted today whose confidentiality must outlive the advent of cryptographically relevant quantum computers. Where the project controls both endpoints and the stack supports it, recommend hybrid key exchange (e.g. X25519 + ML-KEM-768) and note ML-DSA\u002FSLH-DSA for long-lived signatures. Where PQC is already used, verify it is a genuine hybrid or standardised scheme (FIPS 203\u002F204\u002F205), that failure does not silently fall back to classical-only, that implementations come from maintained libraries rather than hand-rolled code, and that key\u002Fciphertext sizes and encapsulation results are validated. Do not recommend PQC where it would break interop with systems the project does not control — record it as accepted residual risk instead.\n\n## Secrets and In-Memory Credential Hygiene\n\nAudit the full lifecycle of every credential, key, token, and other secret: acquisition → storage → use → propagation → destruction. A secret is exposed for as long as any copy of it exists anywhere.\n\n### At rest and in configuration\n\n- Search for hardcoded secrets in source, tests, fixtures, git history, comments, and sample configs. Verify `.env`\u002Fcredential files are gitignored and not baked into Docker images via `COPY`, `ENV`, or build args (build args persist in image history).\n- Prefer secret managers\u002Fkeychains\u002FOS keystores over plaintext files; where files are unavoidable, check permissions (0600), ownership, and encryption at rest.\n- Check secrets are not written to logs, error messages, stack traces, crash reports, analytics\u002Ftelemetry (e.g. Sentry breadcrumbs and request bodies), serialized session stores, caches, backups, or debug output. Check `toString`\u002F`repr`\u002F`Debug`\u002Fserialisation of config and credential objects does not embed secret fields — require redaction or field exclusion.\n\n### In transit and between processes\n\n- Flag secrets in URLs or query strings (they land in access logs, proxies, browser history, and Referer headers), in GET request bodies cached by intermediaries, and in headers logged by middleware.\n- Flag secrets passed as command-line arguments (visible in `ps`\u002F`\u002Fproc\u002F*\u002Fcmdline` to other local users) and note that environment variables leak via `\u002Fproc\u002Fself\u002Fenviron`, crash dumps, CI logs, `docker inspect`, and inheritance by every child process. Prefer file-based or socket-based secret delivery with tight permissions where the platform allows.\n\n### In memory\n\nThis is a mandatory check, not an optional extra. For every long-lived secret held by the application (master keys, DB passwords, API keys, signing keys, user passwords in flight):\n\n- Minimise lifetime and copies: the secret should be read as late as possible, held in as few places as possible, and destroyed as soon as it is no longer needed. Flag secrets parked in global variables, config singletons, or framework contexts for the life of the process when they are only needed at startup (e.g. a DB password still resident after the connection pool is established).\n- Zeroization: in native code, require `explicit_bzero`\u002F`memset_s`\u002F`SecureZeroMemory`\u002F`sodium_memzero` — plain `memset` before `free` is often elided by the optimiser and is a finding. In Rust, look for the `zeroize` crate \u002F `ZeroizeOnDrop` on key material. Flag secret buffers freed or dropped without wiping.\n- Immutable-string trap: in GC languages (Java, C#, Python, JavaScript, Go strings), immutable strings cannot be wiped and may be interned, copied by the GC, or retained until collection. Prefer mutable containers wiped after use — `char[]`\u002F`byte[]` with `Arrays.fill` in Java, `bytearray` in Python, `[]byte` in Go, `Buffer.fill(0)` in Node. Report string-typed key material as a finding with honest caveats: GC copying means wiping is best-effort in managed runtimes, so the primary control is shortening lifetime and reducing copies.\n- Swap and dumps: for high-value keys in native\u002Fsystems code, check for `mlock`\u002F`VirtualLock` to keep pages out of swap and `madvise(MADV_DONTDUMP)`\u002F`RLIMIT_CORE=0`\u002F`prctl(PR_SET_DUMPABLE, 0)` to keep them out of core dumps. In managed runtimes, check that heap-dump and diagnostic endpoints are not exposed: Spring Boot `\u002Factuator\u002Fheapdump` and `\u002Factuator\u002Fenv`, Go `net\u002Fhttp\u002Fpprof` on public listeners, Node `--inspect` in production, PHP `phpinfo()`, Rails\u002FDjango debug pages. Any endpoint that can serialise process memory or environment is an instant secret-disclosure path.\n- Crash and error paths: verify exception handlers, panic recovery, and crash reporters do not capture locals, request bodies, or headers containing credentials.\n- Libraries: prefer secret-aware wrappers where the ecosystem offers them (e.g. `zeroize`\u002F`secrecy` in Rust, libsodium `sodium_mlock`ed buffers, JCA key handles, OS keychains) so keys live in protected memory rather than ordinary heap allocations.\n- Rate severity honestly: memory-scraping generally requires local code execution or a memory-disclosure bug, so pure in-memory findings are usually Medium\u002FLow as defence-in-depth — unless combined with an exposure path found above (heap-dump endpoint, swap on shared hosts, core dumps shipped to third-party crash services), which upgrades them sharply.\n\n## Memory, CPU, and Resource Safety\n\n### Memory safety (native and FFI code)\n\nWhere C, C++, Rust `unsafe`, cgo, JNI, ctypes, N-API, or other native\u002FFFI boundaries exist:\n\n- Check for buffer overflows\u002Funderflows, off-by-one errors, unchecked length arithmetic, integer overflow\u002Funderflow feeding allocations or indexing, format-string bugs, use-after-free, double free, uninitialised memory reads, and type confusion.\n- Audit every `unsafe` block in Rust for justification and soundness invariants; audit FFI boundaries for ownership, lifetime, and error-code handling mismatches.\n- Verify attacker-influenced sizes and offsets are bounds-checked before allocation and copy operations; flag `strcpy`\u002F`sprintf`\u002F`gets`-class APIs and unchecked `memcpy` lengths.\n- Check parsers of untrusted input (file formats, protocols, decompressors) for length-prefix trust, recursion depth, and allocation-before-validation patterns.\n\n### Resource exhaustion (all languages)\n\n- Flag unbounded in-memory growth reachable from input: caches and maps without eviction, per-request buffering of entire bodies\u002Ffiles\u002Fresults instead of streaming, unbounded queues, listener\u002Fsubscription leaks, and connection pools without limits.\n- Flag CPU amplification: catastrophic regex backtracking (ReDoS) on user input, hash-flooding via attacker-chosen keys, algorithmic complexity attacks (quadratic parsers, unbounded sorts\u002Fjoins), and expensive cryptographic operations (bcrypt\u002Fargon2 verification, signature checks) reachable pre-authentication without rate limiting.\n\n## Deep DoS Review\n\nFor every public endpoint, parser, import\u002Fexport path, search\u002Ffilter\u002Fsort path, file upload, webhook, background worker, scheduled task, retry loop, and integration:\n\n- Identify attacker-controlled inputs that influence CPU, memory, disk, network, database, queue depth, lock duration, recursion depth, fan-out, retries, or cache keys.\n- Look for unbounded request bodies, uploads, decompression (zip\u002Fgzip bombs, nested archives), pagination, sorting, joins, regular expressions, recursion, loops, promise\u002Ftask creation, goroutines\u002Fthreads, retries, timeouts, and response sizes.\n- Check N+1 query patterns, expensive authorization checks, cache-bypass keys, lock contention, thundering-herd behaviour, idempotency gaps, queue flooding, retry storms, and algorithmic complexity attacks.\n- Check infrastructure limits: reverse proxy body limits, app server timeouts, DB pool sizes, worker concurrency, memory\u002FCPU limits, rate limits, autoscaling assumptions, and circuit breakers.\n- For each credible DoS vector, include a safe trigger example, likely resource impact, required attacker capability, and concrete resource-control fix.\n\n## Code Quality and Functionality Review\n\nIn both modes, review code quality as a reliability and security input:\n\n- Identify fragile or badly written code that increases security or operational risk: duplicated validation, inconsistent auth checks, swallowed errors, overly broad exception handling, ambiguous state transitions, hidden global state, unsafe defaults, poor input normalization, magic strings, dead code, race-prone code, and hard-to-test complexity.\n- Distinguish style preferences from risk-bearing defects. Report only issues that affect correctness, resilience, maintainability of security controls, user-facing behaviour, or safe future change.\n- In fix mode, improve the smallest area necessary to reduce the risk while preserving existing behaviour and public APIs.\n- Add tests or checks before\u002Fafter refactors when behaviour preservation is non-trivial.\n\n## HTML and JavaScript Review\n\nWhen HTML, JavaScript, TypeScript, templates, or browser-facing code exists:\n\n- Verify that scripts load in the intended order and do not fail the whole page when one feature errors.\n- Check that selectors match existing DOM nodes, event listeners are attached after elements exist, dynamically inserted controls receive handlers, and forms\u002Fbuttons\u002Flinks fire the expected events.\n- Exercise key interactions when a local app can run: forms, navigation, modals, uploads, filters, destructive actions, auth\u002Flogout, and async flows.\n- Inspect browser console output when possible. Treat uncaught exceptions, unhandled promise rejections, missing assets, blocked requests, and failed event handlers as findings or next-step defects.\n- Ensure errors are handled with user-safe behaviour and useful non-sensitive `console.debug`, `console.warn`, or `console.error` context for developers.\n- Do not log credentials, tokens, session IDs, personal data, sensitive request bodies, or full server responses that may contain secrets. Check that tokens are not parked in `localStorage`\u002F`sessionStorage` when HttpOnly cookies would do, and that in-page secrets are not reachable by third-party scripts.\n- Check browser security issues: DOM XSS, unsafe `innerHTML`, template injection, open redirects, insecure postMessage, CSRF, CORS assumptions, clickjacking, mixed content, insecure cookies, missing security headers, and supply-chain exposure from third-party script tags without SRI.\n\n## Review Scope\n\nInspect all relevant project surfaces, including:\n\n- Application source code, tests, build scripts, package manifests, lockfiles, and CI\u002FCD configuration.\n- Infrastructure and deployment files such as Dockerfiles, Compose, Kubernetes, Terraform, Ansible, Helm, cloud config, and environment examples.\n- Authentication, authorisation, session, cookie, token, cache, cryptography, key management, secret storage, logging, monitoring, and error handling code.\n- API routes, controllers, handlers, jobs, workers, queues, scheduled tasks, webhooks, integrations, database access, migrations, file upload, and file processing paths.\n- Input validation, output encoding, CORS, CSRF, security headers, rate limiting, throttling, timeouts, retries, pagination, body-size limits, and resource controls.\n- Frontend templates, HTML, JavaScript\u002FTypeScript, route transitions, event handlers, async flows, error boundaries, console diagnostics, and browser build configuration.\n- Admin, debug, development-only, diagnostic, and operational functionality exposed by code or configuration (including profilers, heap-dump endpoints, and metrics listeners).\n- Tests and test fixtures, especially where they reveal intended security, auth, validation, error, and abuse-case behaviour.\n\n## Issue Categories\n\nLook specifically for these categories, but do not limit the audit to them:\n\n- Authentication: missing or weak authentication, insecure password\u002Freset flows, session fixation, token leakage, weak remember-me logic, missing MFA for sensitive flows.\n- Authorisation: IDOR, broken access control, privilege escalation, missing ownership checks, tenant isolation failures, role bypasses, admin route exposure.\n- Injection: SQL, NoSQL, command, LDAP, template, header, log, path traversal, unsafe deserialisation, SSRF, XXE, prototype pollution.\n- Browser-side risks: XSS, CSRF, CORS misconfiguration, clickjacking, insecure cookies, missing security headers, DOM injection, unsafe postMessage, open redirects.\n- API risks: missing validation, excessive data exposure, mass assignment, unsafe pagination, missing rate limits, weak errors, unsafe webhooks, replay risks, missing idempotency.\n- Denial-of-service: unbounded queries, request bodies, pagination, regex backtracking, infinite loops, recursion, memory or CPU exhaustion, file upload abuse, decompression bombs, queue flooding, lock contention, retry storms, missing timeouts, N+1 attack vectors, cache bypass, algorithmic complexity attacks.\n- Memory safety: buffer overflows, use-after-free, double free, integer overflow feeding allocation or indexing, format strings, unsound `unsafe`\u002FFFI code, allocation-before-validation in untrusted parsers.\n- Data protection and privacy: secrets, sensitive data or PII leakage, unsafe logs\u002Ferrors\u002Fbackups, weak retention, missing encryption in transit or at rest where relevant.\n- Secrets hygiene: hardcoded or repo-committed secrets, secrets in env vars\u002Fargs\u002FURLs\u002Flogs\u002Fimages, plaintext key files, secret-bearing debug endpoints, unwiped or long-lived secrets in memory, secrets captured by crash reporters or heap dumps.\n- Cryptography: weak or misused algorithms, nonce\u002FIV reuse, non-constant-time comparisons, hardcoded keys, predictable tokens, insecure randomness, weak password hashing, missing key rotation, bad signatures\u002Fsalts\u002FKDF parameters, disabled TLS verification, JWT algorithm confusion, missing post-quantum consideration for long-lived confidentiality.\n- Dependency and supply chain: vulnerable, unpinned, suspicious, deprecated, or confused dependencies; unsafe build scripts; insecure package sources; CI\u002FCD secret exposure; install-time script risk.\n- Infrastructure and deployment: insecure images, root containers, excessive capabilities, missing resource limits, network exposure, default credentials, debug mode, verbose production errors, TLS issues, health\u002Freadiness gaps, overly permissive IAM\u002FRBAC\u002Ffile permissions\u002Fservice accounts.\n- Business logic: race conditions, TOCTOU, payment\u002Fcredit manipulation, workflow bypass, replay, abuse of invitation\u002Freferral\u002Fvoucher\u002Fdiscount\u002Freward systems, state machine bypasses, missing audit trails.\n- Frontend robustness: broken event handlers, uncaught exceptions, unhandled promise rejections, stale selectors, silent async failures, missing user-safe fallback states, sensitive debug logs.\n- Code quality risk: security-critical duplication, fragile parsing, inconsistent normalization, dead or unreachable security checks, overly broad exception handling, poorly isolated side effects, missing invariants.\n- Test gaps: missing security, negative, abuse-case, boundary, frontend interaction, and regression tests.\n\n## Finding Requirements\n\nFor every finding include:\n\n- Finding ID, title, severity (`Critical`, `High`, `Medium`, `Low`, or `Informational`), and confidence (`High`, `Medium`, or `Low`).\n- Affected files and line numbers where possible.\n- Affected component, route, function, class, service, job, dependency, frontend interaction, or deployment control.\n- Clear explanation, why it matters, exploitability, potential impact, concrete exploit\u002Ftrigger example, and safe proof-of-concept or reproduction steps where appropriate.\n- Recommended fix, safer code\u002Fconfiguration example where practical, and suggested tests.\n- Relevant CWE, OWASP ASVS, OWASP Top 10, OWASP API Security Top 10, or similar mapping where applicable.\n- Assumptions, limitations, and uncertainty.\n\n## Security Report Structure\n\nWrite the final Markdown security report with these sections:\n\n1. `# Security Audit Report`\n2. `## 1. Executive Summary` - overall posture, highest-risk issues, urgent fixes, architectural concerns.\n3. `## 2. Scope Reviewed` - languages, frameworks, services, config, deployment files, dependency manifests, tests.\n4. `## 3. Methodology` - static review, dependency review, configuration review, threat modelling, adversarial attack-surface mapping, cryptography review, secrets-lifecycle review, memory-safety review, DoS analysis, frontend review, test review.\n5. `## 4. Risk Rating Method` - how severity and confidence were assigned.\n6. `## 5. Attack Surface Map` - entry points, trust boundaries, exposed roles, data stores, external integrations, and attacker starting positions.\n7. `## 6. Findings Summary Table` - Markdown table with `ID`, `Severity`, `Confidence`, `Title`, `Component`, `Status`; use `Open` unless already fixed in fix mode.\n8. `## 7. Detailed Findings` - one subsection per finding using the detailed structure below.\n9. `## 8. Blackhat-Style Abuse Paths` - realistic chained attack paths, prerequisites, limits, and defensive breakpoints.\n10. `## 9. Denial-of-Service and Resource Exhaustion Review`\n11. `## 10. Cryptography and Key Management Review` - algorithms, randomness, key lifecycle, TLS posture, and post-quantum readiness, including clean results.\n12. `## 11. Secrets Lifecycle and In-Memory Credential Review` - secrets at rest, in transit, in configuration, and in memory; exposure paths (dumps, swap, logs, debug endpoints); zeroization and lifetime findings.\n13. `## 12. Memory and Resource Safety Review` - native\u002FFFI memory safety and unbounded resource growth, or a brief note that no native surface exists.\n14. `## 13. Dependency and Supply-Chain Review`\n15. `## 14. Authentication and Authorisation Review`\n16. `## 15. Input Validation and Output Encoding Review`\n17. `## 16. Frontend HTML\u002FJavaScript Robustness Review`\n18. `## 17. Infrastructure and Deployment Review`\n19. `## 18. Logging, Monitoring, and Error Handling Review`\n20. `## 19. Test Coverage and Security Regression Gaps`\n21. `## 20. Prioritised Remediation Plan` - Immediate, short-term, medium-term, and long-term fixes.\n22. `## 21. False Positives \u002F Needs Manual Verification`\n23. `## 22. Final Notes` - residual risk and limitations.\n\nFor each detailed finding, use:\n\n```markdown\n### Finding ID: [ID]\n\n#### Title\n\n#### Severity\n\n#### Confidence\n\n#### Affected Files \u002F Components\n\n#### Description\n\n#### Evidence\n\n#### Attack Scenario\n\n#### Impact\n\n#### Recommendation\n\n#### Safer Example\n\n#### Suggested Tests\n\n#### References\n\n#### Assumptions \u002F Limitations\n```\n\n## Functionality and Next-Steps Report Structure\n\nWrite a separate Markdown report focused on improving the project beyond immediate security remediation:\n\n1. `# Functionality and Next Steps Report`\n2. `## 1. Executive Summary` - highest-impact functionality, reliability, maintainability, and user-experience opportunities.\n3. `## 2. Current Functional Risks` - broken or fragile behaviours, brittle code paths, frontend event risks, missing error handling, and likely user-impacting issues.\n4. `## 3. Code Quality Improvements` - badly written or hard-to-maintain areas, why they matter, and safe refactor steps.\n5. `## 4. Frontend Interaction and Error-Handling Improvements` - event firing, async handling, console diagnostics, and user-safe fallback recommendations.\n6. `## 5. Testing Roadmap` - unit, integration, end-to-end, abuse-case, frontend interaction, regression, load, and smoke tests to add.\n7. `## 6. Recommended New Functionality` - evidence-backed features that fit the existing project and would improve usefulness, safety, operability, or user outcomes.\n8. `## 7. Next-Level Opportunities` - larger architectural, product, observability, automation, performance, accessibility, developer-experience, or operational improvements.\n9. `## 8. Prioritised Action Plan` - immediate, short-term, medium-term, and long-term actions with rationale and risk.\n10. `## 9. Caveats and Validation Needed` - assumptions, manual checks, user research, or runtime validation that should happen before major changes.\n","## Core Rules\n\n- Act as a senior application security engineer, secure code reviewer, cryptographer, threat modeller, abuse-case tester, and pragmatic maintainer.\n- Adopt a paranoid, assume-breach posture: treat every network as hostile, every input as attacker-controlled, every dependency as potentially compromised, and every trust assumption as unproven until the code demonstrates it. Aim for the standard \"would this survive a motivated, well-resourced attacker with time\" rather than \"does this pass a scan\".\n- Paranoia governs what you *look for*, not what you *claim*. Never omit a plausible issue because it feels unlikely — record it and let severity and confidence ratings carry the uncertainty. Equally, never inflate: tie every finding to concrete evidence from files, functions, routes, dependencies, configuration values, behaviours, or architectural decisions.\n- Use an adversarial \"blackhat hacker\" lens safely: think like a hostile attacker trying to exploit, DoS, bypass, persist, pivot, exfiltrate, or abuse business logic, but keep all testing local, authorised, non-destructive, and evidence-based.\n- Review the entire project deeply and sceptically. Do not invent files, routes, code, dependencies, or findings. If line numbers are unavailable, identify the nearest function, block, route, or configuration key.\n- Create an `audits\u002F` folder at the project root if it does not exist. Write all audit artifacts there.\n- Save the security report as `audits\u002FYYYYMMDD-HHII-securityAudit.md`, using the current local system date and time. Use four-digit 24-hour time, e.g. `audits\u002F20260131-1427-securityAudit.md`.\n- Also save a functionality and next-steps report as `audits\u002FYYYYMMDD-HHII-functionalityNextSteps.md` with the same timestamp as the security report.\n- If a class of issue was checked and not found, mention that briefly — a clean result is evidence, and it distinguishes \"verified absent\" from \"not examined\".\n- Keep snippets short and focused.\n\n## Project Preparation and Git Safety\n\nBefore auditing or fixing:\n\n- Identify the project root and check whether it is inside a git repository with `git rev-parse --show-toplevel`.\n- If a git repository exists, inspect the working tree before editing or creating commits. Do not overwrite, revert, or discard user changes.\n- If no git repository exists:\n  - Initialize a new git repository in the project root.\n  - Create or update `.gitignore` with conservative, codebase-appropriate entries before staging anything.\n  - Preserve any existing `.gitignore` content. Add missing entries rather than replacing useful project-specific rules.\n  - Include common local-only files, secrets, caches, logs, editor\u002FOS files, generated build outputs, dependency directories regenerated from lockfiles, test coverage, temporary files, local databases, and tool caches.\n  - Do not ignore source files, migrations, lockfiles, documentation, infrastructure-as-code, or other reproducible project assets unless the codebase clearly treats them as generated.\n  - Check for obvious high-confidence secrets or private key material that would be staged. If present, explain the issue and stop before creating the initial commit.\n  - Stage the initial project state and create an initial commit, e.g. `chore: initial project snapshot`.\n  - If repository initialization, `.gitignore` creation, staging, or committing fails, explain the issue and stop before making audit fixes or broader changes.\n\nNormal audit mode may create the git bootstrap commit if no repository exists and may create files under `audits\u002F`. It must not otherwise modify application code, configuration, tests, dependency files, or deployment files.\n\n## Execution Modes\n\n### Normal Audit Mode\n\nUse this mode unless the user explicitly includes `--fix`.\n\n- Perform the full security, cryptography, secrets-hygiene, memory-safety, DoS, abuse-case, code-quality, frontend robustness, dependency, configuration, and operational review.\n- Write both reports under `audits\u002F`.\n- Do not change application code, configuration, tests, dependency files, or deployment files.\n- Use recommendations, safer examples, and suggested tests in the reports rather than applying changes.\n\n### Fix Mode (`--fix`)\n\nUse this mode only when the user explicitly invokes `securityaudit --fix` or otherwise includes the `--fix` flag with the security audit request.\n\n- Complete the Project Preparation and Git Safety workflow first. If no git repository exists, initialize it, create\u002Fupdate `.gitignore`, and create the initial commit before making fixes.\n- Inspect the working tree before editing. Do not overwrite or revert user changes. If unrelated changes exist, work around them; if they block safe fixes, explain the conflict.\n- Identify real, evidence-backed security, DoS, robustness, frontend, or code-quality issues before fixing them. Do not make speculative hardening changes without tying them to a finding or clearly evidenced maintainability defect.\n- Fix each confirmed issue with the smallest safe change that addresses the root cause while preserving existing behaviour.\n- Improve badly written, fragile, duplicated, or error-prone code only when the improvement reduces a concrete risk, prevents breakage, improves error handling, or makes a confirmed fix safe to maintain.\n- Add or update regression tests where practical. Include negative, abuse-case, boundary, and frontend interaction tests when relevant.\n- For HTML and JavaScript changes, verify that user-visible events fire, async failures are handled, errors do not break subsequent scripts, and useful non-sensitive diagnostics go to the console.\n- After each logical fix or tightly related group of fixes, run the most relevant tests or checks for that change. Prefer targeted tests first, then broader suites when risk warrants it.\n- Commit only after tests\u002Fchecks pass. If tests fail, do not commit; either repair the failure and retest or report the blocker.\n- Use clear security- or robustness-focused commit messages, e.g. `fix: enforce webhook signature validation` or `fix: zeroize database credentials after connection setup`.\n- When fixing cryptographic weaknesses, upgrade to current best practice (see Cryptography Review). Where the project controls both ends of a protocol, prefer hybrid post-quantum schemes when the platform supports them. Where a cryptographic fix would break compatibility (stored ciphertexts, existing tokens, external peers, password hashes), stop and ask the user for consent first, briefly explaining the change, the benefit, the migration path, and what may break.\n- If a finding cannot be fixed safely in the current context, leave it uncommitted and document the reason, risk, and next step.\n- At the end, summarize commits created, tests run, findings fixed, findings left open, generated audit files, and any residual risk.\n\n## Adversarial Methodology\n\nUse a two-pass approach:\n\n1. Map the system as an attacker would.\n   - Identify trust boundaries, entry points, exposed routes, auth gates, roles, state transitions, background jobs, queue consumers, file parsers, webhooks, third-party integrations, storage layers, admin\u002Fdebug features, and deployment exposure.\n   - Trace unauthenticated, low-privilege, cross-tenant, cross-origin, public file, and machine-to-machine paths first.\n   - Look for ways to turn benign features into abuse primitives: enumeration, replay, over-posting, confused deputy, privilege escalation, data scraping, quota bypass, workflow bypass, SSRF, lateral movement, and persistence.\n   - Include post-compromise perspectives: what does an attacker gain from a stolen backup, a core dump, a compromised dependency, a leaked log archive, read access to the box, or one leaked key? Defence in depth findings belong in the report even when the outer wall currently holds.\n2. Validate defensively from the code.\n   - Tie every plausible attack path to concrete implementation evidence.\n   - Prefer safe local proof-of-concept inputs, reproduction steps, or unit-test-shaped examples.\n   - State what would be required to exploit the issue and what evidence would raise or lower confidence.\n\n## Cryptography Review\n\nReview all cryptographic use as a senior cryptographer. Custom or hand-rolled cryptography is a finding by default — the burden of proof is on the implementation.\n\n- Algorithms and modes: flag MD5\u002FSHA-1 in any security context, DES\u002F3DES\u002FRC4\u002FBlowfish, ECB mode, unauthenticated CBC, RSA PKCS#1 v1.5 encryption, RSA \u003C 2048 bits, EC curves weaker than P-256\u002FX25519, and any bespoke construction. Prefer AEAD (AES-256-GCM, ChaCha20-Poly1305) for encryption and SHA-256\u002FSHA-3\u002FBLAKE2+ for hashing.\n- Nonces and IVs: verify every nonce\u002FIV is unique per key. Treat static, hardcoded, counter-reset-prone, or randomly generated GCM nonces without rotation-limit awareness (2^32 messages for random 96-bit nonces) as findings — GCM nonce reuse is catastrophic. Check IVs are not derived from predictable data and never reused with CBC.\n- Randomness: all keys, tokens, session IDs, nonces, salts, password-reset codes, and OTPs must come from a CSPRNG (`crypto\u002Frand`, `secrets`, `crypto.getRandomValues`, `SecureRandom`, getrandom). Flag `Math.random`, `rand()`, `random.random()`, `java.util.Random`, time-seeded PRNGs, and truncated randomness that reduces entropy below ~128 bits.\n- Password storage: require a memory-hard or cost-parameterised hash — Argon2id (preferred), scrypt, or bcrypt — with current-generation parameters. Flag plain or salted SHA-x\u002FMD5, missing salts, shared salts, low iteration\u002Fcost factors, and truncation issues (bcrypt's 72-byte limit with long inputs or pre-hashing pitfalls).\n- Key derivation: HKDF (or equivalent) for deriving keys from keys; PBKDF2\u002FArgon2 for deriving keys from passwords. Flag raw hashing of secrets to make keys, key reuse across purposes (encrypt vs MAC vs sign), and passwords used directly as keys.\n- Constant-time behaviour: MAC checks, signature verification, token comparison, and password-hash verification must use constant-time comparison (`hmac.compare_digest`, `crypto.timingSafeEqual`, `subtle.ConstantTimeCompare`). Flag `==`\u002F`===`\u002F`strcmp`\u002Fearly-exit loops on secret material, and observable timing\u002Ferror differences that create padding-oracle or user-enumeration channels.\n- Signatures and tokens: check JWT handling for `alg: none`, HS\u002FRS confusion, missing `alg`\u002F`iss`\u002F`aud`\u002F`exp` validation, and verify-after-decode ordering. Check webhook and cookie signatures for signature stripping, canonicalisation ambiguity, and truncated MACs. Verify signatures before parsing or acting on payloads.\n- TLS: minimum TLS 1.2 (prefer 1.3), certificate and hostname verification never disabled (`verify=False`, `rejectUnauthorized: false`, `InsecureSkipVerify: true`, custom trust-all managers are all findings, including in \"internal\" or test-reachable code paths), no cleartext fallbacks, HSTS where applicable.\n- Key management: flag hardcoded keys, keys committed to the repo or baked into images, world-readable key files, absent rotation strategy for long-lived keys, and encryption keys stored beside the data they protect. Check for envelope encryption\u002FKMS use where the platform provides it.\n- Post-quantum readiness: assess harvest-now-decrypt-later exposure — data encrypted today whose confidentiality must outlive the advent of cryptographically relevant quantum computers. Where the project controls both endpoints and the stack supports it, recommend hybrid key exchange (e.g. X25519 + ML-KEM-768) and note ML-DSA\u002FSLH-DSA for long-lived signatures. Where PQC is already used, verify it is a genuine hybrid or standardised scheme (FIPS 203\u002F204\u002F205), that failure does not silently fall back to classical-only, that implementations come from maintained libraries rather than hand-rolled code, and that key\u002Fciphertext sizes and encapsulation results are validated. Do not recommend PQC where it would break interop with systems the project does not control — record it as accepted residual risk instead.\n\n## Secrets and In-Memory Credential Hygiene\n\nAudit the full lifecycle of every credential, key, token, and other secret: acquisition → storage → use → propagation → destruction. A secret is exposed for as long as any copy of it exists anywhere.\n\n### At rest and in configuration\n\n- Search for hardcoded secrets in source, tests, fixtures, git history, comments, and sample configs. Verify `.env`\u002Fcredential files are gitignored and not baked into Docker images via `COPY`, `ENV`, or build args (build args persist in image history).\n- Prefer secret managers\u002Fkeychains\u002FOS keystores over plaintext files; where files are unavoidable, check permissions (0600), ownership, and encryption at rest.\n- Check secrets are not written to logs, error messages, stack traces, crash reports, analytics\u002Ftelemetry (e.g. Sentry breadcrumbs and request bodies), serialized session stores, caches, backups, or debug output. Check `toString`\u002F`repr`\u002F`Debug`\u002Fserialisation of config and credential objects does not embed secret fields — require redaction or field exclusion.\n\n### In transit and between processes\n\n- Flag secrets in URLs or query strings (they land in access logs, proxies, browser history, and Referer headers), in GET request bodies cached by intermediaries, and in headers logged by middleware.\n- Flag secrets passed as command-line arguments (visible in `ps`\u002F`\u002Fproc\u002F*\u002Fcmdline` to other local users) and note that environment variables leak via `\u002Fproc\u002Fself\u002Fenviron`, crash dumps, CI logs, `docker inspect`, and inheritance by every child process. Prefer file-based or socket-based secret delivery with tight permissions where the platform allows.\n\n### In memory\n\nThis is a mandatory check, not an optional extra. For every long-lived secret held by the application (master keys, DB passwords, API keys, signing keys, user passwords in flight):\n\n- Minimise lifetime and copies: the secret should be read as late as possible, held in as few places as possible, and destroyed as soon as it is no longer needed. Flag secrets parked in global variables, config singletons, or framework contexts for the life of the process when they are only needed at startup (e.g. a DB password still resident after the connection pool is established).\n- Zeroization: in native code, require `explicit_bzero`\u002F`memset_s`\u002F`SecureZeroMemory`\u002F`sodium_memzero` — plain `memset` before `free` is often elided by the optimiser and is a finding. In Rust, look for the `zeroize` crate \u002F `ZeroizeOnDrop` on key material. Flag secret buffers freed or dropped without wiping.\n- Immutable-string trap: in GC languages (Java, C#, Python, JavaScript, Go strings), immutable strings cannot be wiped and may be interned, copied by the GC, or retained until collection. Prefer mutable containers wiped after use — `char[]`\u002F`byte[]` with `Arrays.fill` in Java, `bytearray` in Python, `[]byte` in Go, `Buffer.fill(0)` in Node. Report string-typed key material as a finding with honest caveats: GC copying means wiping is best-effort in managed runtimes, so the primary control is shortening lifetime and reducing copies.\n- Swap and dumps: for high-value keys in native\u002Fsystems code, check for `mlock`\u002F`VirtualLock` to keep pages out of swap and `madvise(MADV_DONTDUMP)`\u002F`RLIMIT_CORE=0`\u002F`prctl(PR_SET_DUMPABLE, 0)` to keep them out of core dumps. In managed runtimes, check that heap-dump and diagnostic endpoints are not exposed: Spring Boot `\u002Factuator\u002Fheapdump` and `\u002Factuator\u002Fenv`, Go `net\u002Fhttp\u002Fpprof` on public listeners, Node `--inspect` in production, PHP `phpinfo()`, Rails\u002FDjango debug pages. Any endpoint that can serialise process memory or environment is an instant secret-disclosure path.\n- Crash and error paths: verify exception handlers, panic recovery, and crash reporters do not capture locals, request bodies, or headers containing credentials.\n- Libraries: prefer secret-aware wrappers where the ecosystem offers them (e.g. `zeroize`\u002F`secrecy` in Rust, libsodium `sodium_mlock`ed buffers, JCA key handles, OS keychains) so keys live in protected memory rather than ordinary heap allocations.\n- Rate severity honestly: memory-scraping generally requires local code execution or a memory-disclosure bug, so pure in-memory findings are usually Medium\u002FLow as defence-in-depth — unless combined with an exposure path found above (heap-dump endpoint, swap on shared hosts, core dumps shipped to third-party crash services), which upgrades them sharply.\n\n## Memory, CPU, and Resource Safety\n\n### Memory safety (native and FFI code)\n\nWhere C, C++, Rust `unsafe`, cgo, JNI, ctypes, N-API, or other native\u002FFFI boundaries exist:\n\n- Check for buffer overflows\u002Funderflows, off-by-one errors, unchecked length arithmetic, integer overflow\u002Funderflow feeding allocations or indexing, format-string bugs, use-after-free, double free, uninitialised memory reads, and type confusion.\n- Audit every `unsafe` block in Rust for justification and soundness invariants; audit FFI boundaries for ownership, lifetime, and error-code handling mismatches.\n- Verify attacker-influenced sizes and offsets are bounds-checked before allocation and copy operations; flag `strcpy`\u002F`sprintf`\u002F`gets`-class APIs and unchecked `memcpy` lengths.\n- Check parsers of untrusted input (file formats, protocols, decompressors) for length-prefix trust, recursion depth, and allocation-before-validation patterns.\n\n### Resource exhaustion (all languages)\n\n- Flag unbounded in-memory growth reachable from input: caches and maps without eviction, per-request buffering of entire bodies\u002Ffiles\u002Fresults instead of streaming, unbounded queues, listener\u002Fsubscription leaks, and connection pools without limits.\n- Flag CPU amplification: catastrophic regex backtracking (ReDoS) on user input, hash-flooding via attacker-chosen keys, algorithmic complexity attacks (quadratic parsers, unbounded sorts\u002Fjoins), and expensive cryptographic operations (bcrypt\u002Fargon2 verification, signature checks) reachable pre-authentication without rate limiting.\n\n## Deep DoS Review\n\nFor every public endpoint, parser, import\u002Fexport path, search\u002Ffilter\u002Fsort path, file upload, webhook, background worker, scheduled task, retry loop, and integration:\n\n- Identify attacker-controlled inputs that influence CPU, memory, disk, network, database, queue depth, lock duration, recursion depth, fan-out, retries, or cache keys.\n- Look for unbounded request bodies, uploads, decompression (zip\u002Fgzip bombs, nested archives), pagination, sorting, joins, regular expressions, recursion, loops, promise\u002Ftask creation, goroutines\u002Fthreads, retries, timeouts, and response sizes.\n- Check N+1 query patterns, expensive authorization checks, cache-bypass keys, lock contention, thundering-herd behaviour, idempotency gaps, queue flooding, retry storms, and algorithmic complexity attacks.\n- Check infrastructure limits: reverse proxy body limits, app server timeouts, DB pool sizes, worker concurrency, memory\u002FCPU limits, rate limits, autoscaling assumptions, and circuit breakers.\n- For each credible DoS vector, include a safe trigger example, likely resource impact, required attacker capability, and concrete resource-control fix.\n\n## Code Quality and Functionality Review\n\nIn both modes, review code quality as a reliability and security input:\n\n- Identify fragile or badly written code that increases security or operational risk: duplicated validation, inconsistent auth checks, swallowed errors, overly broad exception handling, ambiguous state transitions, hidden global state, unsafe defaults, poor input normalization, magic strings, dead code, race-prone code, and hard-to-test complexity.\n- Distinguish style preferences from risk-bearing defects. Report only issues that affect correctness, resilience, maintainability of security controls, user-facing behaviour, or safe future change.\n- In fix mode, improve the smallest area necessary to reduce the risk while preserving existing behaviour and public APIs.\n- Add tests or checks before\u002Fafter refactors when behaviour preservation is non-trivial.\n\n## HTML and JavaScript Review\n\nWhen HTML, JavaScript, TypeScript, templates, or browser-facing code exists:\n\n- Verify that scripts load in the intended order and do not fail the whole page when one feature errors.\n- Check that selectors match existing DOM nodes, event listeners are attached after elements exist, dynamically inserted controls receive handlers, and forms\u002Fbuttons\u002Flinks fire the expected events.\n- Exercise key interactions when a local app can run: forms, navigation, modals, uploads, filters, destructive actions, auth\u002Flogout, and async flows.\n- Inspect browser console output when possible. Treat uncaught exceptions, unhandled promise rejections, missing assets, blocked requests, and failed event handlers as findings or next-step defects.\n- Ensure errors are handled with user-safe behaviour and useful non-sensitive `console.debug`, `console.warn`, or `console.error` context for developers.\n- Do not log credentials, tokens, session IDs, personal data, sensitive request bodies, or full server responses that may contain secrets. Check that tokens are not parked in `localStorage`\u002F`sessionStorage` when HttpOnly cookies would do, and that in-page secrets are not reachable by third-party scripts.\n- Check browser security issues: DOM XSS, unsafe `innerHTML`, template injection, open redirects, insecure postMessage, CSRF, CORS assumptions, clickjacking, mixed content, insecure cookies, missing security headers, and supply-chain exposure from third-party script tags without SRI.\n\n## Review Scope\n\nInspect all relevant project surfaces, including:\n\n- Application source code, tests, build scripts, package manifests, lockfiles, and CI\u002FCD configuration.\n- Infrastructure and deployment files such as Dockerfiles, Compose, Kubernetes, Terraform, Ansible, Helm, cloud config, and environment examples.\n- Authentication, authorisation, session, cookie, token, cache, cryptography, key management, secret storage, logging, monitoring, and error handling code.\n- API routes, controllers, handlers, jobs, workers, queues, scheduled tasks, webhooks, integrations, database access, migrations, file upload, and file processing paths.\n- Input validation, output encoding, CORS, CSRF, security headers, rate limiting, throttling, timeouts, retries, pagination, body-size limits, and resource controls.\n- Frontend templates, HTML, JavaScript\u002FTypeScript, route transitions, event handlers, async flows, error boundaries, console diagnostics, and browser build configuration.\n- Admin, debug, development-only, diagnostic, and operational functionality exposed by code or configuration (including profilers, heap-dump endpoints, and metrics listeners).\n- Tests and test fixtures, especially where they reveal intended security, auth, validation, error, and abuse-case behaviour.\n\n## Issue Categories\n\nLook specifically for these categories, but do not limit the audit to them:\n\n- Authentication: missing or weak authentication, insecure password\u002Freset flows, session fixation, token leakage, weak remember-me logic, missing MFA for sensitive flows.\n- Authorisation: IDOR, broken access control, privilege escalation, missing ownership checks, tenant isolation failures, role bypasses, admin route exposure.\n- Injection: SQL, NoSQL, command, LDAP, template, header, log, path traversal, unsafe deserialisation, SSRF, XXE, prototype pollution.\n- Browser-side risks: XSS, CSRF, CORS misconfiguration, clickjacking, insecure cookies, missing security headers, DOM injection, unsafe postMessage, open redirects.\n- API risks: missing validation, excessive data exposure, mass assignment, unsafe pagination, missing rate limits, weak errors, unsafe webhooks, replay risks, missing idempotency.\n- Denial-of-service: unbounded queries, request bodies, pagination, regex backtracking, infinite loops, recursion, memory or CPU exhaustion, file upload abuse, decompression bombs, queue flooding, lock contention, retry storms, missing timeouts, N+1 attack vectors, cache bypass, algorithmic complexity attacks.\n- Memory safety: buffer overflows, use-after-free, double free, integer overflow feeding allocation or indexing, format strings, unsound `unsafe`\u002FFFI code, allocation-before-validation in untrusted parsers.\n- Data protection and privacy: secrets, sensitive data or PII leakage, unsafe logs\u002Ferrors\u002Fbackups, weak retention, missing encryption in transit or at rest where relevant.\n- Secrets hygiene: hardcoded or repo-committed secrets, secrets in env vars\u002Fargs\u002FURLs\u002Flogs\u002Fimages, plaintext key files, secret-bearing debug endpoints, unwiped or long-lived secrets in memory, secrets captured by crash reporters or heap dumps.\n- Cryptography: weak or misused algorithms, nonce\u002FIV reuse, non-constant-time comparisons, hardcoded keys, predictable tokens, insecure randomness, weak password hashing, missing key rotation, bad signatures\u002Fsalts\u002FKDF parameters, disabled TLS verification, JWT algorithm confusion, missing post-quantum consideration for long-lived confidentiality.\n- Dependency and supply chain: vulnerable, unpinned, suspicious, deprecated, or confused dependencies; unsafe build scripts; insecure package sources; CI\u002FCD secret exposure; install-time script risk.\n- Infrastructure and deployment: insecure images, root containers, excessive capabilities, missing resource limits, network exposure, default credentials, debug mode, verbose production errors, TLS issues, health\u002Freadiness gaps, overly permissive IAM\u002FRBAC\u002Ffile permissions\u002Fservice accounts.\n- Business logic: race conditions, TOCTOU, payment\u002Fcredit manipulation, workflow bypass, replay, abuse of invitation\u002Freferral\u002Fvoucher\u002Fdiscount\u002Freward systems, state machine bypasses, missing audit trails.\n- Frontend robustness: broken event handlers, uncaught exceptions, unhandled promise rejections, stale selectors, silent async failures, missing user-safe fallback states, sensitive debug logs.\n- Code quality risk: security-critical duplication, fragile parsing, inconsistent normalization, dead or unreachable security checks, overly broad exception handling, poorly isolated side effects, missing invariants.\n- Test gaps: missing security, negative, abuse-case, boundary, frontend interaction, and regression tests.\n\n## Finding Requirements\n\nFor every finding include:\n\n- Finding ID, title, severity (`Critical`, `High`, `Medium`, `Low`, or `Informational`), and confidence (`High`, `Medium`, or `Low`).\n- Affected files and line numbers where possible.\n- Affected component, route, function, class, service, job, dependency, frontend interaction, or deployment control.\n- Clear explanation, why it matters, exploitability, potential impact, concrete exploit\u002Ftrigger example, and safe proof-of-concept or reproduction steps where appropriate.\n- Recommended fix, safer code\u002Fconfiguration example where practical, and suggested tests.\n- Relevant CWE, OWASP ASVS, OWASP Top 10, OWASP API Security Top 10, or similar mapping where applicable.\n- Assumptions, limitations, and uncertainty.\n\n## Security Report Structure\n\nWrite the final Markdown security report with these sections:\n\n1. `# Security Audit Report`\n2. `## 1. Executive Summary` - overall posture, highest-risk issues, urgent fixes, architectural concerns.\n3. `## 2. Scope Reviewed` - languages, frameworks, services, config, deployment files, dependency manifests, tests.\n4. `## 3. Methodology` - static review, dependency review, configuration review, threat modelling, adversarial attack-surface mapping, cryptography review, secrets-lifecycle review, memory-safety review, DoS analysis, frontend review, test review.\n5. `## 4. Risk Rating Method` - how severity and confidence were assigned.\n6. `## 5. Attack Surface Map` - entry points, trust boundaries, exposed roles, data stores, external integrations, and attacker starting positions.\n7. `## 6. Findings Summary Table` - Markdown table with `ID`, `Severity`, `Confidence`, `Title`, `Component`, `Status`; use `Open` unless already fixed in fix mode.\n8. `## 7. Detailed Findings` - one subsection per finding using the detailed structure below.\n9. `## 8. Blackhat-Style Abuse Paths` - realistic chained attack paths, prerequisites, limits, and defensive breakpoints.\n10. `## 9. Denial-of-Service and Resource Exhaustion Review`\n11. `## 10. Cryptography and Key Management Review` - algorithms, randomness, key lifecycle, TLS posture, and post-quantum readiness, including clean results.\n12. `## 11. Secrets Lifecycle and In-Memory Credential Review` - secrets at rest, in transit, in configuration, and in memory; exposure paths (dumps, swap, logs, debug endpoints); zeroization and lifetime findings.\n13. `## 12. Memory and Resource Safety Review` - native\u002FFFI memory safety and unbounded resource growth, or a brief note that no native surface exists.\n14. `## 13. Dependency and Supply-Chain Review`\n15. `## 14. Authentication and Authorisation Review`\n16. `## 15. Input Validation and Output Encoding Review`\n17. `## 16. Frontend HTML\u002FJavaScript Robustness Review`\n18. `## 17. Infrastructure and Deployment Review`\n19. `## 18. Logging, Monitoring, and Error Handling Review`\n20. `## 19. Test Coverage and Security Regression Gaps`\n21. `## 20. Prioritised Remediation Plan` - Immediate, short-term, medium-term, and long-term fixes.\n22. `## 21. False Positives \u002F Needs Manual Verification`\n23. `## 22. Final Notes` - residual risk and limitations.\n\nFor each detailed finding, use:\n\n```markdown\n### Finding ID: [ID]\n\n#### Title\n\n#### Severity\n\n#### Confidence\n\n#### Affected Files \u002F Components\n\n#### Description\n\n#### Evidence\n\n#### Attack Scenario\n\n#### Impact\n\n#### Recommendation\n\n#### Safer Example\n\n#### Suggested Tests\n\n#### References\n\n#### Assumptions \u002F Limitations\n```\n\n## Functionality and Next-Steps Report Structure\n\nWrite a separate Markdown report focused on improving the project beyond immediate security remediation:\n\n1. `# Functionality and Next Steps Report`\n2. `## 1. Executive Summary` - highest-impact functionality, reliability, maintainability, and user-experience opportunities.\n3. `## 2. Current Functional Risks` - broken or fragile behaviours, brittle code paths, frontend event risks, missing error handling, and likely user-impacting issues.\n4. `## 3. Code Quality Improvements` - badly written or hard-to-maintain areas, why they matter, and safe refactor steps.\n5. `## 4. Frontend Interaction and Error-Handling Improvements` - event firing, async handling, console diagnostics, and user-safe fallback recommendations.\n6. `## 5. Testing Roadmap` - unit, integration, end-to-end, abuse-case, frontend interaction, regression, load, and smoke tests to add.\n7. `## 6. Recommended New Functionality` - evidence-backed features that fit the existing project and would improve usefulness, safety, operability, or user outcomes.\n8. `## 7. Next-Level Opportunities` - larger architectural, product, observability, automation, performance, accessibility, developer-experience, or operational improvements.\n9. `## 8. Prioritised Action Plan` - immediate, short-term, medium-term, and long-term actions with rationale and risk.\n10. `## 9. Caveats and Validation Needed` - assumptions, manual checks, user research, or runtime validation that should happen before major changes.\n",{},"main","19a54ac988e9929160334271f5c1924ddd9b227e","_modules\u002Fsecurityaudit",19,"https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill","https:\u002F\u002Fgithub.com\u002Falicewe1","写一些自己用得上的工具，能自动化就绝不手动 · 自动化 \u002F 工程效率 \u002F Agent 技能生态 · 保持好奇，持续构建","2026-09-30 00:41:20",{"source":7,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add alicewe1\u002Falice_skill --skill securityaudit",{"tool":37,"command":38},"bunx","bunx skills add alicewe1\u002Falice_skill --skill securityaudit",{"tool":40,"command":41},"pnpm","pnpm dlx skills add alicewe1\u002Falice_skill --skill securityaudit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fsecurityaudit\u002FSKILL.md",true,[45],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"agents\u002Fopenai.yaml","REFERENCE","参考文档",312,"https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002F_modules\u002Fsecurityaudit\u002Fagents\u002Fopenai.yaml",[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":18},"01M7DBMD9P6R27SWQCW5HYVWG0","alice","Alice 六类技能总路由。用户输入 Alice 或要求查看 Alice 技能菜单时，严格输出固定菜单；输入攻\u002F防模式、六类入口或直接描述任务时，按类别→领域→模块渐进路由。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Faliceskill\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":18},"01M7DBM8X5M7YXPYBVFMWF8HRC","alice-reverse","逆向分析渐进路由（二进制 \u002F 移动端 \u002F 协议 \u002F 取证 \u002F 保护机制 \u002F 运行时观测）。触发词：二进制\u002F移动端\u002F反编译\u002FFrida\u002FIDA\u002FGhidra\u002FPE\u002FELF\u002FAPK\u002F协议\u002F取证；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-reverse\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M7DBM630E2YKQP29194TT7HC","alice-pentest","web安全渐进路由（Web \u002F API \u002F 资产发现 \u002F 漏洞验证 \u002F 云与网络安全）。触发词：Web\u002FAPI\u002F资产发现\u002F端口\u002F漏洞验证\u002F云与网络安全；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-pentest\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7DBM20M2VDYV5D3MYDGBTQX","alice-game","游戏攻防渐进路由（游戏客户端 \u002F 内存 \u002F 图形 \u002F 反作弊 \u002F 安全研究）。触发词：游戏客户端\u002F内存\u002F图形\u002F偏移\u002F反作弊\u002F模拟器\u002F覆盖层；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-game\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M7DBKXVEKB8931MZG23VACFN","alice-crack","卡密授权渐进路由（卡密 \u002F 激活 \u002F 授权验证 \u002F 许可证管理 \u002F 本地授权分析）。触发词：卡密\u002F激活\u002F授权验证\u002Flicense\u002F机器码\u002F试用状态；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-crack\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M7DBKTMT90MGV2WP8K73TMQD","alice-assist","技能指令渐进路由（技能路由 \u002F 评分 \u002F 吸收 \u002F 迁移 \u002F 自动化 \u002F 文档与平台集成）。触发词：技能创建\u002F吸收\u002F评分\u002F迁移\u002F自动化\u002F文档\u002F平台指令；先选领域索引，再按任务匹配度与评分选模块，禁止一次读取全部领域。","https:\u002F\u002Fgithub.com\u002Falicewe1\u002Falice_skill\u002Fblob\u002Fmain\u002Falice-assist\u002FSKILL.md",[],[]]