Loading...
Ababil Hossain
Ababil Hossain

Programmer | DevTools & Open Source

How I Designed the Architecture of EnvLink

How I Designed the Architecture of EnvLink

The decisions and tradeoffs behind building an end-to-end encrypted environment file sharing tool.

EnvLink is an end-to-end encrypted environment file sharing tool. This article explores how EnvLink implements its encryption architecture—not because it uses groundbreaking techniques, but because it demonstrates how standard cryptographic primitives can be properly combined to create a zero-trust security system.

Note: Throughout this post, “link” or “EnvLink” refers to the encrypted ID that EnvLink generates (likeel_71OgJX8hR9ysu4rc). It’s not a web URL—it’s a CLI command ID that teams share to securely install.envfiles. Think of it as an encrypted sharing ID rather than a traditional link.

TL;DR

The Problem: Developers share.envfiles with secrets over Slack/Discord - insecure and permanent.

The Solution: EnvLink is a CLI tool for sharing environment files with:

  • Zero-knowledge encryption - Server can’t read your files (even if compromised)
  • Two modes: Password-protected (secure) or optional-password (convenient)
  • Open source - Audit the crypto yourself

How It Works:

  1. Client encrypts files with AES-256-GCM before sending
  2. Server stores encrypted blobs (never sees plaintext or encryption keys)
  3. Authentication uses zero-knowledge proofs (password never transmitted)
  4. Recipients decrypt client-side with password or embedded key

Tech Stack: Node.js crypto module, AES-256-GCM, PBKDF2 (700K iterations)

Result: Even server operators can’t read your secrets. Try it →

Want to host EnvLink Server yourself? Or publish your own EnvLink CLI?
Take full control of your infrastructure and customize EnvLink for your organization.
See Self-host Guide


What You’ll Learn

In this post, I’ll walk you through the complete architecture of EnvLink’s security system. You’ll learn:

  • End-to-end encryption with AES-256-GCM and why authenticated encryption matters
  • Zero-knowledge authentication using cryptographic proofs instead of password transmission
  • Dual-mode design balancing security and convenience (password-protected vs optional-password)
  • Timing-safe comparison and other practical defenses against side-channel attacks
  • Real implementation details with actual code from production

Whether you’re building a similar tool or just curious about applied cryptography, you’ll see how standard primitives combine into a zero-trust system where even the server operator can’t access user data.

The Core Problem Being Solved

Developers frequently share.envfiles on Slack or Discord. Database URLs with passwords, API keys, AWS credentials—all sitting in chat history permanently.

EnvLink addresses this by providing:

Quick environment file sharing for teams
Server-side storage without access to plaintext secrets
Auto-expiring links to prevent credential persistence

The third requirement necessitates a server infrastructure. The second requirement mandates that the server cannot be trusted with plaintext data. This architectural constraint leads directly to client-side encryption.

Two Modes: Password vs No Password

EnvLink offers two operational modes, each optimized for different security and usability requirements:

Password-protected mode serves production database URLs, critical API keys, and sensitive team credentials. Recipients must possess the password to decrypt content.

Optional-password mode addresses quick configuration sharing scenarios—staging configs or onboarding workflows where password coordination adds friction. The decryption key embeds directly in the extended ID formatel_{baseId}{accessKey}.

The optional-password mode embeds the access key directly in the ID. Data remains encrypted in transit and at rest, and critically, the EnvLink server never receives the access key. This design trades some security for convenience in low-stakes scenarios.

Mode Comparison

Aspect Password-Protected Optional-Password
Use Case Production secrets, sensitive API keys Staging configs, quick onboarding
Security Key User-chosen password Auto-generated 16-char Base62 key
Server Knowledge Stores password hash only Never sees the access key
Sharing Method ID + password (2 pieces) Extended ID (1 piece)
Expiration Configurable See Details Fixed 1 hour
Updates Supported with password proof Not supported
Best For Team collaboration Individual use, temporary sharing

Here’s how the two modes differ architecturally:

graph TD
    subgraph pw["Password-Protected Mode"]
        A1[.env Files] --> B1[Password Input]
        B1 --> C1[Hash Password]
        C1 --> D1[Encrypt Files]
        D1 --> E1[Send Encrypted + Hash]
        E1 --> F1[Server Storage]
        F1 --> G1[Return Encrypted Data]
        G1 --> H1[Decrypt with Password]
        H1 --> I1[.env Files Out]
    end

    subgraph op["Optional-Password Mode"]
        A2[.env Files] --> B2[Generate Access Key]
        B2 --> C2[Encrypt Files]
        C2 --> D2[Send Encrypted Only]
        D2 --> E2[Server Storage]
        B2 --> F2[Embed in Extended ID]
        E2 --> G2[Return Encrypted Data]
        F2 --> H2[Extract Key from ID]
        G2 --> I2[Decrypt with Key]
        H2 --> I2
        I2 --> J2[.env Files Out]
    end

The Encryption Stack

Security Update (v4.0.0): EnvLink optimized crypto parameters following NIST and OWASP standards: reduced IV from 16 to 12 bytes (NIST-recommended for AES-GCM), and PBKDF2 iterations from 1M to 700K (still exceeds OWASP’s 600K minimum). These changes provide ~30% faster operations while maintaining strong security, plus increased payload limits to 2.5MB with no file count restrictions.

EnvLink uses AES-256-GCM for encryption because:

Performance is excellent
The algorithm is battle-tested
It provides authenticated encryption (via GCM mode)

The authenticated encryption property is critical. With GCM mode, any tampering with encrypted data causes decryption to fail. Bit-flipping attacks are immediately detected.

For password-based key derivation, EnvLink implements PBKDF2 with 700,000 iterations. While alternatives like Argon2 or scrypt exist, PBKDF2 ships natively in Node’s crypto module, and 700,000 iterations exceeds OWASP’s recommended minimum of 600,000 iterations for PBKDF2-SHA256, providing substantial computational cost to resist brute-force attacks.

First, here are the crypto constants:

JAVASCRIPT
const CRYPTO_CONFIG = {
  CIPHER_ALGORITHM: "aes-256-gcm",
  HASH_ALGORITHM: "sha256",
  KEY_LENGTH: 32,
  IV_LENGTH: 12,
  ITERATIONS: 700000,
};

View on GitHub

Why these values?

  • AES-256-GCM: Industry standard authenticated encryption (prevents tampering)
  • SHA-256: Widely supported, fast, cryptographically secure for hashing
  • 32-byte key: Required for AES-256 (256 bits = 32 bytes)
  • 12-byte IV: NIST-recommended standard for GCM mode, more efficient than 16 bytes
  • 700,000 iterations: Exceeds OWASP’s minimum of 600,000 for PBKDF2-SHA256. Each password attempt requires 700,000 cryptographic operations, forcing attackers to spend significant computational resources per guess while providing ~30% faster performance than 1M iterations

Here’s the key derivation function:

JAVASCRIPT
const deriveKey = async (password, salt) => {
  const pbkdf2 = util.promisify(crypto.pbkdf2);
  return pbkdf2(
    password,
    salt,
    CRYPTO_CONFIG.ITERATIONS,
    CRYPTO_CONFIG.KEY_LENGTH,
    CRYPTO_CONFIG.HASH_ALGORITHM,
  );
};

View on GitHub

This takes a password and salt, runs 700,000 iterations of PBKDF2 with SHA-256, and outputs a 32-byte (256-bit) key. That’s what we use for AES-256-GCM encryption.

The encryption function implementation:

JAVASCRIPT
export const encrypt = async (plaintext, password) => {
  const salt = crypto.randomBytes(CRYPTO_CONFIG.KEY_LENGTH);
  const key = await deriveKey(password, salt);
  const iv = crypto.randomBytes(CRYPTO_CONFIG.IV_LENGTH);

  const cipher = crypto.createCipheriv(CRYPTO_CONFIG.CIPHER_ALGORITHM, key, iv);

  const encrypted = Buffer.concat([
    cipher.update(plaintext, "utf8"),
    cipher.final(),
  ]);

  return {
    encryptedData: encrypted.toString("base64"),
    iv: iv.toString("base64"),
    salt: salt.toString("base64"),
    authTag: cipher.getAuthTag().toString("base64"),
  };
};

View in GitHub

The salt and IV are randomly generated for each encryption operation. This ensures that encrypting identical files with the same password produces completely different ciphertext. This randomization is essential—it prevents attackers from learning patterns by comparing encrypted files.

The GCM auth tag provides cryptographic proof that data hasn’t been modified.

The decryption function:

JAVASCRIPT
export const decrypt = async (input, password) => {
  const encryptedData = Buffer.from(input.encryptedData, "base64");
  const iv = Buffer.from(input.iv, "base64");
  const salt = Buffer.from(input.salt, "base64");
  const authTag = Buffer.from(input.authTag, "base64");

  try {
    const key = await deriveKey(password, salt);
    const decipher = crypto.createDecipheriv(
      CRYPTO_CONFIG.CIPHER_ALGORITHM,
      key,
      iv,
    );

    decipher.setAuthTag(authTag);

    const decrypted = Buffer.concat([
      decipher.update(encryptedData),
      decipher.final(),
    ]);

    return decrypted.toString("utf8");
  } catch {
    throw new Error("Invalid password or corrupted data");
  }
};

View in GitHub

Decryption uses the stored salt to derive the key, verifies the auth tag (failing if it doesn’t match), and returns the plaintext. Incorrect passwords or tampered data result in immediate failure.

Here’s the complete encryption flow:

sequenceDiagram
    participant User
    participant Client
    participant Crypto
    participant Server

    User->>Client: Provide password & files
    Client->>Crypto: Generate random salt (32 bytes)
    Client->>Crypto: Generate random IV (12 bytes)
    Crypto->>Crypto: PBKDF2(password, salt, 700K iterations)
    Note over Crypto: Derives 256-bit AES key
    Crypto->>Crypto: AES-256-GCM encrypt
    Crypto-->>Client: encrypted data + IV + salt + auth tag
    Client->>Client: Hash password with PBKDF2 (700K iterations)
    Client->>Server: Send encrypted payload + password hash
    Server->>Server: Store everything (no password!)
    Server-->>Client: Return EnvLink ID

Payload Limits and Multi-File Support

EnvLink v4.0.0 supports an encrypted payload of up to 2.5 MB for users. The server accepts up to 3 MB, leaving 500 KB of headroom for encryption overhead and request metadata.

There is no longer a file-count limit. You can include as many.envvariants as fit within the total encrypted payload limit; only the combined payload size matters. This makes sharing multi-environment configurations more flexible without changing the zero-knowledge architecture.

The password-protected creation flow in the CLI:

JAVASCRIPT
const encryptedData = JSON.stringify(
  await encrypt(JSON.stringify(files), password),
);

const passwordHash = await hashPasswordDeterministic(password);

const requestPayload = {
  encryptedData,
  passwordHash,
  expirationDuration: expiration,
};

if (reference && reference.trim() !== "") {
  requestPayload.reference = reference;
}

const response = await apiClient.post("/envlinks", requestPayload);

View on GitHub

The key architectural principle: the password itself NEVER transmits to the server. Only the hash is sent. Because encryption happens first with the actual password, the server cannot decrypt even with the hash.

The Zero-Knowledge Proof System

For password-protected links, the server must verify that a user possesses the correct password without receiving the password itself (which would enable server-side decryption).

EnvLink implements a challenge-response authentication system:

  1. During link creation, the password is hashed with PBKDF2 (700,000 iterations) and the hash is sent to the server
  2. During link access, the client generates a “proof” by combining that hash with a deterministic salt derived from the link ID
  3. The server independently generates the same proof using the stored hash and compares them

How It Works

First, the client hashes the password deterministically using PBKDF2 with a fixed salt:

JAVASCRIPT
export const hashPasswordDeterministic = async (password) => {
  const authSalt = crypto
    .createHash(CRYPTO_CONFIG.HASH_ALGORITHM)
    .digest("hex");
  const key = await deriveKey(password, authSalt);
  return key.toString("hex");
};

View On GitHub

Then generates a proof using both the password hash and the link ID:

JAVASCRIPT
export const generateZKProof = async (passwordHash, envlinkId) => {
  const serverSalt = crypto
    .createHash(CRYPTO_CONFIG.HASH_ALGORITHM)
    .update(`envlink:${envlinkId}`)
    .digest("hex");

  const input = passwordHash + serverSalt;

  const key = await deriveKey(input, serverSalt);

  return key.toString("base64");
};

View on GitHub - Client | View on GitHub - Server

The elegant part: This exact samegenerateZKProoffunction is used by both the CLI client and the server. The client generates a proof with the user’s password hash, and the server independently generates the expected proof with the stored password hash. Because the function is deterministic (same inputs always produce the same output), if the passwords match, the proofs match - without ever transmitting the password itself.

The critical insight: the proof is deterministic for a given password + link ID combination, but completely different across different links. This means:

  • The same password produces different proofs for different links
  • An intercepted proof is useless for accessing other links
  • The server never learns the actual password
  • Each link ID creates a unique salt, so compromising one proof doesn’t help attack other EnvLinks

Server-Side Verification

On the server, I use the exact samegenerateZKProoffunction with the stored password hash to independently compute what the proof should be, then compare it with what the client sent:

JAVASCRIPT
const storedProof = await auth.generateZKProof(
  envLink.passwordHash!,
  envlinkId,
);

let isProved = false;

try {
  const passwordProofBuffer = Buffer.from(passwordProof, "utf8");
  const storedPasswordProofBuffer = Buffer.from(storedProof, "utf8");

  if (passwordProofBuffer.length === storedPasswordProofBuffer.length) {
    isProved = timingSafeEqual(passwordProofBuffer, storedPasswordProofBuffer);
  }
} catch {
  isProved = false;
}

if (!isProved) throw new AppError(HTTP_CODE.UNAUTHORIZED, unAuthMsg);

View on GitHub - Server

Why this works: Both client and server run the identical function with their respective inputs (client uses the actual password hash, server uses the stored password hash). If the passwords match, the cryptographic proofs match. No password ever crosses the network.

ThetimingSafeEqualfunction is critical—it prevents timing attacks by maintaining constant execution time regardless of where differences occur. Regular comparison operators like===would leak information through execution time variations.

Security Benefits

This zero-knowledge proof approach provides several key protections:

Server never sees plaintext passwords - Only hashes are transmitted and stored
Encrypted data remains secure even if server is compromised - Without the password, the encrypted files are useless
Timing-safe comparison prevents side-channel attacks - Attackers can’t measure response times to brute-force proofs
EnvLink-specific salts prevent cross-resource attacks - A proof for one link can’t be reused on another

Here’s the complete zero-knowledge proof flow:

sequenceDiagram
    participant Client
    participant Server

    Note over Client,Server: Creation Phase
    Client->>Client: Hash password (PBKDF2, 700K iterations)
    Client->>Server: Send passwordHash + encrypted data
    Server->>Server: Store passwordHash (NOT the password!)

    Note over Client,Server: Access Phase
    Client->>Client: Hash password (PBKDF2, 700K iterations)
    Client->>Client: Generate salt from linkId
    Client->>Client: generateZKProof(passwordHash, linkId)
    Client->>Server: Send proof (not password!)

    Server->>Server: Get stored passwordHash
    Server->>Server: Generate same salt from linkId
    Server->>Server: generateZKProof(storedHash, linkId)
    Note over Server: Uses SAME function as client!
    Server->>Server: timingSafeEqual(client proof, server proof)

    alt Proofs match
        Server-->>Client: Return encrypted data
        Client->>Client: Decrypt with original password
    else Proofs don't match
        Server-->>Client: 401 Unauthorized
    end

Optional-Password Links: A Different Approach

For optional-password links, EnvLink employs a simpler architecture.

During creation, a random 16-character access key is generated using Base62 encoding (0-9, A-Z, a-z). This key encrypts the files but never transmits to the EnvLink server. Instead:

  • Server receives: base ID (19 chars includingel_prefix) + encrypted data
  • User receives: extended ID (35 chars total) that includes the access key

The Base62 encoding function:

JAVASCRIPT
const BASE62_CHARS =
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

const generateBase62String = (length) => {
  const randomBytes = crypto.randomBytes(length);
  let result = "";

  for (let i = 0; i < length; i++) {
    const byte = randomBytes[i];
    result += BASE62_CHARS[byte % BASE62_CHARS.length];
  }

  return result;
};

const generateAccessKey = () => generateBase62String(16);

View on GitHub

An example link:el_WqsazKUqo444UCJRrtvivnuRT3mKtxSR

  • First 19 characters (el_WqsazKUqo444UCJR) = base ID that goes to the server for lookup
  • Last 16 characters (rtvivnuRT3mKtxSR) = access key that stays client-side only for decryption
  • Total: 35 characters
JAVASCRIPT
const accessKey = generateAccessKey();

const encryptedData = JSON.stringify(
  await encrypt(JSON.stringify(files), accessKey),
);

const response = await apiClient.post("/envlinks", {
  encryptedData,
});

const extendedId = `${response.data.id}${accessKey}`;

View on GitHub

During installation:

JAVASCRIPT
const id = "el_WqsazKUqo444UCJRrtvivnuRT3mKtxSR"; // when user run "npx envlink install <extended id>"

const { baseId, accessKey } = parseExtendedId(id);

const response = await apiClient.post(`/envlinks/${baseId}`);

const { encryptedData } = response.data;

const decrypted = await decrypt(encryptedData, accessKey);

View on GitHub

The EnvLink server never receives the access key. It cannot decrypt files even if compromised.

Here’s how optional-password links work:

sequenceDiagram
    participant Client
    participant Server
    participant Recipient

    Note over Client: Creation
    Client->>Client: Generate random accessKey (16 chars)
    Client->>Client: Encrypt files with accessKey
    Client->>Server: POST encrypted data only
    Note over Server: Server generates baseId
(el_ + 16 random chars) Server-->>Client: Return baseId (19 chars) Client->>Client: Combine: baseId + accessKey Note over Client: Extended ID (35 chars total)
el_WqsazKUqo444UCJRrtvivnuRT3mKtxSR Note over Recipient: Installation Recipient->>Recipient: Parse extended ID (35 chars) Recipient->>Recipient: Extract baseId (first 19 chars) Recipient->>Recipient: Extract accessKey (last 16 chars) Recipient->>Server: POST /envlinks/{baseId} Note over Server: Server only knows baseId
Never saw the accessKey! Server-->>Recipient: Return encrypted data Recipient->>Recipient: Decrypt with accessKey Recipient->>Recipient: Write .env files

What Actually Gets Stored

EnvLink’s database storage is carefully designed to minimize exposure. Only encrypted data and necessary metadata persist.

JSON
{
  "id": "el_71OgJX8hR9ysu4rc",
  "encryptedData": "{\"encryptedData\":\"AKMyRweoUPy1MObsAth1KAlTyASlfQhUzsrFHxo4dtUHc5AKxe9XWlyWtJgB6tSjilm9n30sviaupHK+53PiyNfpARP270D3jeqER4jjo083AiFngbXJiZq8bfNyt6J/ltQ+Jd4JNhIF6nXdOg3tTtP...\",\"iv\":\"URHszVV7+sVISXMN4e8mHw==\",\"salt\":\"rEy7JdnEgbEkW6PPTLc7tjAoXTEMPZxK3AqcjY3+2ew=\",\"authTag\":\"s9WAZhS0F6Cw9SAorsJPGA==\"}",
  "passwordHash": "256abe4a7476c2baaa8907a038dc2b2c28fe3cd6178a43b1911f8fb95343390f",
  "expiresAt": "2026-10-09T04:00:04.227Z",
  "reference": "prod-api-keys",
  "installCount": 2
}

View on GitHub

JSON
{
  "id": "el_WqsazKUqo444UCJR",
  "encryptedData": "{\"encryptedData\":\"k7jH9mP2xQ8vN5tR3wL6zBpYcXvKnMqAsFdGhJkLmNoP...\",\"iv\":\"a8b3c9d2e1f4g5h6\",\"salt\":\"m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9\",\"authTag\":\"x9y8z7a6b5c4d3e2\"}",
  "expiresAt": "2026-10-08T11:30:00.000Z",
  "installCount": 0
}

View on GitHub

Critical security detail: The server only stores the base ID (el_WqsazKUqo444UCJR- 19 characters). The access key (16 additional characters) used for encryption is:

Generated client-side
Never transmitted to the server
Only exists in the extended ID the user receives (35 chars total:el_WqsazKUqo444UCJR+rtvivnuRT3mKtxSR)

The server literally cannot decrypt the files even if compromised—it doesn’t possess the key!

What’s NOT stored:

Plaintext passwords or access keys
Decrypted.envfile contents
Encryption keys or derivation materials (beyond salt/IV which are needed for decryption)

What IS stored:

Encrypted data blob (useless without the key)
Password hash for zero-knowledge proof verification (password-protected only)
Metadata: expiration, install count, optional reference
Salt and IV (required for PBKDF2 and AES decryption, safe to store)
Auth tag (GCM authentication, safe to store)

Why This Architecture

A simpler implementation could use server-side encryption with the server’s own keys—the approach most file-sharing services take. However, this creates fundamental security problems:

Traditional Server-Side Encryption Problems

Issue Impact
Key Management You’re responsible for protecting encryption keys - single point of failure
Breach Impact Server compromise exposes everything in plaintext
Legal Exposure Subpoenas or legal requests can force you to decrypt and hand over data
Trust Requirement Users must trust you, the operator, won’t misuse access
Insider Threat Employees or contractors with server access can read secrets

Zero-Knowledge Encryption Benefits

With EnvLink’s architecture:

Server operators cannot read files - Encryption happens client-side before transmission
Breaches expose nothing - Only encrypted blobs without keys
Legal requests are ineffective - Server cannot decrypt without keys
Users don’t need to trust the operator - Open source crypto can be verified
No insider threat - Even with full database access, data stays encrypted

The tradeoff? Increased complexity and more difficult debugging. For a tool protecting production secrets, this tradeoff is acceptable.

Conclusion

Building EnvLink demonstrates that effective security doesn’t require novel algorithms or exotic cryptographic primitives. Instead, it requires:

Clear threat modeling - Zero-trust architecture from inception
Proper use of proven primitives - AES-256-GCM, PBKDF2, SHA-256 over experimental alternatives
Security by default - CLI that works seamlessly, secure path is the easy path
Honest disclosure of tradeoffs - Optional-password mode trades security for convenience

Key Takeaways

For developers building similar systems, these principles matter most:

  1. Client-side encryption is non-negotiable for zero-trust architecture
  2. Authenticated encryption (GCM) prevents tampering - always use it
  3. Timing-safe comparisons aren’t optional - side-channel attacks are real
  4. Random salt and IV per encryption prevents pattern analysis
  5. Zero-knowledge proofs let servers verify without learning secrets

The entire implementation is open source for audit, forking, or reference.

Found this architecture insightful? Star the EnvLink repository!
Your support helps us continue building secure, open-source tools for developers.
Star on GitHub


External Resources

GitHub: https://github.com/AbabilCore/envlink
Documentation: https://envlink.ababilspark.com

Join the conversation

Share your thoughts

Loading comments...
Reading Progress 0%

Share this post