All skills
🔒

Security Audit

Security

Automatically audit your app against the top 10 most common security vulnerabilities. Covers data protection, login security, and secure coding patterns. No security expertise required. The skill guides your AI agent through the entire process.

Skill prompt

OWASP Security Best Practices Skill

Apply these security standards when writing or reviewing code.

Quick Reference: OWASP Top 10:2025

#VulnerabilityKey Prevention
A01Broken Access ControlDeny by default, enforce server-side, verify ownership
A02Security MisconfigurationHarden configs, disable defaults, minimize features
A03Supply Chain FailuresLock versions, verify integrity, audit dependencies
A04Cryptographic FailuresTLS 1.2+, AES-256-GCM, Argon2/bcrypt for passwords
A05InjectionParameterized queries, input validation, safe APIs
A06Insecure DesignThreat model, rate limit, design security controls
A07Auth FailuresMFA, check breached passwords, secure sessions
A08Integrity FailuresSign packages, SRI for CDN, safe serialization
A09Logging FailuresLog security events, structured format, alerting
A10Exception HandlingFail-closed, hide internals, log with context

Security Code Review Checklist

When reviewing code, check for these issues:

Input Handling
  • All user input validated server-side
  • Using parameterized queries (not string concatenation)
  • Input length limits enforced
  • Allowlist validation preferred over denylist
Authentication & Sessions
  • Passwords hashed with Argon2/bcrypt (not MD5/SHA1)
  • Session tokens have sufficient entropy (128+ bits)
  • Sessions invalidated on logout
  • MFA available for sensitive operations
Access Control
  • Check whether ctx.auth.getUserIdentity() is called in every Convex query/mutation/action that touches user-owned data, before flagging missing per-route auth
  • Authorization checked on every request
  • Using object references user cannot manipulate
  • Deny by default policy
  • Privilege escalation paths reviewed
Data Protection
  • Sensitive data encrypted at rest
  • TLS for all data in transit
  • No sensitive data in URLs/logs
  • Secrets in environment/vault (not code)
Error Handling
  • No stack traces exposed to users
  • Fail-closed on errors (deny, not allow)
  • All exceptions logged with context
  • Consistent error responses (no enumeration)

Secure Code Patterns

Argument Validation

Convex queries and mutations should declare every argument with a validator from convex/values. The validator rejects malformed input before your code runs and gives the client a typed error instead of a crash.

typescript
import { v } from "convex/values";import { query } from "./_generated/server";
// UNSAFE - no argument validation, accepts anythingexport const getUserBad = query({  handler: async (ctx, args: any) => {    return await ctx.db.get(args.userId);  },});
// SAFE - validators reject bad inputexport const getUser = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    return await ctx.db.get(userId);  },});
Command Injection Prevention
typescript
import { execFile } from "node:child_process";
// UNSAFEexec(`convert ${filename} output.png`);
// SAFE - Use execFile with argument arrayexecFile("convert", [filename, "output.png"], (err, stdout) => {  /* ... */});
Password Storage

Hercules apps must use Hercules Auth — a managed OIDC provider that supports Google, Microsoft, and email OTP. The platform handles password hashing, verification, session management, and resets correctly, and custom auth providers are not supported. If you find a hand-rolled auth flow that stores passwords directly in a user table during the audit, flag it as critical and recommend migrating to Hercules Auth.

Access Control

Every Convex query, mutation, and action that touches user-owned data must check who is calling it. In a Hercules app, the signed-in user comes from Hercules Auth via ctx.auth.getUserIdentity(). Throw a ConvexError so the client can react to known failure codes.

typescript
import { ConvexError, v } from "convex/values";import { query } from "./_generated/server";
// UNSAFE - returns any user's data to anyoneexport const getUserBad = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    return await ctx.db.get(userId);  },});
// SAFE - require auth, then enforce ownershipexport const getUser = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    const identity = await ctx.auth.getUserIdentity();    if (!identity) {      throw new ConvexError({ code: "UNAUTHENTICATED" });    }
    const user = await ctx.db.get(userId);    if (!user) return null;    if (user.tokenIdentifier !== identity.tokenIdentifier) {      throw new ConvexError({ code: "FORBIDDEN" });    }    return user;  },});

Hercules apps must use Hercules Auth — there is no support for rolling your own auth provider, NextAuth, Clerk, Auth0, or Better Auth in user apps. If you find a hand-rolled auth flow during the audit, recommend migrating to Hercules Auth.

Error Handling

In Convex functions, throw a ConvexError with a short, structured payload the client can react to. Do not include stack traces or raw internal details — Convex surfaces the thrown value to the client, so anything you put in it is user-visible.

typescript
import { ConvexError } from "convex/values";
// UNSAFE - leaks internal detailsthrow new Error(`DB lookup failed: ${error.stack}`);
// SAFE - short coded error; log internal details on the server side insteadconsole.error("DB lookup failed", error);throw new ConvexError({ code: "INTERNAL_ERROR", message: "Something went wrong" });
Fail-Closed Pattern
typescript
// UNSAFE - Fail-openasync function checkPermission(user: User, resource: string): Promise<boolean> {  try {    return await authService.check(user, resource);  } catch {    return true; // DANGEROUS!  }}
// SAFE - Fail-closedasync function checkPermission(user: User, resource: string): Promise<boolean> {  try {    return await authService.check(user, resource);  } catch (error) {    logger.error({ error, userId: user.id, resource }, "Auth check failed");    return false; // Deny on error  }}

Agentic AI Security (OWASP 2026)

When building or reviewing AI agent systems, check for:

RiskDescriptionMitigation
ASI01: Goal HijackPrompt injection alters agent objectivesInput sanitization, goal boundaries, behavioral monitoring
ASI02: Tool MisuseTools used in unintended waysLeast privilege, fine-grained permissions, validate I/O
ASI03: Privilege AbuseCredential escalation across agentsShort-lived scoped tokens, identity verification
ASI04: Supply ChainCompromised third-party plugins or toolsVerify signatures, sandbox, allowlist what tools an agent can call
ASI05: Code ExecutionUnsafe code generation/executionSandbox execution, static analysis, human approval
ASI06: Memory PoisoningCorrupted RAG/context dataValidate stored content, segment by trust level
ASI07: Agent CommsSpoofing between agentsAuthenticate, encrypt, verify message integrity
ASI08: Cascading FailuresErrors propagate across systemsCircuit breakers, graceful degradation, isolation
ASI09: Trust ExploitationSocial engineering via AILabel AI content, user education, verification steps
ASI10: Rogue AgentsCompromised agents acting maliciouslyBehavior monitoring, kill switches, anomaly detection
Agent Security Checklist
  • All agent inputs sanitized and validated
  • Tools operate with minimum required permissions
  • Credentials are short-lived and scoped
  • Third-party plugins verified and sandboxed
  • Code execution happens in isolated environments
  • Agent communications authenticated and encrypted
  • Circuit breakers between agent components
  • Human approval for sensitive operations
  • Behavior monitoring for anomaly detection
  • Kill switch available for agent systems

ASVS 5.0 Key Requirements

Level 1 (All Applications)
  • Passwords minimum 12 characters
  • Check against breached password lists
  • Rate limiting on authentication
  • Session tokens 128+ bits entropy
  • HTTPS everywhere
Level 2 (Sensitive Data)
  • All L1 requirements plus:
  • MFA for sensitive operations
  • Cryptographic key management
  • Comprehensive security logging
  • Input validation on all parameters
Level 3 (Critical Systems)
  • All L1/L2 requirements plus:
  • Hardware security modules for keys
  • Threat modeling documentation
  • Advanced monitoring and alerting
  • Penetration testing validation

TypeScript / JavaScript Security Patterns

Prototype Pollution
typescript
// UNSAFE: Prototype pollution via mergeObject.assign(target, userInput);_.merge(target, userInput);
// SAFE: Use null prototype objectconst safe = Object.assign(Object.create(null), validated);
// SAFE: Validate keys before mergingfunction safeMerge(target: Record<string, unknown>, source: Record<string, unknown>) {  const banned = new Set(["__proto__", "constructor", "prototype"]);  for (const key of Object.keys(source)) {    if (banned.has(key)) continue;    target[key] = source[key];  }  return target;}
XSS Prevention
typescript
// UNSAFE: Injecting user input into HTML directlyelement.innerHTML = userInput;const html = `<div>${userInput}</div>`;
// SAFE: React JSX auto-escapes, so this is finereturn <div>{userInput}</div>;
// SAFE: If you must render raw HTML, sanitize firstimport DOMPurify from "dompurify";element.innerHTML = DOMPurify.sanitize(userInput);

dangerouslySetInnerHTML in React is the equivalent of innerHTML — never pass unsanitized user input to it.

eval and Dynamic Code Execution
typescript
// UNSAFE: eval with user inputeval(userCode);new Function(userCode)();setTimeout(userCode, 0);
// SAFE: Never execute user-controlled strings as code// Use a proper parser, schema validator, or sandboxed VM if needed
Path Traversal (Convex actions)

Path traversal can show up in Convex action functions that read files from disk based on user input. Most Hercules apps store files via Convex file storage (ctx.storage) instead, which avoids the problem entirely — flag any code that joins user input into a filesystem path.

typescript
// UNSAFE: user-controlled segment in a filesystem pathconst filePath = `./uploads/${args.filename}`;
// SAFE: use Convex file storage by storage ID, not by filenameconst url = await ctx.storage.getUrl(args.storageId);
Insecure Deserialization
typescript
// UNSAFE: Deserializing untrusted data with type coercionconst data = JSON.parse(body);processUser(data as User); // No runtime validation
// SAFE: Validate with a schema library (zod, valibot, etc.)import { z } from "zod";const UserSchema = z.object({  id: z.string().uuid(),  name: z.string().max(255),  role: z.enum(["user", "admin"]),});const data = UserSchema.parse(JSON.parse(body));
ReDoS (Regular Expression Denial of Service)
typescript
// UNSAFE: Catastrophic backtrackingconst emailRegex = /^([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+@([a-zA-Z0-9]+\.)+[a-zA-Z]{2,}$/;emailRegex.test(userInput); // Can hang on malicious input
// SAFE: Use simple patterns or a validation libraryimport { z } from "zod";const email = z.string().email().parse(userInput);
Server-Side Request Forgery (SSRF)

SSRF shows up in Convex action functions that call fetch() on a URL the user provided. An attacker can point that URL at internal services (like 169.254.169.254 for cloud metadata) and exfiltrate secrets.

typescript
// UNSAFE: Fetching whatever URL the user passed inconst response = await fetch(args.url);
// SAFE: Validate against an allowlist and block internal networksfunction isAllowedUrl(urlStr: string): boolean {  const url = new URL(urlStr);  const blocked = ["localhost", "127.0.0.1", "0.0.0.0", "169.254.169.254"];  if (blocked.includes(url.hostname)) return false;  if (url.protocol !== "https:") return false;  // Add domain allowlist as needed  return true;}
Timing-Safe Comparison
typescript
import { timingSafeEqual } from "node:crypto";
// UNSAFE: String comparison leaks timing infoif (token === storedToken) {  /* ... */}
// SAFE: Constant-time comparisonfunction safeCompare(a: string, b: string): boolean {  const bufA = Buffer.from(a);  const bufB = Buffer.from(b);  if (bufA.length !== bufB.length) return false;  return timingSafeEqual(bufA, bufB);}

Watch for: eval(), Function(), innerHTML, document.write(), __proto__, constructor.prototype, unvalidated JSON.parse(), child_process.exec() with string args, missing CORS configuration, JWT alg: none attacks, insecure cookie flags


Bash Security Patterns

Command Injection and Word Splitting
bash
# UNSAFE: Unquoted variablesrm $user_filefor f in $files; do process "$f"; done
# SAFE: Always quote variablesrm "$user_file"while IFS= read -r f; do process "$f"; done <<< "$files"
Script Hardening
bash
# Always start scripts with strict modeset -euo pipefail
# UNSAFE: eval with external inputeval "$user_command"
# SAFE: Never eval user input; use explicit commands
Temporary Files
bash
# UNSAFE: Predictable temp filetmpfile="/tmp/myapp_$$"
# SAFE: Use mktemptmpfile="$(mktemp)"trap 'rm -f "$tmpfile"' EXIT

Watch for: Unquoted variables, eval, backticks, $(...) with user input, missing set -euo pipefail, world-readable temp files, curl | bash patterns


Deep Security Analysis Mindset

When reviewing TypeScript/Node.js code, think like a senior security researcher:

  1. Type System Gaps: TypeScript types are erased at runtime. Always validate untrusted data with runtime schemas (zod, valibot).
  2. Prototype Chain: JavaScript's prototype-based inheritance creates unique pollution and confusion attack vectors.
  3. Event Loop: Blocking the event loop is a DoS vector. Watch for CPU-intensive sync operations on untrusted input (regex, JSON parsing of large payloads).
  4. Serialization: JSON.parse() is safe from RCE but not from schema violations. Always validate the shape of deserialized data.
  5. Package Ecosystem: npm is the largest package registry. Typosquatting, dependency confusion, and malicious postinstall scripts are real threats. Use lockfiles, audit regularly.
  6. Build System: npm/pnpm script injection during builds. Review postinstall hooks in dependencies.
  7. Node.js Builtins: child_process.exec() spawns a shell (injection risk). Prefer execFile() or spawn() with argument arrays.
  8. Error Handling: Unhandled promise rejections can crash the process or leak info. Use global handlers and structured logging.
  9. Secrets in Environment: process.env values are strings and can leak into logs or error messages. Validate and redact.
  10. CORS and Headers: Misconfigured CORS, missing security headers (CSP, HSTS, X-Frame-Options) are common in Node.js apps.

When to Apply This Skill

Use this skill when:

  • Writing authentication or authorization code
  • Handling user input or external data
  • Implementing cryptography or password storage
  • Reviewing code for security vulnerabilities
  • Designing API endpoints
  • Building AI agent systems
  • Configuring application security settings
  • Handling errors and exceptions
  • Working with third-party dependencies
  • Working in TypeScript/Node.js or Bash - apply the deep analysis mindset above