replit-policy-guardrails

0
1
Source

Implement Replit lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Replit integrations, implementing pre-commit hooks, or configuring CI policy checks for Replit best practices. Trigger with phrases like "replit policy", "replit lint", "replit guardrails", "replit best practices check", "replit eslint".

Install

mkdir -p .claude/skills/replit-policy-guardrails && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6905" && unzip -o skill.zip -d .claude/skills/replit-policy-guardrails && rm skill.zip

Installs to .claude/skills/replit-policy-guardrails

About this skill

Replit Policy Guardrails

Overview

Policy enforcement for Replit-hosted applications. Replit's public-by-default Repls, shared hosting, and resource limits require specific guardrails around secrets exposure, resource consumption, deployment security, and endpoint protection.

Prerequisites

  • Replit account with Deployment access
  • Understanding of Replit's security model
  • Awareness of Replit's Terms of Service

Instructions

Step 1: Secrets Exposure Prevention

Replit Repls are public by default on free plans. Source code is visible to anyone.

# CRITICAL POLICY: Never hardcode secrets in source files

# BAD — visible to anyone viewing your Repl
API_KEY = "sk-live-abc123"
DB_PASSWORD = "p@ssw0rd"

# GOOD — use Replit Secrets (AES-256 encrypted)
import os

API_KEY = os.environ.get("API_KEY")
if not API_KEY:
    raise RuntimeError("API_KEY not set. Add it in the Secrets tab (lock icon).")

# Startup validation — fail fast if secrets missing
REQUIRED_SECRETS = ["API_KEY", "DATABASE_URL", "JWT_SECRET"]
missing = [s for s in REQUIRED_SECRETS if not os.environ.get(s)]
if missing:
    raise RuntimeError(f"Missing required secrets: {missing}")

Automated secret detection:

// Pre-deploy check script: scripts/check-secrets.ts
import { readFileSync, readdirSync, statSync } from 'fs';
import { join } from 'path';

const SECRET_PATTERNS = [
  /sk[-_](?:live|test)[-_]\w{20,}/,     // API keys
  /(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]+['"]/i,
  /(?:secret|token)\s*[:=]\s*['"][^'"]{10,}['"]/i,
  /-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/,
  /eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+/,  // JWT tokens
];

function scanFile(filepath: string): string[] {
  const content = readFileSync(filepath, 'utf-8');
  const issues: string[] = [];

  SECRET_PATTERNS.forEach((pattern, i) => {
    if (pattern.test(content)) {
      issues.push(`${filepath}: potential secret found (pattern ${i})`);
    }
  });

  return issues;
}

function scanDirectory(dir: string): string[] {
  const issues: string[] = [];
  const entries = readdirSync(dir);

  for (const entry of entries) {
    if (['.git', 'node_modules', '.cache', 'dist'].includes(entry)) continue;
    const path = join(dir, entry);
    if (statSync(path).isDirectory()) {
      issues.push(...scanDirectory(path));
    } else if (/\.(ts|js|py|json|env|yaml|yml|toml)$/.test(entry)) {
      issues.push(...scanFile(path));
    }
  }

  return issues;
}

const issues = scanDirectory('.');
if (issues.length > 0) {
  console.error('SECRET SCAN FAILED:');
  issues.forEach(i => console.error(`  ${i}`));
  process.exit(1);
}
console.log('Secret scan passed: no hardcoded secrets found.');

Step 2: Resource Usage Guards

Replit containers have CPU and memory limits. Guard against runaway processes.

import resource
import signal
import os

# Set memory limit (match your deployment tier)
MEMORY_LIMIT_MB = int(os.environ.get("MEMORY_LIMIT_MB", "512"))
resource.setrlimit(
    resource.RLIMIT_AS,
    (MEMORY_LIMIT_MB * 1024 * 1024, MEMORY_LIMIT_MB * 1024 * 1024)
)

# Per-request CPU timeout
def timeout_handler(signum, frame):
    raise TimeoutError("Request exceeded CPU time limit")

signal.signal(signal.SIGALRM, timeout_handler)

@app.route('/process')
def process_request():
    signal.alarm(30)  # 30 second max
    try:
        result = heavy_computation()
        return jsonify(result)
    except TimeoutError:
        return jsonify({"error": "Request timed out"}), 504
    finally:
        signal.alarm(0)
// Node.js: memory and request size limits
app.use(express.json({ limit: '1mb' }));  // Prevent payload bombs
app.use(express.urlencoded({ limit: '1mb', extended: true }));

// Monitor and alert on high memory
setInterval(() => {
  const heapMB = Math.round(process.memoryUsage().heapUsed / 1024 / 1024);
  if (heapMB > 400) {  // Approaching 512MB limit
    console.warn(`HIGH MEMORY: ${heapMB}MB — consider restart`);
  }
}, 30000);

Step 3: Endpoint Protection

// Protect all data endpoints with authentication
import { Request, Response, NextFunction } from 'express';

function requireAuth(req: Request, res: Response, next: NextFunction) {
  const userId = req.headers['x-replit-user-id'];
  if (!userId) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  next();
}

// Apply to all API routes
app.use('/api', requireAuth);

// Admin-only routes: check specific user IDs or roles
function requireAdmin(req: Request, res: Response, next: NextFunction) {
  const userId = req.headers['x-replit-user-id'] as string;
  const adminIds = (process.env.ADMIN_USER_IDS || '').split(',');

  if (!adminIds.includes(userId)) {
    return res.status(403).json({ error: 'Admin access required' });
  }
  next();
}

app.use('/admin', requireAuth, requireAdmin);

Step 4: Deployment Visibility Controls

// Validate deployment configuration at startup
function validateDeploymentSecurity() {
  const warnings: string[] = [];

  // Check if running as Deployment vs Repl
  if (!process.env.REPL_DEPLOYMENT && process.env.NODE_ENV === 'production') {
    warnings.push('WARNING: Production NODE_ENV but not a Deployment. Container may sleep.');
  }

  // Check debug mode
  if (process.env.DEBUG && process.env.NODE_ENV === 'production') {
    warnings.push('WARNING: DEBUG enabled in production');
  }

  // Check CORS
  if (process.env.CORS_ORIGIN === '*' && process.env.NODE_ENV === 'production') {
    warnings.push('WARNING: CORS allows all origins in production');
  }

  if (warnings.length) {
    warnings.forEach(w => console.warn(w));
  }

  return { secure: warnings.length === 0, warnings };
}

// Run at startup
const security = validateDeploymentSecurity();
if (!security.secure) {
  console.warn('Security warnings detected. Review before production deployment.');
}

Step 5: Security Audit Checklist

## Replit Security Audit

### Secrets (Critical)
- [ ] No API keys in source code
- [ ] All secrets in Replit Secrets tab
- [ ] Startup validates required secrets
- [ ] Secret Scanner warnings addressed

### Access Control
- [ ] All data endpoints require authentication
- [ ] Admin routes have role-based access
- [ ] Rate limiting on public endpoints
- [ ] CORS configured for specific origins

### Data Protection
- [ ] Parameterized SQL queries (no string concatenation)
- [ ] Input validation on all user data
- [ ] Error responses don't expose internals
- [ ] Logs don't contain PII or secrets

### Deployment
- [ ] Production uses Deployments (not Repl "Run")
- [ ] NODE_ENV set to "production"
- [ ] Health endpoint doesn't expose secrets
- [ ] Custom domain has SSL (auto-provisioned)

### Resources
- [ ] Memory limits appropriate for tier
- [ ] Request size limits configured
- [ ] Per-request timeout enforced
- [ ] Payload size validation

Error Handling

IssueCauseSolution
Secret leaked in codeNot using Secrets tabRotate key, move to Secrets
OOM killNo memory limitsSet resource limits, monitor usage
Unauthorized data accessMissing auth middlewareAdd requireAuth to all /api routes
Debug info in productionDebug mode not disabledCheck NODE_ENV and DEBUG env vars

Resources

Next Steps

For architecture patterns, see replit-architecture-variants.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

11340

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

9033

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

18828

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5519

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,6851,430

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,2701,335

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,5441,153

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,359809

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,265728

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,493684