index.js 2.72 KB
// Generated by CoffeeScript 1.12.7
(function() {
  var PASSWORD, encrypted_file, fs, main, plaintext_file, yael;

  fs = require('fs');

  yael = require('yael');

  PASSWORD = null;

  plaintext_file = null;

  encrypted_file = null;

  main = function(options) {
    var cache, orig_plaintext, plaintext;
    cache = options.cache != null ? options.cache : options.cache = true;
    if (cache) {
      if (PASSWORD == null) {
        PASSWORD = options.password;
      }
      if (plaintext_file == null) {
        plaintext_file = options.plaintext_file;
      }
      if (encrypted_file == null) {
        encrypted_file = options.encrypted_file || options.plaintext_file + '.yael';
      }
    } else {
      PASSWORD = options.password;
      plaintext_file = options.plaintext_file;
      encrypted_file = options.encrypted_file || options.plaintext_file + '.yael';
    }
    if (!fs.existsSync(plaintext_file)) {
      console.log("Reading secrets from " + encrypted_file + ".");
      plaintext = main.readEncrypted();
      return plaintext;
    }
    console.log("Reading secrets from " + plaintext_file + ".");
    orig_plaintext = fs.readFileSync(plaintext_file).toString();
    if (PASSWORD != null) {
      if (!fs.existsSync(encrypted_file)) {
        console.log("Saving " + encrypted_file + " because it doesn't exist.");
        main.saveEncrypted();
      } else {
        plaintext = main.readEncrypted();
        if (plaintext !== orig_plaintext) {
          console.log("Updating " + encrypted_file + " because it has changed.");
          main.saveEncrypted();
        } else {
          console.log("Not updating " + encrypted_file + " because nothing has changed.");
        }
      }
    }
    return orig_plaintext;
  };

  main.readEncrypted = function() {
    var cipherObject, cipherbuffer, plaintext;
    if (!fs.existsSync(encrypted_file)) {
      throw Error("Cannot find " + plaintext_file + " or " + encrypted_file);
    }
    if (PASSWORD == null) {
      throw Error("No encryption password was set.");
    }
    cipherbuffer = fs.readFileSync(encrypted_file);
    cipherObject = new yael.CipherObject(cipherbuffer);
    plaintext = yael.decryptSync(PASSWORD, cipherObject);
    return plaintext.toString();
  };

  main.saveEncrypted = function() {
    var cipherObject, cipherbuffer, plaintext;
    if (!fs.existsSync(plaintext_file)) {
      throw Error("Cannot find " + plaintext_file);
    }
    if (PASSWORD == null) {
      throw Error("No encryption password was set.");
    }
    plaintext = fs.readFileSync(plaintext_file);
    cipherObject = yael.encryptSync(PASSWORD, plaintext);
    cipherbuffer = cipherObject.toBuffer();
    return fs.writeFileSync(encrypted_file, cipherbuffer);
  };

  module.exports = main;

}).call(this);