All files / core env-sync.ts

100% Statements 79/79
100% Branches 18/18
100% Functions 12/12
100% Lines 73/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130      1x 1x 1x 1x     1x     11x       11x       20x     1x 12x 12x 12x 12x   12x 12x 12x   12x               1x 8x 8x 8x 8x 8x 8x   8x 8x 4x     1x 4x 4x 4x     4x 4x           4x 4x     1x 3x 3x   3x 1x     2x 2x     1x 4x 4x   3x 5x 2x     1x 11x 11x 25x 25x 13x 13x 12x 12x   12x 2x   12x   11x     1x       6x 6x 6x 6x 6x   6x 8x 6x 4x 2x     6x    
// Copyright 2026 ForgeKit Contributors
// SPDX-License-Identifier: Apache-2.0
// https://github.com/SubhanshuMG/ForgeKit
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as crypto from 'crypto';
import { EncryptedPayload } from '../types';
 
const STORE_DIR = path.join(os.homedir(), '.forgekit', 'envs');
 
function getProjectHash(projectPath: string): string {
  return crypto.createHash('sha256').update(path.resolve(projectPath)).digest('hex').slice(0, 16);
}
 
function getProjectStoreDir(projectPath: string): string {
  return path.join(STORE_DIR, getProjectHash(projectPath));
}
 
function deriveKey(passphrase: string, salt: Buffer): Buffer {
  return crypto.scryptSync(passphrase, salt, 32);
}
 
export function encryptEnv(data: string, passphrase: string): EncryptedPayload {
  const salt = crypto.randomBytes(16);
  const key = deriveKey(passphrase, salt);
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
 
  let encrypted = cipher.update(data, 'utf-8', 'hex');
  encrypted += cipher.final('hex');
  const tag = cipher.getAuthTag();
 
  return {
    encrypted,
    salt: salt.toString('hex'),
    iv: iv.toString('hex'),
    tag: tag.toString('hex'),
  };
}
 
export function decryptEnv(payload: EncryptedPayload, passphrase: string): string {
  const salt = Buffer.from(payload.salt, 'hex');
  const key = deriveKey(passphrase, salt);
  const iv = Buffer.from(payload.iv, 'hex');
  const tag = Buffer.from(payload.tag, 'hex');
  const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
  decipher.setAuthTag(tag);
 
  let decrypted = decipher.update(payload.encrypted, 'hex', 'utf-8');
  decrypted += decipher.final('utf-8');
  return decrypted;
}
 
export function pushEnv(projectPath: string, environment: string, envContent: string, passphrase: string): void {
  const storeDir = getProjectStoreDir(projectPath);
  if (!fs.existsSync(storeDir)) {
    fs.mkdirSync(storeDir, { recursive: true, mode: 0o700 });
  }
 
  const payload = encryptEnv(envContent, passphrase);
  const metadata = {
    environment,
    updatedAt: new Date().toISOString(),
    payload,
  };
 
  const filePath = path.join(storeDir, `${environment}.enc.json`);
  fs.writeFileSync(filePath, JSON.stringify(metadata, null, 2), { mode: 0o600 });
}
 
export function pullEnv(projectPath: string, environment: string, passphrase: string): string {
  const storeDir = getProjectStoreDir(projectPath);
  const filePath = path.join(storeDir, `${environment}.enc.json`);
 
  if (!fs.existsSync(filePath)) {
    throw new Error(`No stored environment "${environment}" found for this project.`);
  }
 
  const metadata = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
  return decryptEnv(metadata.payload, passphrase);
}
 
export function listEnvs(projectPath: string): string[] {
  const storeDir = getProjectStoreDir(projectPath);
  if (!fs.existsSync(storeDir)) return [];
 
  return fs.readdirSync(storeDir)
    .filter(f => f.endsWith('.enc.json'))
    .map(f => f.replace('.enc.json', ''));
}
 
export function parseEnvFile(content: string): Record<string, string> {
  const vars: Record<string, string> = {};
  for (const line of content.split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eqIndex = trimmed.indexOf('=');
    if (eqIndex === -1) continue;
    const key = trimmed.slice(0, eqIndex).trim();
    let value = trimmed.slice(eqIndex + 1).trim();
    // Remove surrounding quotes
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
      value = value.slice(1, -1);
    }
    vars[key] = value;
  }
  return vars;
}
 
export function diffEnvs(
  env1: Record<string, string>,
  env2: Record<string, string>
): { added: string[]; removed: string[]; changed: string[]; unchanged: string[] } {
  const allKeys = new Set([...Object.keys(env1), ...Object.keys(env2)]);
  const added: string[] = [];
  const removed: string[] = [];
  const changed: string[] = [];
  const unchanged: string[] = [];
 
  for (const key of allKeys) {
    if (!(key in env1)) added.push(key);
    else if (!(key in env2)) removed.push(key);
    else if (env1[key] !== env2[key]) changed.push(key);
    else unchanged.push(key);
  }
 
  return { added, removed, changed, unchanged };
}