require "optparse" require "json" require "yaml" require "fileutils" require "securerandom" require_relative "2pass/version" module TwoPass VAULT_DIR = "#{Dir.home}/.2pass" def self.create_symlink(vault_name, target_path) FileUtils.mkdir_p(VAULT_DIR) symlink_path = "#{VAULT_DIR}/#{vault_name}.yml" if File.exist?(symlink_path) puts "Symlink already exists: #{symlink_path}" else File.symlink(target_path, symlink_path) puts "Created symlink: #{symlink_path} -> #{target_path}" end end def self.load_vault(vault_name) file_path = "#{VAULT_DIR}/#{vault_name}.yml" return [] unless File.exist?(file_path) YAML.load_file(file_path, symbolize_names: true) || [] rescue Psych::SyntaxError => e STDERR.puts "Error parsing YAML file: #{e.message}" [] end def self.save_vault(vault_name, data) FileUtils.mkdir_p(VAULT_DIR) file_path = "#{VAULT_DIR}/#{vault_name}.yml" File.write(file_path, YAML.dump(data)) end def self.list_content(vault_name) vault = load_vault(vault_name) JSON.pretty_generate(vault) end def self.add_secret(vault_name, id, value) new_secret = { id: id, value: value, uuid: SecureRandom.uuid } data = load_vault(vault_name) existing_entry_id = data.find_index { |hash| hash[:id] == new_secret[:id] } if existing_entry_id raise "The secret already exists" end data << new_secret save_vault(vault_name, data) end def self.get_secret(vault_name, id) vault = load_vault(vault_name) entry = vault.find { |hash| hash[:id] == id } if entry entry[:value] else raise "Entry not found" end end end