Environment & Config Validator: Lint .env, package.json & Docker Compose

⚙️ Infrastructure Configuration Linter

Environment & Config Validator

Instantly detect syntax errors, structural anomalies, and formatting violations in .env files, package.json, and Docker Compose manifests.

⚪ Select a file type and paste your configuration...
Waiting for input to generate diagnostics...

Why Configuration Validation is Critical

A single missing comma in package.json, an unquoted space in a .env file, or an incorrect indentation level in docker-compose.yml can crash automated CI/CD pipelines, cause silent production failures, or expose environment secrets. Pre-deployment linting acts as a fundamental safeguard for Infrastructure as Code (IaC).

Zero-Telemetry Local Execution

This utility computes semantic parsing and lexical analysis strictly within your browser's local JavaScript runtime. Your proprietary database connection strings, AWS credentials, and infrastructure architectures never touch an external server.

🔒
100% Client-side: Zero-knowledge local browser processing

All parsing rules, token validation, and error diagnostics execute natively within your browser's V8 engine. Sensitive .env secrets and private repository manifests are never transmitted across the network or stored in remote cache layers.

Deep-Dive: The Mechanics of Configuration Parsing

Modern cloud-native applications rely on a trifecta of configuration syntaxes: POSIX-compliant environment variable files (.env), strict JSON package manifests (package.json), and indentation-sensitive YAML orchestrations (docker-compose.yml). Because each format answers to a completely different specification, they suffer from distinct lexical parsing hazards.

  • .env (Dotenv) Lexical Analysis: Standard .env parsers evaluate files line-by-line using POSIX-style shell variable rules. A valid line must follow the KEY=VALUE structure. Validation engines must check for unquoted values containing spaces (e.g., SECRET=my val breaks parsers; it must be SECRET="my val"), identify illegal characters in keys (only alphanumeric and underscores are universally permitted), and detect colliding duplicate keys.
  • package.json Validation (RFC 8259 + NPM Spec): A Node.js manifest must first pass strict JSON parsing (no trailing commas, keys must be double-quoted). Beyond raw syntax, domain-specific validation is applied: the name must be URL-safe, the version must conform strictly to Semantic Versioning (SemVer v2.0.0), and dependency maps must not contain overlapping identical packages across dependencies and devDependencies.
  • Docker Compose (YAML) Tokenization: YAML relies on the off-side rule (scoping via indentation). Validators track state depth using a stack memory structure. The most common structural failure is the accidental mixing of spaces and tabs, which triggers fatal YAMLException errors. Furthermore, Compose manifests require a top-level services map to be considered orchestrator-valid.

Real-World Engineering Use Cases

1. CI/CD Pipeline Build Gates (GitHub Actions / GitLab CI)

Automated pipelines inject package.json and YAML linting stages prior to initiating expensive Docker image builds. If a developer accidentally leaves a trailing comma in the JSON manifest or misaligns a YAML volume mount array, the pipeline fails fast, preventing broken application containers from reaching the Kubernetes registry.

2. Local Development Secret Management (.env)

When spinning up local environments, developers frequently copy-paste database connection strings or JWT secrets into .env files. A validator immediately identifies invalid unquoted hashes (e.g., passwords containing a literal # symbol which the parser treats as a comment), saving hours of debugging "Authentication Failed" errors.

3. Container Orchestration & Multi-Service Mocking

Docker Compose files define inter-container networks and volume mapping. Validating the docker-compose.yml file ensures that core schema constraints—such as confirming that services exist at the root depth and that environment variable arrays are properly formatted—are met before Docker daemon orchestration attempts to launch the stack.

Implementation Examples

Validating configurations programmatically ensures application boot resilience. Below are production implementations for loading and validating .env and package.json configurations in Node.js and Python.

Node.js Implementation (dotenv & JSON parse)

// Config loader validation script for backend microservices
import fs from 'node:fs';
import dotenv from 'dotenv';

export function validateEnvironmentAndPackage() {
  const diagnostics = { valid: true, errors: [] };

  // 1. Validate package.json
  try {
    const pkgRaw = fs.readFileSync('./package.json', 'utf-8');
    const pkg = JSON.parse(pkgRaw);
    if (!pkg.name || !pkg.version) {
      diagnostics.errors.push("package.json is missing required 'name' or 'version' keys.");
      diagnostics.valid = false;
    }
  } catch (err) {
    diagnostics.errors.push(`package.json syntax error: ${err.message}`);
    diagnostics.valid = false;
  }

  // 2. Validate .env
  try {
    const envRaw = fs.readFileSync('./.env');
    const parsedEnv = dotenv.parse(envRaw);
    if (!parsedEnv.DATABASE_URL) {
      diagnostics.errors.push(".env is missing critical DATABASE_URL variable.");
      diagnostics.valid = false;
    }
  } catch (err) {
    diagnostics.errors.push(`.env formatting error: ${err.message}`);
    diagnostics.valid = false;
  }

  return diagnostics;
}

Python 3 Implementation (PyYAML validation)

import yaml
import sys

def validate_docker_compose(filepath: str) -> bool:
    """
    Validates Docker Compose YAML structure and service schema.
    Returns True if valid, raises ValueError otherwise.
    """
    try:
        with open(filepath, 'r') as f:
            # Always use safe_load to prevent arbitrary code execution
            manifest = yaml.safe_load(f)
            
        if not isinstance(manifest, dict):
            raise ValueError("Root YAML structure must be a dictionary/mapping.")
            
        if "services" not in manifest:
            raise ValueError("Missing top-level 'services' declaration required for Compose.")
            
        return True
    except yaml.YAMLError as exc:
        print(f"YAML Syntax Error: {exc}", file=sys.stderr)
        return False
    except FileNotFoundError:
        print(f"File not found: {filepath}", file=sys.stderr)
        return False

# Example trigger
# validate_docker_compose("docker-compose.yml")

Common Pitfalls & Edge Cases

  • Unquoted Spaces in .env Files: If a variable value contains spaces (e.g., APP_NAME=My App), standard shell parsers and dotenv libraries will interpret the space as a command delimiter, reading the value only as My. Values with spaces must be strictly enclosed in quotes: APP_NAME="My App".
  • Trailing Commas in package.json: JavaScript object literals permit trailing commas, but strict JSON (RFC 8259) does not. A single trailing comma at the end of a dependencies list will cause npm install or yarn to throw an immediate fatal SyntaxError: Unexpected token and halt the deployment pipeline.
  • Tab Indentation in YAML: The YAML specification outright bans the use of literal Tab (\t) characters for structural indentation to prevent misinterpretation across different IDEs. A single tab mixed with spaces in docker-compose.yml will prevent the Docker daemon from starting.
  • Accidental Comments in .env Passwords: Hash symbols (#) indicate the start of a comment in Bash and dotenv. If your database password contains a hash (e.g., DB_PASS=admin#123), the parser will truncate the password to admin. Passwords containing hashes must be wrapped in single quotes ('admin#123').

Frequently Asked Questions

Are .env files a secure way to store credentials in production?

Yes and no. While .env files are the industry standard for injecting twelve-factor app configuration into local runtimes and Docker containers, they should never be committed to version control (Git). In cloud production environments, secrets should ideally be injected at runtime via managed secret vaults (like AWS Secrets Manager, HashiCorp Vault, or Kubernetes Secrets) rather than relying on flat files on the server disk.

Why does my YAML validator throw a "Mapping values are not allowed here" error?

This error typically occurs when there is a missing space after a colon (:). In YAML, a key-value pair must have a space separating them (e.g., image: ubuntu). If you write image:ubuntu, the parser treats the entire string as a scalar value and fails when it expects structural mapping further down the hierarchy.

Is it safe to paste API keys and passwords into this validator?

Yes. This tool is built on a strict zero-telemetry, 100% client-side execution model. The JavaScript logic runs entirely within your browser's local DOM. Nothing is transmitted to external servers, API endpoints, or analytics platforms, guaranteeing complete privacy for your sensitive infrastructure secrets.

Comments

Popular posts from this blog

Secure Password Generator

JSON Formatter and Validator

URL Encoder & Decoder