
Security News
Socket Releases Free Certified Patches for Critical vm2 Sandbox Escape
A critical vm2 sandbox escape can allow untrusted JavaScript to break isolation and execute commands on the host Node.js process.
@samiyev/guardian
Advanced tools
Research-backed code quality guardian for AI-assisted development. Detects hardcodes, secrets, circular deps, framework leaks, entity exposure, and 9 architecture violations. Enforces Clean Architecture/DDD principles. Works with GitHub Copilot, Cursor, W
Your AI Coding Companion - Keep the Vibe, Ditch the Tech Debt
Code quality guardian for vibe coders and enterprise teams - because AI writes fast, Guardian keeps it clean.
Perfect for:
- š Vibe Coders: Ship fast with GitHub Copilot, Cursor, Windsurf, Claude, ChatGPT while maintaining quality
- š¢ Enterprise Teams: Enforce architectural standards and code quality at scale
- š Code Review Automation: Catch issues before human reviewers see them
⨠Hardcode Detection
š Circular Dependency Detection
š Naming Convention Detection
š Framework Leak Detection
š Entity Exposure Detection
ā¬ļø Dependency Direction Enforcement
š¦ Repository Pattern Validation
š Aggregate Boundary Validation
š Secret Detection ⨠NEW in v0.8.0
𩺠Anemic Domain Model Detection ⨠NEW in v0.9.0
šÆ Severity-Based Prioritization
--only-critical or --min-severity highšļø Clean Architecture Enforcement
š Developer & Enterprise Friendly
š¤ Built for Vibe Coding
The Problem: AI assistants (GitHub Copilot, Cursor, Windsurf, Claude, ChatGPT) are incredible at shipping features fast, but they love hardcoding values and sometimes ignore architectural patterns. You're moving fast, but accumulating tech debt.
The Solution: Guardian is your quality safety net. Code with AI at full speed, then let Guardian catch the issues before they hit production.
1. š¤ Ask Claude/GPT: "Build me a user authentication service"
ā AI generates 200 lines in 10 seconds
2. š”ļø Run Guardian: npx @samiyev/guardian check ./src
ā Finds: hardcoded JWT secret, magic timeouts, circular deps
3. š Feed Guardian's output back to AI: "Fix these 5 issues"
ā AI refactors in 5 seconds with proper constants
4. ā
Ship clean code in minutes, not hours
Hardcoded Secrets & Config (Most Common)
// ā AI writes this
const jwt = sign(payload, "super-secret-key-123", { expiresIn: 3600 })
app.listen(3000)
setTimeout(retry, 5000)
// ā
Guardian suggests
const jwt = sign(payload, JWT_SECRET, { expiresIn: TOKEN_EXPIRY_SECONDS })
app.listen(DEFAULT_PORT)
setTimeout(retry, RETRY_TIMEOUT_MS)
Architecture Violations
// ā AI might do this
// domain/User.ts importing from infrastructure
import { database } from '../infrastructure/database'
// ā
Guardian catches it
ā ļø Domain layer cannot import from infrastructure
š” Use dependency injection or repository pattern
Circular Dependencies
// ā AI creates these accidentally
UserService ā OrderService ā UserService
// ā
Guardian finds the cycle
š Circular dependency detected
š” Extract shared logic to a common service
Think of Guardian as a senior developer reviewing AI's pull requests:
The Challenge: Large codebases with multiple developers, junior devs learning patterns, legacy code, and AI adoption creating inconsistent code quality.
The Solution: Guardian enforces your architectural standards automatically - no more manual code review for common issues.
šļø Architectural Governance
// Guardian enforces Clean Architecture rules across teams
// ā Domain layer importing from infrastructure? Blocked.
// ā Wrong naming conventions? Caught immediately.
// ā Circular dependencies? Detected before merge.
// Result: Consistent architecture across 100+ developers
š„ Onboarding & Training
// New developer writes code
// Guardian provides instant feedback with suggestions
// Junior devs learn patterns from Guardian's violations
// Result: Faster onboarding, consistent code quality from day 1
š Security & Compliance
// Guardian catches before production:
// - Hardcoded API keys and secrets
// - Exposed database credentials
// - Magic configuration values
// Result: Prevent security incidents, pass compliance audits
š Technical Debt Management
// Track metrics over time:
// - Number of hardcoded values per sprint
// - Architecture violations by team
// - Circular dependency trends
// Result: Data-driven refactoring decisions
š AI Adoption at Scale
// Your team starts using GitHub Copilot/Claude
// Guardian acts as quality gate for AI-generated code
// Developers get instant feedback on AI suggestions
// Result: Leverage AI speed without sacrificing quality
CI/CD Pipeline
# GitHub Actions / GitLab CI / Jenkins
- name: Guardian Quality Gate
run: |
npm install -g @samiyev/guardian
guardian check ./src --format json > guardian-report.json
# Fail build if critical violations found
guardian check ./src --fail-on hardcode --fail-on circular
Pull Request Automation
# Auto-comment on PRs with Guardian findings
- name: PR Guardian Check
run: |
guardian check ./src --format markdown | \
gh pr comment ${{ github.event.pull_request.number }} --body-file -
Pre-commit Hooks (Husky)
{
"husky": {
"hooks": {
"pre-commit": "guardian check --staged --fail-on hardcode"
}
}
}
Metrics Dashboard
// Track quality metrics across sprints
import { analyzeProject } from "@samiyev/guardian"
const metrics = await analyzeProject({ projectPath: "./src" })
// Export to your analytics platform
await reportMetrics({
hardcodedValues: metrics.hardcodeViolations.length,
circularDeps: metrics.circularDependencyViolations.length,
architectureViolations: metrics.architectureViolations.length,
timestamp: Date.now(),
})
| Benefit | Impact |
|---|---|
| Reduced Code Review Time | Save 30-40% time on reviewing common issues |
| Consistent Standards | All teams follow same architectural patterns |
| Faster Onboarding | New devs learn from instant Guardian feedback |
| Security | Catch hardcoded secrets before production |
| AI Enablement | Safely adopt AI coding tools at scale |
| Technical Debt Visibility | Metrics and trends for data-driven decisions |
npm install @samiyev/guardian
# or
pnpm add @samiyev/guardian
# or
yarn add @samiyev/guardian
30-Second Setup:
# 1. Install globally for instant use
npm install -g @samiyev/guardian
# 2. Run on your AI-generated code
cd your-project
guardian check ./src
# 3. Copy output and paste into Claude/GPT
# "Here's what Guardian found, please fix these issues"
# 4. Done! Ship it š
Integration with Claude Code / Cursor:
// Add this to your project root: guardian.config.js
module.exports = {
exclude: ["node_modules", "dist", "build"],
rules: {
hardcode: true, // Catch magic numbers/strings
architecture: true, // Enforce Clean Architecture
circular: true, // Find circular dependencies
naming: true, // Check naming conventions
},
}
// Then in your AI chat:
// "Before each commit, run: guardian check ./src and fix any issues"
import { analyzeProject } from "@samiyev/guardian"
const result = await analyzeProject({
projectPath: "./src",
excludeDirs: ["node_modules", "dist"],
})
console.log(`Found ${result.hardcodeViolations.length} hardcoded values`)
console.log(`Found ${result.secretViolations.length} hardcoded secrets š`)
// Check for critical security issues first!
result.secretViolations.forEach((violation) => {
console.log(`š CRITICAL: ${violation.file}:${violation.line}`)
console.log(` Secret Type: ${violation.secretType}`)
console.log(` ${violation.message}`)
console.log(` ā ļø Rotate this secret immediately!`)
})
result.hardcodeViolations.forEach((violation) => {
console.log(`${violation.file}:${violation.line}`)
console.log(` Type: ${violation.type}`)
console.log(` Value: ${violation.value}`)
console.log(` š” Suggested: ${violation.suggestedConstantName}`)
console.log(` š Location: ${violation.suggestedLocation}`)
})
Guardian can also be used as a command-line tool:
# Check your project
npx @samiyev/guardian check ./src
# With custom excludes
npx @samiyev/guardian check ./src --exclude node_modules dist build
# Verbose output
npx @samiyev/guardian check ./src --verbose
# Skip specific checks
npx @samiyev/guardian check ./src --no-hardcode # Skip hardcode detection
npx @samiyev/guardian check ./src --no-architecture # Skip architecture checks
# Filter by severity (perfect for finding secrets first!)
npx @samiyev/guardian check ./src --only-critical # Show only critical issues (secrets, circular deps)
npx @samiyev/guardian check ./src --min-severity high # Show high and critical only
# Limit detailed output (useful for large codebases)
npx @samiyev/guardian check ./src --limit 10 # Show first 10 violations per category
npx @samiyev/guardian check ./src -l 20 # Short form
# Combine options
npx @samiyev/guardian check ./src --only-critical --limit 5 # Top 5 critical issues
# Show help
npx @samiyev/guardian --help
# Show version
npx @samiyev/guardian --version
Example output:
š”ļø Guardian - Analyzing your code...
š Project Metrics:
Files analyzed: 45
Total functions: 128
Total imports: 234
š¦ Layer Distribution:
domain: 12 files
application: 8 files
infrastructure: 15 files
shared: 10 files
ā ļø Found 2 architecture violations:
1. src/domain/services/UserService.ts
Rule: clean-architecture
Layer "domain" cannot import from "infrastructure"
š Found 1 circular dependencies:
1. Circular dependency detected: src/services/UserService.ts ā src/services/OrderService.ts ā src/services/UserService.ts
Severity: error
Cycle path:
1. src/services/UserService.ts
2. src/services/OrderService.ts
3. src/services/UserService.ts (back to start)
š Found 3 naming convention violations:
1. src/application/use-cases/user.ts
Rule: naming-convention
Layer: application
Type: wrong-verb-noun
Expected: Verb + Noun in PascalCase (CreateUser.ts, UpdateProfile.ts)
Actual: user.ts
š” Suggestion: Start with a verb like: Analyze, Create, Update, Delete, Get
2. src/domain/UserDto.ts
Rule: naming-convention
Layer: domain
Type: forbidden-pattern
Expected: PascalCase noun (User.ts, Order.ts)
Actual: UserDto.ts
š” Suggestion: Move to application or infrastructure layer, or rename to follow domain patterns
š Found 5 hardcoded values:
1. src/api/server.ts:15:20
Type: magic-number
Value: 3000
Context: app.listen(3000)
š” Suggested: DEFAULT_PORT
š Location: infrastructure/config
2. src/services/auth.ts:42:35
Type: magic-string
Value: "http://localhost:8080"
Context: const apiUrl = "http://localhost:8080"
š” Suggested: API_BASE_URL
š Location: shared/constants
ā Found 7 issues total
š” Tip: Fix these issues to improve code quality and maintainability.
analyzeProject(options)Analyzes a project for code quality issues.
interface AnalyzeProjectRequest {
projectPath: string // Path to analyze
excludeDirs?: string[] // Directories to exclude
}
interface AnalyzeProjectResponse {
// Violations
hardcodeViolations: HardcodeViolation[]
violations: ArchitectureViolation[]
circularDependencyViolations: CircularDependencyViolation[]
namingViolations: NamingViolation[]
frameworkLeakViolations: FrameworkLeakViolation[]
entityExposureViolations: EntityExposureViolation[]
dependencyDirectionViolations: DependencyDirectionViolation[]
repositoryPatternViolations: RepositoryPatternViolation[]
// Metrics
metrics: ProjectMetrics
}
interface HardcodeViolation {
file: string
line: number
column: number
type: "magic-number" | "magic-string"
value: string | number
context: string
severity: "critical" | "high" | "medium" | "low"
suggestion: {
constantName: string
location: string
}
}
interface CircularDependencyViolation {
rule: "circular-dependency"
message: string
cycle: string[]
severity: "critical" | "high" | "medium" | "low"
}
interface NamingViolation {
file: string
fileName: string
layer: string
type: string
message: string
suggestion?: string
severity: "critical" | "high" | "medium" | "low"
}
interface FrameworkLeakViolation {
file: string
packageName: string
category: string
categoryDescription: string
layer: string
rule: string
message: string
suggestion: string
severity: "critical" | "high" | "medium" | "low"
}
interface EntityExposureViolation {
file: string
line?: number
entityName: string
returnType: string
methodName?: string
layer: string
rule: string
message: string
suggestion: string
severity: "critical" | "high" | "medium" | "low"
}
interface DependencyDirectionViolation {
file: string
fromLayer: string
toLayer: string
importPath: string
message: string
suggestion: string
severity: "critical" | "high" | "medium" | "low"
}
interface RepositoryPatternViolation {
file: string
layer: string
violationType: string
details: string
message: string
suggestion: string
severity: "critical" | "high" | "medium" | "low"
}
interface ProjectMetrics {
totalFiles: number
totalFunctions: number
totalImports: number
layerDistribution: Record<string, number>
}
// ā Detected
setTimeout(() => {}, 5000)
const maxRetries = 3
const port = 8080
// ā
Not detected (allowed numbers: -1, 0, 1, 2, 10, 100, 1000)
const items = []
const index = 0
const increment = 1
// ā
Not detected (exported constants)
export const CONFIG = {
timeout: 5000,
port: 8080,
} as const
// ā Detected
const url = "http://localhost:8080"
const dbUrl = "mongodb://localhost:27017/db"
// ā
Not detected
console.log("debug message") // console logs ignored
import { foo } from "bar" // imports ignored
test("should work", () => {}) // tests ignored
// ā
Not detected (exported constants)
export const API_CONFIG = {
baseUrl: "http://localhost",
} as const
// ā Detected - Simple cycle
// UserService.ts
import { OrderService } from './OrderService'
export class UserService {
constructor(private orderService: OrderService) {}
}
// OrderService.ts
import { UserService } from './UserService' // Circular!
export class OrderService {
constructor(private userService: UserService) {}
}
// ā
Fixed - Use interfaces or events
// UserService.ts
import { IOrderService } from './interfaces/IOrderService'
export class UserService {
constructor(private orderService: IOrderService) {}
}
// OrderService.ts
import { IUserService } from './interfaces/IUserService'
export class OrderService implements IOrderService {
constructor(private userService: IUserService) {}
}
Guardian enforces Clean Architecture naming patterns based on the layer:
// ā Domain Layer - Wrong names
// domain/userDto.ts - DTOs don't belong in domain
// domain/UserController.ts - Controllers don't belong in domain
// domain/user.ts - Should be PascalCase
// ā
Domain Layer - Correct names
// domain/entities/User.ts - PascalCase noun
// domain/entities/Order.ts - PascalCase noun
// domain/services/UserService.ts - *Service suffix
// domain/repositories/IUserRepository.ts - I*Repository prefix
// domain/value-objects/Email.ts - PascalCase noun
// ā Application Layer - Wrong names
// application/use-cases/user.ts - Should start with verb
// application/use-cases/User.ts - Should start with verb
// application/dtos/userDto.ts - Should be PascalCase
// ā
Application Layer - Correct names
// application/use-cases/CreateUser.ts - Verb + Noun
// application/use-cases/UpdateProfile.ts - Verb + Noun
// application/use-cases/AnalyzeProject.ts - Verb + Noun
// application/dtos/UserDto.ts - *Dto suffix
// application/dtos/CreateUserRequest.ts - *Request suffix
// application/mappers/UserMapper.ts - *Mapper suffix
// ā Infrastructure Layer - Wrong names
// infrastructure/controllers/userController.ts - Should be PascalCase
// infrastructure/repositories/user.ts - Should have *Repository suffix
// ā
Infrastructure Layer - Correct names
// infrastructure/controllers/UserController.ts - *Controller suffix
// infrastructure/repositories/MongoUserRepository.ts - *Repository suffix
// infrastructure/services/EmailService.ts - *Service suffix
// infrastructure/adapters/S3StorageAdapter.ts - *Adapter suffix
Supported Use Case Verbs: Analyze, Create, Update, Delete, Get, Find, List, Search, Validate, Calculate, Generate, Send, Fetch, Process, Execute, Handle, Register, Authenticate, Authorize, Import, Export, Place, Cancel, Approve, Reject, Confirm
Guardian includes comprehensive examples of good and bad architecture patterns in the examples/ directory:
Good Architecture Examples (29 files):
Bad Architecture Examples (7 files):
Use these examples to:
See examples/README.md and examples/SUMMARY.md for detailed documentation.
Guardian analyzes context to suggest meaningful constant names:
// timeout ā TIMEOUT_MS
setTimeout(() => {}, 5000)
// retry ā MAX_RETRIES
const maxRetries = 3
// port ā DEFAULT_PORT
const port = 8080
// http:// ā API_BASE_URL
const url = "http://localhost"
import { analyzeProject } from "@samiyev/guardian"
const result = await analyzeProject({ projectPath: "./src" })
if (result.hardcodeViolations.length > 0) {
console.error(`Found ${result.hardcodeViolations.length} hardcoded values`)
process.exit(1)
}
{
"husky": {
"hooks": {
"pre-commit": "node scripts/check-hardcodes.js"
}
}
}
import { HardcodeDetector } from "@samiyev/guardian"
const detector = new HardcodeDetector()
const code = `const timeout = 5000`
const violations = detector.detectAll(code, "file.ts")
// [{ value: 5000, type: "magic-number", ... }]
Use Guardian's output to guide your AI assistant:
# 1. Generate code with AI
# (Ask Claude: "Create a REST API with user authentication")
# 2. Run Guardian
npx @samiyev/guardian check ./src > guardian-report.txt
# 3. Feed back to AI
# (Show Claude the report: "Fix these issues Guardian found")
# 4. Verify fixes
npx @samiyev/guardian check ./src
Catch issues before they hit your repo:
# .husky/pre-commit
#!/bin/sh
npx @samiyev/guardian check ./src
if [ $? -ne 0 ]; then
echo "ā Guardian found issues. Fix them or commit with --no-verify"
exit 1
fi
Add to your GitHub Actions or GitLab CI:
# .github/workflows/ai-quality-check.yml
name: AI Code Quality
on: [push, pull_request]
jobs:
guardian-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm install -g @samiyev/guardian
- run: guardian check ./src
Watch mode for real-time feedback as AI generates code:
# Terminal 1: AI generates code
# (You're chatting with Claude/GPT)
# Terminal 2: Guardian watches for changes
while true; do
clear
npx @samiyev/guardian check ./src --no-exit
sleep 2
done
Use Guardian to create better prompts:
**Before (Generic prompt):**
"Create a user service with CRUD operations"
**After (Guardian-informed prompt):**
"Create a user service with CRUD operations. Follow these rules:
- No hardcoded values (use constants from shared/constants)
- Follow Clean Architecture (domain/application/infrastructure layers)
- Name use cases as VerbNoun (e.g., CreateUser.ts)
- No circular dependencies
- Export all configuration as constants"
Result: AI generates cleaner code from the start!
import {
FileScanner,
CodeParser,
HardcodeDetector,
} from "@samiyev/guardian"
// Scan files
const scanner = new FileScanner()
const files = await scanner.scanDirectory("./src", {
exclude: ["node_modules"],
extensions: [".ts", ".tsx"],
})
// Parse code
const parser = new CodeParser()
const tree = parser.parseTypeScript(code)
const functions = parser.extractFunctions(tree)
// Detect hardcodes
const detector = new HardcodeDetector()
const violations = detector.detectAll(code, "file.ts")
Guardian follows Clean Architecture principles:
@samiyev/guardian/
āāā domain/ # Business logic & interfaces
ā āāā entities/ # BaseEntity, SourceFile
ā āāā value-objects/# HardcodedValue, ProjectPath
ā āāā services/ # ICodeParser, IHardcodeDetector
ā āāā repositories/ # IRepository
āāā application/ # Use cases
ā āāā use-cases/ # AnalyzeProject
āāā infrastructure/ # External services
ā āāā parsers/ # CodeParser (tree-sitter)
ā āāā scanners/ # FileScanner
ā āāā analyzers/ # HardcodeDetector
āāā api/ # Public API
āāā analyzeProject()
Q: Will Guardian slow down my AI workflow? A: No! Run it after AI generates code, not during. Analysis takes 1-2 seconds for most projects.
Q: Can I use this with any AI coding assistant? A: Yes! Works with GitHub Copilot, Cursor, Windsurf, Claude, ChatGPT, Cline, or any tool that generates TypeScript/JavaScript.
Q: Does Guardian replace ESLint/Prettier? A: No, it complements them. ESLint checks syntax, Guardian checks architecture and hardcodes.
Q: What if I'm just prototyping? A: Perfect use case! Guardian helps you identify tech debt so you can decide what to fix before production.
Q: Can AI fix Guardian's findings automatically? A: Yes! Copy Guardian's output, paste into Claude, ChatGPT, or your AI assistant with "fix these issues", and watch the magic.
Contributions are welcome! Please feel free to submit a Pull Request.
Built with ā¤ļø for the vibe coding community.
MIT Ā© Fozilbek Samiyev
FAQs
Research-backed code quality guardian for AI-assisted development. Detects hardcodes, secrets, circular deps, framework leaks, entity exposure, and 9 architecture violations. Enforces Clean Architecture/DDD principles. Works with GitHub Copilot, Cursor, W
We found that @samiyev/guardian demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
A critical vm2 sandbox escape can allow untrusted JavaScript to break isolation and execute commands on the host Node.js process.

Research
Five malicious NuGet packages impersonate Chinese .NET libraries to deploy a stealer targeting browser credentials, crypto wallets, SSH keys, and local files.

Security News
pnpm 11 turns on a 1-day Minimum Release Age and blocks exotic subdeps by default, adding safeguards against fast-moving supply chain attacks.