zorath-env Documentation
Package: zorath-env | Binary: zenv
Everything you need to get started with zorath-env.
Table of Contents
1. Installation
Use latest stable Rust 1.99.0 (rustup update stable); the supported minimum is Rust 1.85 with locked dependencies. Install zorath-env using Cargo (Rust package manager). The package installs as the zenv binary:
From crates.io
cargo +stable install zorath-env --lockedFrom source
git clone https://github.com/zorl-engine/zorath-env.git
cd zorath-env
cargo +stable install --path . --lockedAfter installation, verify it works by running:
zenv version2. Quick Start
Option A: Start from scratch
Create an env.schema.json file in your project root:
{
"DATABASE_URL": {
"type": "url",
"required": true,
"description": "Database connection string"
},
"PORT": {
"type": "int",
"required": false,
"default": 3000,
"description": "Server port number"
}
}Create a matching .env file
DATABASE_URL=postgres://localhost:5432/example
PORT=3000Use local values for your application and keep real env files out of Git. Defaults do not populate your application process.
Option B: Generate from existing .env.example
If you already have a .env.example file, generate a schema from it:
zenv initThis creates an env.schema.json with intelligent type inference (detects bool, int, float, url). Edit the file to add descriptions and refine types.
Validate your .env
Once you have both .env and env.schema.json, run:
$ zenv check
zenv: OK3. Schema Reference
Schema Structure
The schema file is a JSON object where each key is a variable name:
{
"VARIABLE_NAME": {
"type": "string",
"required": true,
"default": "value",
"description": "What this variable does",
"validate": { "min_length": 1 }
}
}Variable Properties
| Property | Type | Required | Description |
|---|---|---|---|
type | string | No | The data type (defaults to string) |
required | boolean | No | Whether the variable must be present (default: false) |
default | string, number, boolean | No | Validated fallback metadata; permits absence during check, but is not injected into the application |
description | string | No | Human-readable description |
values | string[] | For enum | List of allowed values (required for enum type) |
validate | object | No | Type-specific rules: int min/max, float min_value/max_value, string min_length/max_length/pattern |
Set secret: true for declared sensitive values and pass the schema to diff. Masking is heuristic; exports contain real values and schema defaults can appear in docs/examples. Severity accepts error or warning. Unknown variable fields, invalid defaults, and incompatible rules are rejected.
Supported Types
stringAny string value. This is the default type.
"API_KEY": { "type": "string", "required": true }intInteger numbers only. Validates that the value can be parsed as an integer.
"PORT": { "type": "int", "default": "3000" }floatFloating-point numbers. Validates that the value can be parsed as a float.
"RATE_LIMIT": { "type": "float", "default": "1.5" }boolBoolean values. Accepts true, false, 1, 0, yes, no (case-insensitive).
"DEBUG": { "type": "bool", "default": false }urlValid URL format. Validates URL structure.
"DATABASE_URL": { "type": "url", "required": true }enumOne of the specified values. Requires the values property.
"LOG_LEVEL": { "type": "enum", "values": ["debug", "info", "warn", "error"] }uuidUUID version 4 format (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx).
"SESSION_ID": { "type": "uuid", "required": true }emailValid email address format with basic RFC 5322 validation.
"ADMIN_EMAIL": { "type": "email", "required": true }ipv4Valid IPv4 address in dotted decimal notation (0.0.0.0 to 255.255.255.255).
"SERVER_IP": { "type": "ipv4", "default": "127.0.0.1" }ipv6Valid IPv6 address in standard notation.
"IPV6_ADDR": { "type": "ipv6", "required": false }semverSemantic version format (MAJOR.MINOR.PATCH with optional prerelease/build metadata).
"APP_VERSION": { "type": "semver", "default": "1.0.0" }portValid network port number between 1 and 65535.
"HTTP_PORT": { "type": "port", "default": "8080" }dateISO 8601 date format (YYYY-MM-DD).
"RELEASE_DATE": { "type": "date", "required": false }hostnameValid hostname or domain name per RFC 1123.
"API_HOST": { "type": "hostname", "default": "localhost" }4. Global Flags
These flags work with any command.
| Flag | Description |
|---|---|
--config <path> | Path to custom .zenvrc config file (default: auto-discover in current/parent directories) |
--verbose | Show verbose diagnostic output (conflicts with --quiet) |
--quiet | Suppress all diagnostic output (conflicts with --verbose) |
--no-color | Disable colored output (also respects NO_COLOR env var and .zenvrc no_color setting) |
5. CLI Commands
zenv check
Validates your .env file against the schema. Optionally scan for leaked secrets. Returns exit code 0 on success, 1 on failure.
Options:
--env <path>- Path to .env file (default: .env)--schema <path>- Path to schema file (default: env.schema.json)--allow-missing-env- Allow missing .env if schema validates (default: false)--detect-secrets- Scan for potential secrets (AWS keys, tokens, passwords)--watch- Watch mode for continuous validation with delta detection--format <format>- Output format: text or json (default: text)--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv check
zenv: OK
$ zenv check --format json
{"valid":true,"errors":[],"warnings":[]}
$ zenv check --watch
[14:32:15] Watching .env and env.schema.json...
[14:32:20] Change detected in .env
zenv: OKzenv diff
Compare two .env files and show differences. Find variables only in one file, or with different values.
Options:
<file_a>- First .env file<file_b>- Second .env file--schema <path>- Also check schema compliance for both files--format <format>- Output format: text or json (default: text)--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv diff .env.development .env.production
Only in .env.development:
- DEBUG_MODE
Different values:
- NODE_ENV: "development" vs "production"
$ zenv diff .env.dev .env.prod --format jsonzenv init
Generates a schema file from an existing .env.example file with intelligent type inference and smart description generation based on key names.
Options:
--example <path>- Path to .env.example (default: .env.example)--schema <path>- Output path (default: env.schema.json)--preset <name>- Use a framework preset (nextjs, rails, django, fastapi, express, laravel)--list-presets- List available framework presets
Example:
$ zenv init
Created env.schema.json from .env.example
$ zenv init --preset nextjs
Created env.schema.json from nextjs preset
$ zenv init --list-presets
Available presets: nextjs, rails, django, fastapi, express, laravelzenv docs
Generates documentation from your schema. Outputs to stdout.
Options:
--schema <path>- Path to schema file (default: env.schema.json)--format <format>- Output format: markdown or json (default: markdown)--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv docs
# prints markdown to stdout
$ zenv docs --format json > schema.jsonzenv example
Generate .env.example from schema (reverse of init).
Options:
--schema <path>- Path to schema (default: env.schema.json)--output <path>- Output file (default: stdout)--include-defaults- Include default values in output--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv example
# outputs to stdout
$ zenv example --include-defaults --output .env.examplezenv version
Displays the current version of zenv with optional update check and changelog links.
Options:
--check-update- Check crates.io for newer version
Example:
$ zenv version
zenv v0.3.13
$ zenv version --check-update
# Checks crates.io for the latest releasezenv completions
Generate shell completions for bash, zsh, fish, or PowerShell.
Options:
<SHELL>- Shell type: bash, zsh, fish, powershell
Example:
$ zenv completions bash > ~/.bash_completion.d/zenv
$ zenv completions zsh > ~/.zfunc/_zenv
$ eval "$(zenv completions bash)"zenv export
Export .env files to various deployment formats. Supports 7 output formats for different platforms.
Options:
--env <path>- Path to .env file to export (default: .env or configured env path)--format <format>- Output format: shell, docker, k8s, json, systemd, dotenv, github-secrets--schema <path>- Filter to only schema-defined variables--output <path>- Write to file instead of stdout--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv export --env .env --format shell
export DATABASE_URL="postgres://..."
$ zenv export --env .env --format docker
ENV DATABASE_URL=postgres://...
$ zenv export --env .env --format k8s
apiVersion: v1
kind: ConfigMap
data:
DATABASE_URL: postgres://...zenv doctor
Run comprehensive health diagnostics. Checks schema validity, .env parsing, config file, remote cache, and validation.
Options:
--env <path>- Path to .env file (default: .env)--schema <path>- Path to schema file (default: env.schema.json)--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv doctor
zenv Doctor
===========
[OK] Schema: env.schema.json (12 variables)
[OK] Env file: .env (parsed successfully)
[OK] Config: .zenvrc (valid)
[OK] Validation: all checks passed
[WARN] Cache: 2 expired entrieszenv fix
Automatically fix common .env issues. Creates a backup before making changes. Adds missing required variables with schema defaults.
Options:
--env <path>- Path to .env file (default: .env)--schema <path>- Path to schema file (default: env.schema.json)--remove-unknown- Remove variables not in schema--dry-run- Show changes without applying (masks secrets)--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv fix --dry-run
# Preview missing required variables and manual repairs
$ zenv fix --remove-unknown --dry-run
# Also preview removal of keys absent from the schema
$ zenv fix
# Apply supported fixes and create a backupzenv scan
Scan source code for environment variable usage. Finds unused schema variables and undeclared env references.
Options:
--path <dir>- Directory to scan (default: .)--schema <path>- Path to schema file (default: env.schema.json)--format <format>- Output format: text or json (default: text)--show-unused- Show variables in schema but not in code--show-paths- Show file:line for all found variables--no-cache- Bypass schema cache for remote URLs--verify-hash <hash>- Verify remote schema SHA-256 hash--ca-cert <path>- Custom CA certificate (PEM format)
Example:
$ zenv scan --show-unused
Scanning 142 files...
Unused (in schema but not in code):
- OLD_API_KEY
- LEGACY_MODE
Used variables: 23
Files scanned: 142
Languages: JavaScript, TypeScript, Pythonzenv cache
Manage the remote schema cache. View cache location, list entries, clear cached schemas, or view statistics.
Options:
path- Show cache directory pathlist- List all cached schemas with URLs and agesclear [url]- Clear all cache or specific URLstats- Show cache health statistics and size
Example:
$ zenv cache path
~/.cache/zorath-env
$ zenv cache list
Cached schemas:
1. https://example.com/schema.json (2h ago)
2. https://team.dev/env.schema.json (15m ago)
$ zenv cache stats
Cache Statistics:
Total entries: 2
Total size: 4.2 KB
Oldest: 2h ago
$ zenv cache clear
Cleared 2 cached schemaszenv template
Generate CI/CD configuration templates for environment validation. Supports GitHub Actions, GitLab CI, and CircleCI.
Options:
<template>- Template name: github (gh), gitlab (gl), circleci (circle)--output <path>- Write to file instead of stdout--list- List available templates--use-binary- Use pre-built binary download instead of cargo install
Example:
$ zenv template --list
Available templates:
github - GitHub Actions workflow
gitlab - GitLab CI pipeline
circleci - CircleCI config
$ zenv template github
# Outputs GitHub Actions YAML to stdout
$ zenv template github --output .github/workflows/env-validation.yml
Created .github/workflows/env-validation.ymlzenv mcp
Run the local JSON-RPC server over stdin/stdout for an MCP client. Exposes check, scan, diff, doctor, and docs tools plus schema, masked env, and docs resources. Four tools return JSON serialized in text content; doctor returns plain text. Review masked output and schema defaults before sharing with an AI provider.
Example:
$ zenv mcp
# Configure your MCP client with command: zenv, args: ["mcp"]
# Select project settings with: zenv --config /path/to/.zenvrc mcpzenv --help
Shows help information and available commands.
Example:
$ zenv --help6. Examples
Web Application
{
"NODE_ENV": {
"type": "enum",
"values": ["development", "production", "test"],
"required": true,
"description": "Application environment"
},
"PORT": {
"type": "int",
"required": false,
"default": 3000,
"description": "HTTP server port",
"validate": { "min": 1024, "max": 65535 }
},
"DATABASE_URL": {
"type": "url",
"required": true,
"description": "PostgreSQL connection string"
},
"JWT_SECRET": {
"type": "string",
"required": true,
"description": "Secret key for JWT signing",
"validate": { "min_length": 32, "max_length": 128 }
},
"DEBUG": {
"type": "bool",
"required": false,
"default": false,
"description": "Enable debug logging"
}
}API Service
{
"API_HOST": {
"type": "string",
"required": false,
"default": "0.0.0.0",
"description": "Host to bind the API server"
},
"API_PORT": {
"type": "int",
"required": false,
"default": 8080,
"description": "Port for the API server",
"validate": { "min": 1, "max": 65535 }
},
"LOG_LEVEL": {
"type": "enum",
"values": ["debug", "info", "warn", "error"],
"required": false,
"default": "info",
"description": "Logging verbosity level"
},
"RATE_LIMIT": {
"type": "float",
"required": false,
"default": 100.0,
"description": "Requests per second limit",
"validate": { "min_value": 0.0, "max_value": 10000.0 }
},
"CORS_ORIGIN": {
"type": "url",
"required": false,
"description": "Allowed CORS origin"
}
}7. .env File Features
zenv supports advanced .env file features beyond simple key=value pairs.
Variable Interpolation
Reference other variables using ${VAR} or $VAR syntax:
BASE_URL=https://api.example.com
API_ENDPOINT=${BASE_URL}/v2
PORT=3000
SERVER_URL=http://localhost:${PORT}Circular references are detected and will cause a validation error.
Multiline Values
Double-quoted strings can span multiple lines:
SSH_KEY="-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA...
-----END RSA PRIVATE KEY-----"Escape Sequences
Double-quoted strings support escape sequences:
| Sequence | Result |
|---|---|
\n | Newline |
\t | Tab |
\r | Carriage return |
\\ | Backslash |
\" | Double quote |
Comments and Export Syntax
Full-line comments, inline comments, shell export syntax, and blank lines are supported:
# This is a full-line comment
DATABASE_URL=postgres://localhost/db # inline comment
# Shell export syntax works too
export NODE_ENV=production
export DEBUG=false.env Fallback Chain
If .env is not found, zenv automatically checks these fallbacks in order:
.env.local.env.development.env.development.local
8. Schema Inheritance
Extend base schemas for environment-specific configurations using the extends field. Children replace whole variable definitions. Local parents must stay within the child schema directory. Pinned roots require a separate extends_hash for each parent.
Base Schema (base.schema.json)
{
"DATABASE_URL": {
"type": "url",
"required": true,
"description": "Database connection string"
},
"LOG_LEVEL": {
"type": "enum",
"values": ["debug", "info", "warn", "error"],
"default": "info"
}
}Production Schema (prod.schema.json)
{
"extends": "base.schema.json",
"SENTRY_DSN": {
"type": "url",
"required": true,
"description": "Sentry error tracking DSN"
},
"LOG_LEVEL": {
"type": "enum",
"values": ["info", "warn", "error"],
"default": "warn"
}
}The production schema inherits all variables from base.schema.json, adds SENTRY_DSN, and overrides LOG_LEVEL to exclude debug level.
Inheritance supports up to 10 levels of depth. Circular references are detected and will cause an error.
9. Configuration File (.zenvrc)
Create a .zenvrc file in your project root to set default options. CLI arguments override .zenvrc settings. Discovery stops at the project boundary; configured relative paths resolve from the config directory. Invalid configuration fails visibly.
{
"schema": "config/env.schema.json",
"env": ".env.local",
"detect_secrets": true,
"format": "json",
"no_color": false
}| Key | Type | Description |
|---|---|---|
schema | string | Path to schema file (default: env.schema.json) |
env | string | Path to .env file (default: .env) |
allow_missing_env | boolean | Allow validation when .env file is missing |
detect_secrets | boolean | Enable secret detection during validation |
no_cache | boolean | Skip cache when fetching remote schemas |
no_color | boolean | Disable colored terminal output |
format | string | Default output format (text, json, markdown -- CLI --format overrides) |
verify_hash | string | SHA-256 hash to verify remote schema integrity |
ca_cert | string | Path to custom CA certificate (PEM format) |
rate_limit_seconds | number | Seconds between remote schema fetches (default: 60) |
Unknown keys in .zenvrc will trigger a warning but will not cause failures.
10. CI/CD Integration
zenv is designed for CI/CD pipelines with clear exit codes and easy integration.
Exit Codes
| Code | Meaning |
|---|---|
0 | No blocking errors; warnings (including secret findings) may remain |
1 | Validation failed |
2 | Usage, input, or configuration error |
3 | Schema error (invalid or missing schema) |
Pre-commit Hook
Add to .git/hooks/pre-commit or use with pre-commit framework:
#!/usr/bin/env bash
set -euo pipefail
command -v zenv >/dev/null 2>&1 || { echo "Install zenv before committing." >&2; exit 1; }
zenv check --env .env.example --schema env.schema.json --detect-secretsGitHub Actions
- name: Validate environment
uses: zorl-engine/zorath-env/.github/actions/[email protected]
with:
version: '0.3.13'
schema: env.schema.json
env-file: .env.exampleValidation Failure Output
When validation fails, zenv provides clear error messages:
$ zenv check
zenv check failed:
- DATABASE_URL: expected url, got 'not-a-url'
- NODE_ENV: expected one of ["development", "staging", "production"], got 'dev'
- API_KEY: missing (required)
- UNKNOWN_VAR: not in schema (unknown key)11. Secret Detection
Scan .env values with 22 built-in regex patterns, URL/webhook checks, and an entropy heuristic. Findings are warnings and do not by themselves fail validation.
Usage
zenv check --detect-secretsDetected Patterns
zenv scans for the following secret patterns:
| Type | Pattern | Description |
|---|---|---|
| AWS Access Keys | AKIA... | AWS access key IDs starting with AKIA |
| AWS Secret Keys | 40-char strings | AWS secret access keys |
| Stripe Keys | sk_live_, sk_test_, pk_live_, pk_test_ | Stripe API keys |
| GitHub Tokens | ghp_, gho_, ghs_, ghr_ | GitHub personal access tokens |
| GitLab Tokens | glpat- | GitLab personal access tokens |
| Slack Tokens | xoxb-, xoxp-, xoxa- | Slack bot and user tokens |
| Google API Keys | AIza... | Google Cloud API keys |
| Heroku API Keys | UUID format | Heroku platform API keys |
| SendGrid API Keys | SG.... | SendGrid email API keys |
| Twilio Credentials | AC..., SK... | Twilio account and API keys |
| Mailchimp API Keys | ...-us## | Mailchimp marketing API keys |
| npm Tokens | npm_... | npm registry access tokens |
| Private Keys | -----BEGIN RSA PRIVATE KEY----- | RSA, SSH, PGP private keys |
| JWT Tokens | eyJ... | JSON Web Tokens |
| URL Passwords | ://user:pass@host | URLs with embedded credentials |
| High-Entropy Strings | 32+ chars, high entropy | Possible API keys or secrets |
| OpenAI API Keys | sk-, sk-proj- | OpenAI API key formats |
| Anthropic API Keys | sk-ant-api..., sk-ant-admin... | Anthropic API and admin keys |
| Discord Bot Tokens | Three-part token | Discord bot token format |
| Discord Webhooks | discord.com/api/webhooks/... | Discord webhook credentials |
| Slack Webhooks | hooks.slack.com/services/... | Slack webhook credentials |
| HuggingFace Tokens | hf_... | HuggingFace access tokens |
| Datadog API Keys | 32 hex characters | Datadog keys under matching variable names |
| Common API Key Prefixes | api_key..., apikey... | Generic API key prefix patterns |
Example Output
$ zenv check --detect-secrets
Warning: Potential secrets detected:
- AWS_SECRET_KEY (line 12): AWS Secret Access Key
- DATABASE_URL (line 15): URL contains embedded password
- API_TOKEN (line 22): High-entropy string (possible secret)
These values may be real secrets. Consider using placeholders in committed files.Need Help?
Found a bug, have a feature request, or just want to discuss zorath-env?