stacks-security

$npx mdskill add stacksjs/stacks/stacks-security

Encrypts and hashes sensitive data securely in Stacks applications

  • Automatically generates secure application keys for encryption.
  • Supports AES encryption with optional custom passphrases and decryption.
  • Hashes passwords using bcrypt or argon2, supports rehash detection and algorithm identification.
  • Provides feedback on password strength and hash integrity through built-in functions.

SKILL.md

.github/skills/stacks-securityView on GitHub ↗
---
name: stacks-security
description: Use when implementing security in Stacks — password hashing (bcrypt/argon2), app key generation, AES encryption/decryption, hash verification, rehashing detection, or security configuration (firewall, rate limiting, IP allowlists). Covers @stacksjs/security and config/security.ts.
license: MIT
compatibility: Bun >= 1.3.0, TypeScript
allowed-tools: Read Edit Write Bash Grep Glob
---

# Stacks Security

## Key Paths
- Core package: `storage/framework/core/security/src/`
- Security config: `config/security.ts`
- Hashing config: `config/hashing.ts`

## Source Files
```
security/src/
├── index.ts    # all exports
├── key.ts      # generateAppKey()
├── crypt.ts    # encrypt/decrypt (AES via APP_KEY)
└── hash.ts     # password hashing (bcrypt/argon2)
```

## App Key Generation

```typescript
import { generateAppKey } from '@stacksjs/security'

const key = generateAppKey()  // 32-character random string
// Run via CLI: buddy key:generate
```

## Encryption / Decryption

```typescript
import { encrypt, decrypt } from '@stacksjs/security'

const encrypted = await encrypt('sensitive data')           // uses APP_KEY
const encrypted = await encrypt('data', 'custom-passphrase')
const decrypted = await decrypt(encrypted)
const decrypted = await decrypt(encrypted, 'custom-passphrase')
```

## Password Hashing

```typescript
import { make, check, needsRehash, info, detectAlgorithm } from '@stacksjs/security'

// Hash a password
const hash = await make('password123')                          // bcrypt (default)
const hash = await make('password123', { algorithm: 'argon2' })
const hash = await make('password123', { rounds: 14 })          // bcrypt rounds

// Verify
const valid = await check('password123', hash)  // true/false

// Check if rehash needed (e.g., after changing rounds)
const needs = needsRehash(hash, { rounds: 14 })

// Inspect hash
const hashInfo = info(hash)         // { algorithm, options }
const algo = detectAlgorithm(hash)  // 'bcrypt' | 'argon2' | 'argon2id' | ...
```

### Aliases
- `hashMake` = `make`
- `hashCheck` = `check`
- `hashNeedsRehash` = `needsRehash`
- `hashInfo` = `info`
- `makeHash` = `make`
- `verifyHash` = `check`

### Algorithm-Specific Functions
```typescript
bcryptEncode(value, rounds?)     // bcrypt hash
bcryptVerify(value, hash)        // bcrypt verify
argon2Encode(value, options?)    // argon2 hash
argon2Verify(value, hash)        // argon2 verify
md5Encode(value)                  // MD5 (legacy only)
base64Encode(value)               // base64
base64Verify(value, encoded)      // base64 compare
```

## HashMakeOptions
```typescript
interface HashMakeOptions {
  algorithm?: 'bcrypt' | 'argon2' | 'argon2id' | 'argon2i' | 'argon2d'
  rounds?: number      // bcrypt (default: 12)
  memory?: number      // argon2 (default: 65536)
  time?: number        // argon2 (default: 3)
}
```

## config/hashing.ts
```typescript
{
  driver: 'bcrypt',
  bcrypt: { rounds: 12 },
  argon2: { memory: 65536, time: 3 }
}
```

## config/security.ts
```typescript
{
  firewall: {
    enabled: true,
    countryCodes: [],                // block by country
    ipAddresses: {
      allowlist: [],
      blocklist: []
    },
    rateLimitPerMinute: 500,
    useIpReputationLists: true,
    useKnownBadInputsRuleSet: true
  }
}
```

## Gotchas
- Default hashing is bcrypt with 12 rounds — sufficient for most applications
- `needsRehash()` compares current hash options against provided options — useful after config changes
- APP_KEY is used for `encrypt()`/`decrypt()` — generate via `buddy key:generate`
- APP_KEY format is colon-separated (validated during deployment)
- Argon2 requires more memory/time but is more resistant to GPU attacks
- `md5Encode()` exists for legacy compatibility only — never use for passwords
- The firewall config is used by cloud deployment for WAF rules
- Rate limiting is per-minute per-IP (500 default)

More from stacksjs/stacks

SkillDescription
stacks-actionsUse when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/actions/.
stacks-aiUse when integrating AI capabilities into a Stacks application — using Anthropic/OpenAI/Ollama/AWS Bedrock drivers, image generation (DALL-E), vision analysis, RAG/vector search, embeddings, MCP (Model Context Protocol) clients, text summarization, sentiment analysis, content classification, personalization, or the buddy AI assistant. Covers @stacksjs/ai and config/ai.ts.
stacks-aliasUse when working with path aliases in a Stacks project — import resolution, module aliasing, or debugging import paths. Covers @stacksjs/alias which defines 260+ path mappings for the entire framework.
stacks-analyticsUse when adding analytics to a Stacks application — configuring Fathom or self-hosted analytics, generating tracking scripts, privacy-friendly analytics setup, or the analytics configuration. Covers @stacksjs/analytics and config/analytics.ts.
stacks-apiUse when building, modifying, or debugging API endpoints in a Stacks application — defining routes, handling requests, API middleware, working with the API server, HTTP client (fetcher), API resources, or OpenAPI generation. Covers both @stacksjs/api utilities and the stacks-api server implementation.
stacks-arraysUse when working with array utilities in Stacks — statistical operations (average, median, mode, standard deviation, z-score, percentile, covariance), array manipulation (unique, flatten, partition, shuffle, sample, move), containment checks, or the Arr facade. Covers @stacksjs/arrays.
stacks-authUse when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.
stacks-auto-importsUse when working with the Stacks auto-import system — understanding how browser and server auto-imports work, configuring auto-imported functions/models/composables, the auto-import manifests, type generation, or how globals are injected. Covers the auto-import pipeline at storage/framework/auto-imports/.
stacks-brandkitUse when defining or exploring a brand identity for a Stacks project and you want premium brand-kit REFERENCE IMAGES first - logo directions, palettes, typography specimens, identity boards, and application/mockup decks. Generates IMAGES ONLY, never code. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems with intentional logo concepting, sparse type, strong symbolic meaning, and disciplined palettes a coding step can build against.
stacks-browseUse for headless browser QA on Stacks applications — navigation, screenshots, responsive testing, console/network monitoring, and accessibility snapshots. Dependency-free: drives a system browser over the Chrome DevTools Protocol using only Bun (no Playwright/Puppeteer). Invoke with /stacks-browse.