MCPInstall

security-bun

Review Bun runtime security audit patterns. Use for auditing Bun-specific vulnerabilities including shell injection, SQL injection, server security, and process spawning. Use proactively when reviewing Bun apps (bun.lockb, bunfig.toml, or bun: imports present). Examples: - user: "Review this Bun shell script" → audit $ usage and argument injection - user: "Check my bun:sqlite queries" → verify sql tagged template usage - user: "Audit my Bun.serve() setup" → check path traversal and request limits - user: "Is my Bun.spawn() usage safe?" → audit command injection and input validation - user: "Review WebSocket security in Bun" → check authentication before upgrade

Installs
104
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/igorwarzocha/opencode-workflows --skill security-bun
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads security-bun automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

<overview>

Security audit patterns for Bun runtime applications covering shell injection, SQL injection, server security, and Bun-specific vulnerabilities.

</overview> <rules>

The #1 Bun Footgun: Shell Escaping vs Raw Shell

Bun's shell $ is a tagged template that escapes by default. If you bypass escaping (via raw mode), user input can become command injection.

import { $ } from "bun";

const userInput = "hello; rm -rf /";

// ✓ SAFE: Tagged template - automatically escapes
await $`echo ${userInput}`;
// Executes: echo 'hello; rm -rf /'

// ❌ CRITICAL: Spawning a new shell (bypasses Bun escaping)
await $`bash -c "echo ${userInput}"`;
// The nested shell interprets user input as code

Argument Injection (Even with Escaping)

Even the safe tagged template is vulnerable to argument injection:

import { $ } from "bun";

// ❌ HIGH: Argument injection via -- prefix
const userRepo = "--upload-pack=id>/tmp/pwned";
await $`git ls-remote ${userRepo} main`;
// The -- prefix makes it a command-line argument, not a value

// ✓ Validate input format before use
const userRepo = getUserInput();
if (!userRepo.match(/^https?:\/\//)) {
  throw new Error("Invalid repository URL");
}
await $`git ls-remote ${userRepo} main`;

// ✓ Or use -- to end argument parsing
await $`git ls-remote -- ${userRepo} main`;

bun:sqlite SQL Injection

sql is a tagged template that parameterizes values. If you build SQL strings manually, you can still be vulnerable.

import { sql } from "bun";

const userId = "1 OR 1=1";

// ❌ CRITICAL: Function call - SQL injection!
await sql(`SELECT * FROM users WHERE id = ${userId}`);
// Executes: SELECT * FROM users WHERE id = 1 OR 1=1

// ✓ SAFE: Tagged template - parameterized query
await sql`SELECT * FROM users WHERE id = ${userId}`;
// Executes: SELECT * FROM users WHERE id = $1 with params ['1 OR 1=1']

bun:sqlite Database Class

import { Database } from "bun:sqlite";

const db = new Database("mydb.sqlite");
const userInput = "'; DROP TABLE users; --";

// ❌ CRITICAL: String interpolation
db.run(`INSERT INTO logs VALUES ('${userInput}')`);

// ✓ SAFE: Parameterized with .run()
db.run("INSERT INTO logs VALUES (?)", [userInput]);

// ✓ SAFE: Prepared statements
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
stmt.get(userInput);

// ✓ SAFE: Query with parameters
db.query("SELECT * FROM users WHERE email = ?").get(userInput);
</rules> <vulnerabilities>

Bun.serve() Security

Missing Request Validation

// ❌ No input validation
Bun.serve({
  fetch(req) {
    const url = new URL(req.url);
    const file = url.searchParams.get("file");
    return new Response(Bun.file(`./uploads/${file}`)); // Path traversal!
  },
});

// ✓ Validate and sanitize
import { join, basename, resolve } from "path";

Bun.serve({
  fetch(req) {
    const url = new URL(req.url);
    const file = url.searchParams.get("file");
    
    // Sanitize filename
    const safeName = basename(file ?? "");
    const uploadsDir = resolve("./uploads");
    const filePath = resolve(join(uploadsDir, safeName));
    
    // Verify path is within uploads directory
    if (!filePath.startsWith(uploadsDir)) {
      return new Response("Forbidden", { status: 403 });
    }
    
    return new Response(Bun.file(filePath));
  },
});

Request Size Limits (DoS Protection)

// ❌ No body size limit (large uploads can exhaust memory)
Bun.serve({
  fetch(req) {
    return new Response("ok");
  },
});

// ✓ Set a max request body size
Bun.serve({
  maxRequestBodySize: 1_000_000, // 1 MB
  fetch(req) {
    return new Response("ok");
  },
});

CORS Configuration

// ❌ Wide open CORS
Bun.serve({
  fetch(req) {
    return new Response("data", {
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true", // Dangerous combo!
      },
    });
  },
});

// ✓ Explicit origin allowlist
const ALLOWED_ORIGINS = ["https://app.example.com"];

Bun.serve({
  fetch(req) {
    const origin = req.headers.get("Origin");
    const corsHeaders: Record<string, string> = {};
    
    if (origin && ALLOWED_ORIGINS.includes(origin)) {
      corsHeaders["Access-Control-Allow-Origin"] = origin;
      corsHeaders["Access-Control-Allow-Credentials"] = "true";
    }
    
    return new Response("data", { headers: corsHeaders });
  },
});

Host Binding

// ❌ Exposed to network (sometimes unintentional)
Bun.serve({
  hostname: "0.0.0.0", // Accessible from any network interface
  port: 3000,
  fetch(req) { /* ... */ },
});

// ✓ Localhost only for development
Bun.serve({
  hostname: "127.0.0.1", // Only local access
  port: 3000,
  fetch(req) { /* ... */ },
});

Bun.spawn() Command Injection

// ❌ CRITICAL: User input in command array (can still be dangerous)
const filename = userInput; // Could be "--version" or other flags
Bun.spawn(["convert", filename, "output.png"]);

// ❌ CRITICAL: Shell execution with user input
Bun.spawn(["sh", "-c", `convert ${userInput} output.png`]);

// ✓ Validate input first
const filename = userInput;
if (!filename.match(/^[a-zA-Z0-9_-]+\.(jpg|png|gif)$/)) {
  throw new Error("Invalid filename");
}
Bun.spawn(["convert", filename, "output.png"]);

// ✓ Use -- to prevent flag injection
Bun.spawn(["convert", "--", filename, "output.png"]);

Bun.file() and Bun.write() Path Traversal

// ❌ HIGH: Path traversal
const userFile = req.query.file; // "../../etc/passwd"
const content = await Bun.file(`./uploads/${userFile}`).text();

// ❌ HIGH: Writing to arbitrary paths
await Bun.write(`./data/${userFile}`, content);

// ✓ Sanitize paths
import { join, basename, resolve } from "path";

const UPLOADS_DIR = resolve("./uploads");

function getSafePath(userInput: string): string {
  const safeName = basename(userInput);
  const fullPath = resolve(join(UPLOADS_DIR, safeName));
  
  if (!fullPath.startsWith(UPLOADS_DIR)) {
    throw new Error("Invalid path");
  }
  
  return fullPath;
}

const content = await Bun.file(getSafePath(userFile)).text();

Bun.password (Secure, but check usage)

// ✓ Bun.password.hash is secure by default (uses argon2)
const hash = await Bun.password.hash(password);

// ✓ Verify passwords
const isValid = await Bun.password.verify(password, hash);

// ⚠️ But check: is it actually being used?
// Common vibecoding mistake: storing plaintext anyway

// ❌ Storing plaintext
db.run("INSERT INTO users (password) VALUES (?)", [password]);

// ✓ Storing hash
const hash = await Bun.password.hash(password);
db.run("INSERT INTO users (password_hash) VALUES (?)", [hash]);

Environment Variables

// Bun.env is the same as process.env

// ❌ Secrets in client-facing code
// If using Bun with a bundler, check what gets bundled

// ✓ Server-only access
const apiKey = Bun.env.API_KEY;
if (!apiKey) {
  throw new Error("API_KEY not configured");
}

// Check bunfig.toml for any exposed variables

bunfig.toml Security

# Check for suspicious configurations

[install]
# ❌ Disabling lockfile = supply chain risk
save-lockfile = false

# ❌ Allowing arbitrary registries
registry = "http://malicious-registry.com"

[run]
# ❌ Disabling sandbox (if applicable)

WebSocket Security

Bun.serve({
  fetch(req, server) {
    if (req.headers.get("upgrade") === "websocket") {
      // ❌ No auth check before upgrade
      server.upgrade(req);
      return;
    }
  },
  websocket: {
    message(ws, message) {
      // ❌ Broadcasting without auth
      ws.publish("chat", message);
    },
  },
});

// ✓ Authenticate before upgrade
Bun.serve({
  fetch(req, server) {
    if (req.headers.get("upgrade") === "websocket") {
      const token = req.headers.get("Authorization");
      const user = await verifyToken(token);
      
      if (!user) {
        return new Response("Unauthorized", { status: 401 });
      }
      
      server.upgrade(req, { data: { user } });
      return;
    }
  },
  websocket: {
    message(ws, message) {
      // Access authenticated user
      const user = ws.data.user;
      // Now safe to process message
    },
  },
});
</vulnerabilities>

<severity_table>

Common Vulnerabilities Summary

IssuePattern to FindSeverity
Shell injection (function call)$(...) or $("...")CRITICAL
SQL injection (function call)sql(...)CRITICAL
SQL string interpolation`...${var}...` in SQLCRITICAL
Argument injectionUser input starting with -HIGH
Path traversalBun.file(userInput)HIGH
Command injectionBun.spawn with user inputHIGH
Open CORSAccess-Control-Allow-Origin: *MEDIUM
Network exposurehostname: "0.0.0.0"MEDIUM
Missing WebSocket authserver.upgrade without auth checkHIGH

</severity_table>

<commands>

Quick Audit Commands

# Find dangerous shell usage (function call instead of tagged template)
rg '\$\s*\(' . -g "*.ts" -g "*.js"

# Find SQL function calls (should be tagged template)
rg 'sql\s*\(' . -g "*.ts" -g "*.js"

# Find string interpolation in queries
rg '(query|run|exec)\s*\(\s*`' . -g "*.ts" -g "*.js"

# Find Bun.spawn usage
rg 'Bun\.spawn' . -g "*.ts" -g "*.js" -A 2

# Find Bun.file with variables (potential path traversal)
rg 'Bun\.file\s*\([^"'\''`]' . -g "*.ts" -g "*.js"

# Find hostname binding
rg 'hostname.*0\.0\.0\.0' . -g "*.ts" -g "*.js"

# Find CORS headers
rg 'Access-Control-Allow-Origin' . -g "*.ts" -g "*.js"

# Find WebSocket upgrades
rg 'server\.upgrade' . -g "*.ts" -g "*.js" -B 5
</commands> <checklist>

Hardening Checklist

  • All $ shell usage is tagged template (no parentheses)
  • All sql usage is tagged template (no parentheses)
  • All bun:sqlite queries use parameterization
  • User input validated before shell/spawn commands
  • -- used to prevent argument injection where applicable
  • File paths sanitized with basename() and path validation
  • CORS restricted to specific origins
  • hostname is 127.0.0.1 for dev, explicit for prod
  • WebSocket connections authenticated before upgrade
  • Bun.password.hash used for passwords (not plaintext)
  • bunfig.toml reviewed for suspicious settings
</checklist>

FAQ

What does the security-bun skill do?

Review Bun runtime security audit patterns. Use for auditing Bun-specific vulnerabilities including shell injection, SQL injection, server security, and process spawning. Use proactively when reviewing Bun apps (bun.lockb, bunfig.toml, or bun: imports present). Examples: - user: "Review this Bun shell script" → audit $ usage and argument injection - user: "Check my bun:sqlite queries" → verify sql tagged template usage - user: "Audit my Bun.serve() setup" → check path traversal and request limits - user: "Is my Bun.spawn() usage safe?" → audit command injection and input validation - user: "Review WebSocket security in Bun" → check authentication before upgrade

How do I install security-bun?

Run npx skills add https://github.com/igorwarzocha/opencode-workflows --skill security-bun in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/security-bun/ (personal) or .claude/skills/security-bun/ (project).

Which AI agents can use security-bun?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is security-bun safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains security-bun?

It is published by igorwarzocha in igorwarzocha/opencode-workflows. It has 104 recorded installs.

More from igorwarzocha/opencode-workflows

View all →

powerpoint

igorwarzocha/opencode-workflows

Handle PowerPoint (.pptx) creation, design, and analysis. Use for pitch decks, status updates, and visual storytelling. Use proactively when precise layout positioning and design principles are needed. Examples: - user: "Create a 10-slide deck for the board meeting" - use design principles + html2pptx - user: "Convert this report into a presentation" - extract text and map to template - user: "Audit this deck for layout issues" - generate thumbnail grid for inspection

Docs & Writing6K installs

word

igorwarzocha/opencode-workflows

Handle Word document (.docx) creation, editing, and analysis with high-fidelity visual review. Use for professional reports, legal documents, and tracked changes. Use proactively when quality and precise formatting are critical. Examples: - user: "Create a professional report in Word" - use python-docx with render loops - user: "Draft a legal contract with redlines" - use ooxml redlining workflow - user: "Extract text from this DOCX while preserving structure" - use pandoc markdown conversion

Docs & Writing774 installs

security-nextjs

igorwarzocha/opencode-workflows

Review Next.js security audit patterns for App Router and Server Actions. Use for auditing NEXTPUBLIC exposure, Server Action auth, and middleware matchers. Use proactively when reviewing Next.js apps. Examples: - user: "Scan Next.js env vars" → find leaked secrets with NEXTPUBLIC prefix - user: "Audit Server Actions" → check for missing auth and input validation - user: "Review Next.js middleware" → verify matcher coverage for protected routes - user: "Check Next.js API routes" → verify auth in app/api and pages/api - user: "Secure Next.js headers" → audit next.config.js for security headers

Security367 installs

create-opencode-plugin

igorwarzocha/opencode-workflows

Create OpenCode plugins using the @opencode-ai/plugin SDK. Use for building custom tools, event hooks, auth providers, or tool execution interception. Use proactively when developing new plugins in .opencode/plugin/ or /.config/opencode/plugin/. Examples: - user: "Create a plugin to block dangerous commands" → implement tool execution before hook with blocking logic - user: "Add a custom tool for jira" → design tool schema and implementation using SDK context - user: "Show toast on file edit" → react to file edit events and display status message - user: "Build a custom auth provider" → implement auth flow for new model provider - user: "Intercept git commits" → add hook to validate commit messages before execution

Backend & APIs347 installs

agent-architect

igorwarzocha/opencode-workflows

Create and refine OpenCode agents via guided Q&A. Use proactively for agent creation, performance improvement, or configuration design. Examples: - user: "Create an agent for code reviews" → ask about scope, permissions, tools, model preferences, generate AGENTS.md frontmatter - user: "My agent ignores context" → analyze description clarity, allowed-tools, permissions, suggest improvements - user: "Add a database expert agent" → gather requirements, set convex-database-expert in subagenttype, configure permissions - user: "Make my agent faster" → suggest smaller models, reduce allowed-tools, tighten permissions

Data & Databases318 installs

opencode-config

igorwarzocha/opencode-workflows

Edit opencode.json, AGENTS.md, and config files. Use proactively for provider setup, permission changes, model config, formatter rules, or environment variables. Examples: - user: "Add Anthropic as a provider" → edit opencode.json providers, add API key baseEnv var, verify with opencode run test - user: "Restrict this agent's permissions" → add permission block to agent config, set deny/allow for tools/fileAccess - user: "Set GPT-5 as default model" → edit global or agent-level model preference, verify model name format - user: "Disable gofmt formatter" → edit formatters section, set languages.gofmt.enabled = false

Backend & APIs308 installs

Popular security skills

View category →

azure-compliance

microsoft/azure-skills

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

OfficialSecurity567K installs

minimal-run-and-audit

lllllllama/rigorpilot-skills

Rigor Run skill for README-first deep learning repo reproduction. Use when the task is specifically to capture or normalize evidence from the selected smoke test or documented inference or evaluation command and write standardized reprooutputs/ files, including patch notes when repository files changed. Do not use for training execution, initial repo intake, generic environment setup, paper lookup, target selection, hidden scientific-meaning changes, or end-to-end orchestration by itself.

Security477.4K installs

seo-audit

coreyhaines31/marketingskills

When the user wants to audit, review, or diagnose SEO issues on their site. Also use when the user mentions "SEO audit," "technical SEO," "why am I not ranking," "SEO issues," "on-page SEO," "meta tags review," "SEO health check," "my traffic dropped," "lost rankings," "not showing up in Google," "site isn't ranking," "Google update hit me," "page speed," "core web vitals," "crawl errors," "indexing issues," "stuck on page 2," "striking distance keywords," "title tag rewrite," "low CTR," "local SEO," "Google Business Profile," or "map pack." Use this even if the user just says something vague like "my SEO is bad" or "help with SEO" — start with an audit. For building pages at scale to target keywords, see programmatic-seo. For adding structured data, see schema. For AI search optimization, see ai-seo.

Security238.7K installs

firebase-security-rules-auditor

firebase/agent-skills

Audits Firebase (Firestore, Cloud Storage) security rules for vulnerabilities, privilege escalation, role bypasses, create vs update inconsistencies, resource exhaustion, type safety, size limits, and hasOnly ownership checks. Use when auditing/reviewing rules, running red-team rule assessments, or scoring against auditor checklists. Don't use for Firebase CLI (login, deploy), Auth, Crashlytics, Remote Config, or database queries.

OfficialSecurity139.1K installs

audit

pbakaus/impeccable

Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.

Security81.9K installs

competitors

coreyhaines31/marketingskills

When the user wants to create competitor comparison or alternative pages for SEO and buyer-facing use. Also use when the user mentions 'alternative page,' 'vs page,' 'competitor comparison,' 'comparison page,' '[Product] vs [Product],' '[Product] alternative,' 'competitive landing pages,' 'how do we compare to X,' 'competitor teardown,' 'audit our competitor pages,' 'are our comparison pages out of date,' or 'competitive asset audit.' Use this for any content that positions your product against competitors. Covers four formats: singular alternative, plural alternatives, you vs competitor, and competitor vs competitor. For auditing existing claims (not researching competitors from scratch, which is competitor-profiling; not technical SEO on these pages, which is seo-audit), use the asset audit here. For internal battle cards and sales-specific competitor docs, see sales-enablement.

Security79.3K installs