Class: LocalVault::CLI
- Inherits:
-
Thor
- Object
- Thor
- LocalVault::CLI
- Includes:
- TeamHelpers
- Defined in:
- lib/localvault/cli.rb,
lib/localvault/cli/keys.rb,
lib/localvault/cli/sync.rb,
lib/localvault/cli/team.rb,
lib/localvault/cli/team_helpers.rb,
lib/localvault/cli/error_presenter.rb
Defined Under Namespace
Modules: TeamHelpers Classes: CommandStatus, ErrorPresenter, GroupSaveError, GroupSelectionError, Keys, SetValueSourceError, Sync, Team
Constant Summary collapse
- USAGE_EXIT_STATUS =
1- GROUP_ALL_SENTINEL =
"\0localvault-all-groups"- GROUP_OFF_SENTINEL =
"\0localvault-groups-off"
Class Method Summary collapse
- .exit_on_failure? ⇒ Boolean
- .help(shell, subcommand = false) ⇒ Object
- .normalize_legacy_group_option(arguments) ⇒ Object
- .start(given_args = ARGV, config = {}) ⇒ Object
Instance Method Summary collapse
-
#add(handle) ⇒ Object
Grant a user access to a synced vault by creating a key slot.
- #copy(key) ⇒ Object
- #dashboard ⇒ Object
- #delete(key) ⇒ Object
- #demo ⇒ Object
- #doctor ⇒ Object
- #env ⇒ Object
- #exec(*cmd) ⇒ Object
- #get(key) ⇒ Object
- #groups(query = nil) ⇒ Object
- #import(file) ⇒ Object
- #init(name = nil) ⇒ Object
- #install_mcp(client = "claude-code") ⇒ Object
- #keygen ⇒ Object
- #list ⇒ Object
- #lock(name = nil) ⇒ Object
- #login(token = nil) ⇒ Object
- #logout ⇒ Object
- #mcp ⇒ Object
- #receive ⇒ Object
- #rekey(name = nil) ⇒ Object
-
#remove(handle) ⇒ Object
Remove a user's access to a vault.
- #rename(old_key, new_key) ⇒ Object
- #reset(name = nil) ⇒ Object
- #revoke(share_id) ⇒ Object
- #set(key, value = nil) ⇒ Object
- #share(vault_name = nil) ⇒ Object
- #show ⇒ Object
- #switch(vault_name = nil) ⇒ Object
- #unlock(vault_name = nil) ⇒ Object
- #vaults ⇒ Object
-
#verify(handle) ⇒ Object
Verify a user's handle and public key status before adding them.
- #version ⇒ Object
Class Method Details
.exit_on_failure? ⇒ Boolean
1535 1536 1537 |
# File 'lib/localvault/cli.rb', line 1535 def self.exit_on_failure? false end |
.help(shell, subcommand = false) ⇒ Object
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
# File 'lib/localvault/cli.rb', line 110 def self.help(shell, subcommand = false) shell.say "" shell.say "LocalVault — encrypted local secrets vault with MCP support for AI agents" shell.say " https://inventlist.com/tools/localvault" shell.say "" shell.say "GETTING STARTED" shell.say " localvault login [TOKEN] Log in to InventList (enables sync + team features)" shell.say " localvault init [NAME] Create a new encrypted vault" shell.say " localvault demo Create a demo vault to explore commands" shell.say "" shell.say "SECRETS" shell.say " printf '%s' \"$SECRET\" | localvault set KEY --stdin" shell.say " Store a secret without argv/history exposure" shell.say " localvault set KEY VALUE Store a secret (compatibility path)" shell.say " localvault set --group G K V Store a secret inside group G" shell.say " localvault get KEY Retrieve a secret" shell.say " localvault show Display all secrets (masked by default)" shell.say " localvault groups [QUERY] List or search stored groups (names only)" shell.say " localvault list List secret key names" shell.say " localvault delete KEY Remove a secret" shell.say " localvault import FILE Bulk-import from .env / .json / .yml" shell.say " localvault env Export as shell variable assignments" shell.say " localvault exec -- CMD Run a command with secrets injected as env vars" shell.say "" shell.say " Use with any CLI: localvault exec -- inventlist ships list" shell.say " localvault exec -- curl -H \"Authorization: Bearer $API_KEY\" ..." shell.say "" shell.say "VAULT MANAGEMENT" shell.say " localvault vaults List all vaults" shell.say " localvault switch [VAULT] Switch default vault" shell.say " localvault rekey [NAME] Change vault passphrase" shell.say " localvault unlock Cache passphrase for session" shell.say " localvault lock [NAME] Clear cached passphrase" shell.say " localvault reset [NAME] Destroy and reinitialize a vault" shell.say " localvault rename OLD NEW Rename a secret key" shell.say " localvault copy KEY --to V Copy a secret to another vault" shell.say "" shell.say "SYNC (requires localvault login)" shell.say " localvault sync Sync all vaults bidirectionally (smart push/pull with conflict detection)" shell.say " localvault sync --dry-run Show what would happen without making changes" shell.say " localvault sync push [NAME] Push one vault to cloud" shell.say " localvault sync pull [NAME] Pull one vault from cloud" shell.say " localvault sync status Show sync status for all vaults" shell.say "" shell.say "TEAM SHARING (requires localvault login)" shell.say " localvault dashboard Aggregate view: owned vaults, vaults shared with you, legacy shares" shell.say " localvault verify @HANDLE Check if a person has a published public key" shell.say " localvault add @HANDLE Add teammate (use --scope KEY... for partial access)" shell.say " localvault remove @HANDLE Remove teammate (--scope KEY to strip one key, --rotate to re-key)" shell.say " localvault team init [VAULT] Convert vault to team vault (required before add)" shell.say " localvault team list [VAULT] List vault members and their access" shell.say " localvault team rotate [VAULT] Re-key vault, keep all members" shell.say " localvault team SUBCOMMAND See `localvault help team` for the full team namespace" shell.say " (also accepts `team add/remove/verify` aliases for the top-level commands)" shell.say "" shell.say "KEYS (X25519 identity for vault sharing)" shell.say " localvault keys generate Generate X25519 identity keypair" shell.say " localvault keys publish Publish public key so others can share vaults with you" shell.say " localvault keys show Display your current public key" shell.say " localvault keys SUBCOMMAND See `localvault help keys` for the full keys namespace" shell.say "" shell.say "AI / MCP" shell.say " localvault install-mcp Configure MCP server in your AI tool" shell.say " localvault mcp Start MCP server (stdio)" shell.say " localvault mcp --check Check setup and active-vault readiness" shell.say " Agents: list names, then use localvault_build_exec for safe injection" shell.say "" shell.say "LEGACY SHARING (pre-v1.2 direct share, still works as fallback)" shell.say " localvault keygen Generate X25519 keypair (same as `keys generate`)" shell.say " localvault share [VAULT] Share a vault with a user, team, or crew (one-shot copy)" shell.say " localvault receive Fetch and import vaults shared with you" shell.say " localvault revoke SHARE_ID Revoke a direct vault share" shell.say "" shell.say "OTHER" shell.say " localvault login --status Show current login status" shell.say " localvault logout Log out" shell.say " localvault version Print version" shell.say " localvault doctor Check install and PATH readiness" shell.say " localvault help [COMMAND] Full help for any command" shell.say "" end |
.normalize_legacy_group_option(arguments) ⇒ Object
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 |
# File 'lib/localvault/cli.rb', line 78 def self.normalize_legacy_group_option(arguments) command = arguments.first matches = all_commands.keys.select { |name| name.start_with?(command.to_s) } return arguments unless command == "show" || matches == ["show"] normalized = [] index = 0 while index < arguments.length argument = arguments[index] if argument == "--" normalized.concat(arguments[index..]) break end if argument == "--group" && arguments[index + 1]&.match?(/\A(?:true|false|t|f)\z/i) enabled = arguments[index + 1].match?(/\A(?:true|t)\z/i) normalized << "--group=#{enabled ? GROUP_ALL_SENTINEL : GROUP_OFF_SENTINEL}" index += 2 next end case argument when /\A--group=(?:true|t)\z/i then normalized << "--group=#{GROUP_ALL_SENTINEL}" when /\A--group=(?:false|f)\z/i, "--no-group", "--skip-group" then normalized << "--group=#{GROUP_OFF_SENTINEL}" else normalized << argument end index += 1 end normalized end |
.start(given_args = ARGV, config = {}) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/localvault/cli.rb', line 66 def self.start(given_args = ARGV, config = {}) require_relative "cli/error_presenter" config[:shell] ||= Thor::Base.shell.new result = dispatch(nil, normalize_legacy_group_option(given_args.dup), nil, config) result.is_a?(CommandStatus) ? result.code : 0 rescue Thor::Error => error ErrorPresenter.new(self, given_args).render(error) error.respond_to?(:exit_status) ? error.exit_status : USAGE_EXIT_STATUS rescue Errno::EPIPE 0 end |
Instance Method Details
#add(handle) ⇒ Object
Grant a user access to a synced vault by creating a key slot.
With --scope, creates a per-member encrypted blob containing only the
specified keys. Without --scope, grants full vault access.
Requires the vault to be a team vault (run localvault team init first).
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 |
# File 'lib/localvault/cli.rb', line 1024 def add(handle) unless Config.token $stderr.puts "Error: Not logged in." $stderr.puts "\n localvault login YOUR_TOKEN\n" $stderr.puts "Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" return end unless Identity.exists? $stderr.puts "Error: No keypair found. Run: localvault keygen" return end target = handle vault_name = [:vault] || Config.default_vault scope_list = [:scope] master_key = ensure_master_key(vault_name) return unless master_key client = ApiClient.new(token: Config.token) # Load existing bundle — must be a team vault (v3) existing_blob = client.pull_vault(vault_name) rescue nil unless existing_blob.is_a?(String) && !existing_blob.empty? $stderr.puts "Error: Vault '#{vault_name}' is not a team vault. Run: localvault team init -v #{vault_name}" return end data = SyncBundle.unpack(existing_blob) unless data[:owner] $stderr.puts "Error: Vault '#{vault_name}' is not a team vault. Run: localvault team init -v #{vault_name}" return end unless data[:owner] == Config.inventlist_handle $stderr.puts "Error: Only the vault owner (@#{data[:owner]}) can manage team access." return end key_slots = data[:key_slots].is_a?(Hash) ? data[:key_slots] : {} # Resolve recipients — single @handle, team:HANDLE, or crew:SLUG recipients = resolve_add_recipients(client, target) if recipients.empty? $stderr.puts "Error: No recipients with public keys found for '#{target}'" return end # Decrypt the vault ONCE if we're going to need filtered blobs for # scoped members. Without this, a `team add team:HANDLE --scope KEY` # call against an N-member team re-decrypts the whole vault N times. vault = scope_list ? Vault.new(name: vault_name, master_key: master_key) : nil all_secrets = scope_list ? vault.all : nil added = 0 recipients.each do |member_handle, pub_key| next if member_handle == Config.inventlist_handle # skip self # Skip if already has full access if key_slots.key?(member_handle) && key_slots[member_handle].is_a?(Hash) && key_slots[member_handle]["scopes"].nil? $stdout.puts "@#{member_handle} already has full vault access." if scope_list next end if scope_list existing_scopes = key_slots.dig(member_handle, "scopes") || [] merged_scopes = (existing_scopes + scope_list).uniq filtered = vault.filter(merged_scopes, from: all_secrets) member_key = RbNaCl::Random.random_bytes(32) encrypted_blob = Crypto.encrypt(JSON.generate(filtered), member_key) begin enc_key = KeySlot.create(member_key, pub_key) rescue ArgumentError, KeySlot::DecryptionError => e $stderr.puts "Error: @#{member_handle}'s public key is invalid: #{e.}" next end key_slots[member_handle] = { "pub" => pub_key, "enc_key" => enc_key, "scopes" => merged_scopes, "blob" => Base64.strict_encode64(encrypted_blob) } else begin enc_key = KeySlot.create(master_key, pub_key) rescue ArgumentError, KeySlot::DecryptionError => e $stderr.puts "Error: @#{member_handle}'s public key is invalid: #{e.}" next end key_slots[member_handle] = { "pub" => pub_key, "enc_key" => enc_key, "scopes" => nil, "blob" => nil } end added += 1 end if added == 0 $stdout.puts "No new members added." return end store = Store.new(vault_name) blob = SyncBundle.pack_v3(store, owner: data[:owner], key_slots: key_slots) client.push_vault(vault_name, blob) if recipients.size == 1 h = recipients.first[0] if scope_list $stdout.puts "Added @#{h} to vault '#{vault_name}' (scopes: #{key_slots[h]["scopes"].join(", ")})." else $stdout.puts "Added @#{h} to vault '#{vault_name}'." end else $stdout.puts "Added #{added} member(s) to vault '#{vault_name}'." end rescue ApiClient::ApiError => e if e.status == 404 $stderr.puts "Error: @#{handle} not found or has no public key." else $stderr.puts "Error: #{e.}" end rescue SyncBundle::UnpackError => e $stderr.puts "Error: #{e.}" end |
#copy(key) ⇒ Object
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 |
# File 'lib/localvault/cli.rb', line 1454 def copy(key) src_vault = open_vault! value = src_vault.get(key) if value.nil? abort_with "Key '#{key}' not found in vault '#{src_vault.name}'" return end dst_vault = open_vault_by_name!([:to]) dst_vault.set(key, value) $stdout.puts "Copied '#{key}' from '#{src_vault.name}' to '#{dst_vault.name}'" end |
#dashboard ⇒ Object
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 |
# File 'lib/localvault/cli.rb', line 1225 def dashboard unless Config.token $stderr.puts "Error: Not logged in." $stderr.puts "\n localvault login YOUR_TOKEN\n" $stderr.puts "Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" return end client = ApiClient.new(token: Config.token) my_handle = Config.inventlist_handle begin list = client.list_vaults rescue ApiClient::ApiError => e $stderr.puts "Error: #{e.}" return end vaults = list["vaults"] || [] local_set = Store.list_vaults.to_set owned = [] shared = [] skipped = [] vaults.each do |v| name = v["name"] next unless name begin blob = client.pull_vault(name) rescue ApiClient::ApiError => e skipped << [name, e.] next end next if blob.nil? || blob.empty? begin data = SyncBundle.unpack(blob) rescue SyncBundle::UnpackError => e skipped << [name, e.] next end owner = data[:owner] || v["owner_handle"] local_exists = local_set.include?(name) sync_status = local_exists ? "synced" : "remote only" synced_at = v["synced_at"]&.slice(0, 10) || "—" size_label = v["size_bytes"] ? "#{(v["size_bytes"].to_f / 1024).round(1)} KB" : nil row = { name: name, owner: owner, key_slots: data[:key_slots] || {}, is_team: !owner.nil?, remote_shared: v["shared"] == true, sync_status: sync_status, synced_at: synced_at, size_label: size_label } if owner && owner == my_handle owned << row elsif v["shared"] == true || (owner && owner != my_handle) shared << row else # v1 personal vault (no owner) — treat as owned (it's yours) owned << row end end # Add local-only vaults (exist on disk but not on InventList) remote_names = vaults.map { |v| v["name"] }.compact.to_set (local_set - remote_names).sort.each do |name| owned << { name: name, owner: nil, key_slots: {}, is_team: false, remote_shared: false, sync_status: "local only", synced_at: "—", size_label: nil } end # ── Render everything in tables ── $stdout.puts # OWNED BY YOU — one table with all vaults and their members unless owned.empty? $stdout.puts VAULT_STYLE.render("OWNED BY YOU") $stdout.puts render_dashboard_table(owned.sort_by { |r| r[:name] }, my_handle: my_handle) $stdout.puts end # SHARED WITH YOU unless shared.empty? $stdout.puts VAULT_STYLE.render("SHARED WITH YOU") $stdout.puts render_dashboard_table(shared.sort_by { |r| r[:name] }, my_handle: my_handle) $stdout.puts end if owned.empty? && shared.empty? $stdout.puts COUNT_STYLE.render("No vaults found. Create one with `localvault init NAME`.") $stdout.puts end # LEGACY DIRECT SHARES — only show if there are any sent = safe_fetch_shares { client.sent_shares } pending = safe_fetch_shares { client.pending_shares } outgoing_count = (sent["shares"] || []).reject { |s| s["status"] == "revoked" }.size pending_count = (pending["shares"] || []).size if outgoing_count + pending_count > 0 $stdout.puts VAULT_STYLE.render("LEGACY DIRECT SHARES") legacy_rows = [] (sent["shares"] || []).reject { |s| s["status"] == "revoked" }.each do |s| legacy_rows << [s["vault_name"] || "—", "@#{s["recipient_handle"]}", s["status"], "outgoing"] end (pending["shares"] || []).each do |s| legacy_rows << [s["vault_name"] || "—", "@#{s["sender_handle"]}", "pending", "incoming"] end $stdout.puts render_legacy_shares_table(legacy_rows) $stdout.puts end # Skipped unless skipped.empty? $stderr.puts COUNT_STYLE.render("#{skipped.size} vault(s) could not be loaded:") skipped.each { |name, reason| $stderr.puts " #{name}: #{reason}" } $stdout.puts end end |
#delete(key) ⇒ Object
365 366 367 368 369 370 371 372 373 |
# File 'lib/localvault/cli.rb', line 365 def delete(key) vault = open_vault! deleted = vault.delete(key) if deleted.nil? abort_with "Key '#{key}' not found in vault '#{vault.name}'" return end $stdout.puts "Deleted #{key} from vault '#{vault.name}'" end |
#demo ⇒ Object
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 |
# File 'lib/localvault/cli.rb', line 712 def demo names = Store.list_vaults unless names.empty? abort_with "Vaults already exist (#{names.join(", ")}). " \ "Run `localvault reset <name>` to clear one, or use a fresh LOCALVAULT_HOME." return end $stderr.puts "This creates DEMO vaults with fake data for learning purposes." $stderr.puts "These are NOT for real secrets. Passphrase for all vaults: \"demo\"" $stderr.print "Type 'demo' to continue: " confirmation = prompt_confirmation unless confirmation == "demo" abort_with "Cancelled." return end DEMO_DATA.each do |vault_name, secrets| salt = Crypto.generate_salt master_key = Crypto.derive_master_key("demo", salt) vault = Vault.create!(name: vault_name, master_key: master_key, salt: salt) vault.merge(secrets) $stdout.puts " created vault '#{vault_name}' (#{secrets.size} secrets)" end $stdout.puts $stdout.puts "Done! All vaults use passphrase: demo" $stdout.puts $stdout.puts "Try:" $stdout.puts " localvault vaults" $stdout.puts " localvault show" $stdout.puts " localvault show --vault x --group" $stdout.puts " localvault show --vault production --reveal" $stdout.puts " localvault exec -- env | grep -E 'DATABASE|REDIS'" end |
#doctor ⇒ Object
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 |
# File 'lib/localvault/cli.rb', line 1504 def doctor paths = localvault_paths warnings = localvault_path_warnings(paths) $stdout.puts "LocalVault doctor" $stdout.puts "Version: localvault #{VERSION}" $stdout.puts "Home: #{Config.root_path}" if paths.empty? $stdout.puts "Executable selected by PATH: not found" else $stdout.puts "Executable selected by PATH: #{paths.first}" $stdout.puts "All localvault executables on PATH:" paths.each_with_index { |path, index| $stdout.puts " #{index + 1}. #{path}" } end if warnings.empty? $stdout.puts "PATH: ok" CommandStatus.ok else $stdout.puts warnings.each { |warning| $stdout.puts "Warning: #{warning}" } $stdout.puts $stdout.puts "Suggested checks:" $stdout.puts " asdf reshim ruby" $stdout.puts " hash -r" $stdout.puts " which -a localvault" CommandStatus.error end end |
#env ⇒ Object
404 405 406 407 408 409 410 |
# File 'lib/localvault/cli.rb', line 404 def env vault = open_vault! skip_warn = ->(k) { $stderr.puts "Warning: skipping unsafe key '#{k}'" } $stdout.puts vault.export_env(**(on_skip: skip_warn)) rescue EnvProjection::InvalidMapping, EnvProjection::UnknownProfile => e abort_with e. end |
#exec(*cmd) ⇒ Object
439 440 441 442 443 444 445 446 |
# File 'lib/localvault/cli.rb', line 439 def exec(*cmd) vault = open_vault! skip_warn = ->(k) { $stderr.puts "Warning: skipping unsafe key '#{k}'" } env_vars = vault.env_hash(**(on_skip: skip_warn)) Kernel.exec(env_vars, *cmd) rescue EnvProjection::InvalidMapping, EnvProjection::UnknownProfile => e abort_with e. end |
#get(key) ⇒ Object
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/localvault/cli.rb', line 290 def get(key) vault = open_vault! lookup = KeyLookup.lookup(vault, key) if lookup.exact? $stdout.puts lookup.value elsif lookup.single_match? $stdout.puts vault.get(lookup.matches.first) elsif lookup.multiple_matches? $stderr.puts "Error: Multiple keys match '#{key}'. Be more specific:" lookup.matches.each { |k| $stderr.puts " #{k}" } else abort_with "Key '#{key}' not found in vault '#{vault.name}'" end end |
#groups(query = nil) ⇒ Object
337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
# File 'lib/localvault/cli.rb', line 337 def groups(query = nil) vault = open_vault! matches = GroupCatalog.new(vault.all).search(query) if matches.empty? $stdout.puts "No groups match #{query}" return end heading = query ? "Groups matching `#{query}`" : "Groups" $stdout.puts "#{heading} in vault `#{vault.name}`:" $stdout.puts $stdout.printf(" %-20s %-6s %s\n", "Group", "Keys", "Kind") matches.each { |group| $stdout.printf(" %-20s %-6d %s\n", group.name, group.count, group.kind) } end |
#import(file) ⇒ Object
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 |
# File 'lib/localvault/cli.rb', line 1378 def import(file) unless File.exist?(file) abort_with "File not found: #{file}" return end data = parse_import_file(file) if data.nil? || data.empty? abort_with "No secrets found in #{file}" return end vault = open_vault! project = [:project] # Restructure data for bulk merge to_merge = {} data.each do |key, value| if value.is_a?(Hash) to_merge[key] = value elsif project to_merge[project] ||= {} to_merge[project][key] = value.to_s else to_merge[key] = value.to_s end end vault.merge(to_merge) count = to_merge.sum { |_, v| v.is_a?(Hash) ? v.size : 1 } $stdout.puts "Imported #{count} secret(s) into vault '#{vault.name}'" \ "#{project ? " / #{project}" : ""}." rescue RuntimeError => e abort_with e. end |
#init(name = nil) ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/localvault/cli.rb', line 193 def init(name = nil) vault_name = name || Config.default_vault passphrase = prompt_passphrase("Passphrase: ") if passphrase.empty? abort_with "Passphrase cannot be empty" return end confirm = prompt_passphrase("Confirm passphrase: ") if passphrase != confirm abort_with "Passphrases do not match" return end salt = Crypto.generate_salt master_key = Crypto.derive_master_key(passphrase, salt) Vault.create!(name: vault_name, master_key: master_key, salt: salt) $stdout.puts "Vault '#{vault_name}' created." rescue RuntimeError => e abort_with e. end |
#install_mcp(client = "claude-code") ⇒ Object
701 702 703 704 705 706 707 708 709 |
# File 'lib/localvault/cli.rb', line 701 def install_mcp(client = "claude-code") case client.downcase when "claude-code" then install_for_claude_code when "cursor" then install_mcp_via_json("Cursor", cursor_settings_path) when "windsurf" then install_mcp_via_json("Windsurf", windsurf_settings_path) else abort_with "Unknown client '#{client}'. Supported: claude-code, cursor, windsurf" end end |
#keygen ⇒ Object
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 |
# File 'lib/localvault/cli.rb', line 765 def keygen if [:show] unless Identity.exists? $stdout.puts "No keypair found. Run: localvault keygen" return end $stdout.puts Identity.public_key return end if Identity.exists? && ![:force] $stdout.puts "Keypair already exists. Use --force to regenerate." return end Config.ensure_directories! Identity.generate!(force: [:force]) $stdout.puts "Keypair generated." $stdout.puts "Public key: #{Identity.public_key}" end |
#list ⇒ Object
323 324 325 326 |
# File 'lib/localvault/cli.rb', line 323 def list vault = open_vault! vault.list.each { |key| $stdout.puts key } end |
#lock(name = nil) ⇒ Object
635 636 637 638 639 640 641 642 643 |
# File 'lib/localvault/cli.rb', line 635 def lock(name = nil) if name SessionCache.clear(name) $stdout.puts "Session cleared for vault '#{name}'." else SessionCache.clear_all $stdout.puts "All vault sessions cleared." end end |
#login(token = nil) ⇒ Object
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 |
# File 'lib/localvault/cli.rb', line 788 def login(token = nil) if [:status] handle = Config.inventlist_handle if handle $stdout.puts "Logged in as @#{handle}" else $stdout.puts "Not logged in. Run: localvault login TOKEN" end return end unless token $stdout.puts "Usage: localvault login YOUR_TOKEN" $stdout.puts $stdout.puts "Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" $stdout.puts "New to InventList? Sign up free at https://inventlist.com" $stdout.puts $stdout.puts "LocalVault sync and team features require a free InventList account." $stdout.puts "Local vault encryption works without an account." $stdout.puts $stdout.puts "Docs: https://inventlist.com/sites/localvault/series/localvault" return end client = ApiClient.new(token: token) data = client.me handle = data.dig("user", "handle") Config.token = token Config.inventlist_handle = handle Config.ensure_directories! Identity.generate! unless Identity.exists? client.publish_public_key(Identity.public_key) $stdout.puts "Logged in as @#{handle}" $stdout.puts "Public key published to your InventList profile." $stdout.puts $stdout.puts "Next: localvault sync push # sync your vault to the cloud" rescue ApiClient::ApiError => e if e.status == 401 $stdout.puts "Invalid token. Check your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" else $stdout.puts "Error connecting to InventList: #{e.}" end end |
#logout ⇒ Object
837 838 839 840 841 842 843 844 845 846 847 |
# File 'lib/localvault/cli.rb', line 837 def logout unless Config.token $stdout.puts "Not logged in." return end handle = Config.inventlist_handle Config.token = nil Config.inventlist_handle = nil $stdout.puts "Logged out#{" @#{handle}" if handle}." end |
#mcp ⇒ Object
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 |
# File 'lib/localvault/cli.rb', line 663 def mcp if [:check] require_relative "mcp/tools" status = VaultResolver.readiness_status([:vault]) ready = status["active_vault_unlocked"] tool_names = MCP::Tools::DEFINITIONS.map { |definition| definition.fetch("name") } $stdout.puts "LocalVault #{VERSION}" $stdout.puts "Home: #{Config.root_path}" $stdout.puts "MCP readiness: #{ready ? "ready" : "locked"}" $stdout.puts "Active vault: #{status["active_vault"]} (#{status["active_vault_source"]})" $stdout.puts "Vault session: #{ready ? "available" : "unlock with `localvault show`"}" $stdout.puts "MCP tools: #{tool_names.join(", ")}" $stdout.puts "Plaintext gate: enabled" $stdout.puts "Server instructions: enabled" $stdout.puts $stdout.puts "Safe agent workflow: list_secrets → localvault_build_exec → run the generated command" $stdout.puts "Plaintext retrieval is opt-in with allow_plaintext: true." return ready ? CommandStatus.ok : CommandStatus.error end require_relative "mcp/server" MCP::Server.new.start end |
#receive ⇒ Object
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 |
# File 'lib/localvault/cli.rb', line 895 def receive unless Config.token abort_with "Not logged in. Run: localvault login YOUR_TOKEN\n Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" return end unless Identity.private_key_bytes abort_with "No keypair found. Run: localvault keys generate" return end client = ApiClient.new(token: Config.token) result = client.pending_shares shares = result["shares"] || [] if shares.empty? $stdout.puts "No pending shares." return end $stdout.puts "Found #{shares.size} pending share(s):" $stdout.puts imported = 0 shares.each do |share| vault_name = sanitize_receive_vault_name(share["vault_name"], share["sender_handle"]) $stdout.puts " [#{share["id"]}] vault '#{share["vault_name"]}' from @#{share["sender_handle"]}" begin secrets = ShareCrypto.decrypt_from(share["encrypted_payload"], Identity.private_key_bytes) rescue ShareCrypto::DecryptionError => e $stderr.puts " Failed to decrypt: #{e.}" next end if Store.new(vault_name).exists? $stdout.puts " Vault '#{vault_name}' already exists, skipping." next end passphrase = prompt_passphrase(" Passphrase for new vault '#{vault_name}': ") if passphrase.empty? $stderr.puts " Skipped (empty passphrase)." next end salt = Crypto.generate_salt master_key = Crypto.derive_master_key(passphrase, salt) vault = Vault.create!(name: vault_name, master_key: master_key, salt: salt) vault.merge(secrets) count = secrets.sum { |_, v| v.is_a?(Hash) ? v.size : 1 } $stdout.puts " Imported #{count} secret(s) → vault '#{vault_name}'" begin client.accept_share(share["id"]) rescue ApiClient::ApiError => e $stderr.puts " Warning: could not mark share as accepted: #{e.}" end imported += 1 end $stdout.puts $stdout.puts "Done. #{imported} vault(s) imported." rescue ApiClient::ApiError => e abort_with e. end |
#rekey(name = nil) ⇒ Object
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
# File 'lib/localvault/cli.rb', line 555 def rekey(name = nil) vault_name = name || resolve_vault_name store = Store.new(vault_name) unless store.exists? abort_with "Vault '#{vault_name}' does not exist." return end current = prompt_passphrase("Current passphrase: ") vault = Vault.open(name: vault_name, passphrase: current) vault.all # verify new_pass = prompt_passphrase("New passphrase: ") if new_pass.empty? abort_with "Passphrase cannot be empty" return end confirm = prompt_passphrase("Confirm new passphrase: ") unless new_pass == confirm abort_with "Passphrases do not match" return end new_vault = vault.rekey(new_pass) SessionCache.set(vault_name, new_vault.master_key) $stdout.puts "Passphrase updated for vault '#{vault_name}'." rescue Crypto::DecryptionError abort_with "Wrong passphrase for vault '#{vault_name}'" rescue RuntimeError => e abort_with e. end |
#remove(handle) ⇒ Object
Remove a user's access to a vault.
Removes the user's key slot and pushes the updated bundle. With --rotate,
re-encrypts the vault with a new master key and recreates all remaining
key slots for full cryptographic revocation. Falls back to revoking a
direct share if no key slots exist.
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 |
# File 'lib/localvault/cli.rb', line 1162 def remove(handle) unless Config.token $stderr.puts "Error: Not logged in." $stderr.puts $stderr.puts " localvault login YOUR_TOKEN" $stderr.puts $stderr.puts "Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" $stderr.puts "New to InventList? Sign up free at https://inventlist.com" $stderr.puts "Docs: https://inventlist.com/sites/localvault/series/localvault" return end handle = handle.delete_prefix("@") vault_name = [:vault] || Config.default_vault client = ApiClient.new(token: Config.token) # Try sync-based key slot removal first team_data = load_team_data(client, vault_name) if team_data && team_data[:key_slots] && !team_data[:key_slots].empty? # Must be a v3 team vault with owner unless team_data[:owner] $stderr.puts "Error: Vault '#{vault_name}' is not a team vault. Run: localvault team init -v #{vault_name}" return end unless team_data[:owner] == Config.inventlist_handle $stderr.puts "Error: Only the vault owner (@#{team_data[:owner]}) can manage team access." return end remove_key_slot(handle, vault_name, team_data[:key_slots], client, rotate: [:rotate], remove_scopes: [:scope], owner: team_data[:owner]) return end # Fall back to direct share revocation result = client.sent_shares(vault_name: vault_name) share = (result["shares"] || []).find do |s| s["recipient_handle"] == handle && s["status"] != "revoked" end unless share $stderr.puts "Error: No active share found for @#{handle}." return end client.revoke_share(share["id"]) $stdout.puts "Removed @#{handle} from vault '#{vault_name}'." rescue ApiClient::ApiError => e $stderr.puts "Error: #{e.}" end |
#rename(old_key, new_key) ⇒ Object
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 |
# File 'lib/localvault/cli.rb', line 1428 def rename(old_key, new_key) vault = open_vault! value = vault.get(old_key) if value.nil? abort_with "Key '#{old_key}' not found in vault '#{vault.name}'" return end vault.set(new_key, value) vault.delete(old_key) $stdout.puts "Renamed '#{old_key}' → '#{new_key}' in vault '#{vault.name}'" end |
#reset(name = nil) ⇒ Object
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 |
# File 'lib/localvault/cli.rb', line 590 def reset(name = nil) vault_name = name || resolve_vault_name store = Store.new(vault_name) unless store.exists? abort_with "Vault '#{vault_name}' does not exist. Run: localvault init #{vault_name}" return end $stderr.puts "WARNING: This will permanently delete all secrets in vault '#{vault_name}'." $stderr.puts "This cannot be undone." $stderr.print "Type '#{vault_name}' to confirm: " confirmation = prompt_confirmation unless confirmation == vault_name abort_with "Cancelled." return end # Gather + validate the new passphrase BEFORE destroying the existing # vault. If the user enters empty / mismatched / interrupts, we abort # without touching anything on disk. passphrase = prompt_passphrase("New passphrase: ") if passphrase.empty? abort_with "Passphrase cannot be empty" return end confirm = prompt_passphrase("Confirm passphrase: ") unless passphrase == confirm abort_with "Passphrases do not match" return end # All inputs validated — safe to destroy + recreate. store.destroy! salt = Crypto.generate_salt master_key = Crypto.derive_master_key(passphrase, salt) Vault.create!(name: vault_name, master_key: master_key, salt: salt) $stdout.puts "Vault '#{vault_name}' has been reset." rescue RuntimeError => e abort_with e. end |
#revoke(share_id) ⇒ Object
963 964 965 966 967 968 969 970 971 972 973 974 975 |
# File 'lib/localvault/cli.rb', line 963 def revoke(share_id) unless Config.token abort_with "Not logged in. Run: localvault login YOUR_TOKEN\n Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" return end client = ApiClient.new(token: Config.token) client.revoke_share(share_id) $stdout.puts "Share #{share_id} revoked." $stdout.puts "Note: @recipient retains any secrets already received." rescue ApiClient::ApiError => e abort_with e. end |
#set(key, value = nil) ⇒ Object
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
# File 'lib/localvault/cli.rb', line 245 def set(key, value = nil) validate_secret_value_source!(value) vault = open_vault! if [:group] group = canonical_group_name(vault, [:group]) validate_group_segment!(group) validate_group_segment!(key) raise GroupSaveError, :collision if vault.all.key?(group) && !vault.all[group].is_a?(Hash) value = read_secret_value(value) vault.set("#{group}.#{key}", value) $stdout.puts "Set #{key} in group `#{group}` in vault `#{vault.name}`." $stdout.puts $stdout.puts "Stored as:" $stdout.puts " #{group}.#{key}" else value = read_secret_value(value) vault.set(key, value) $stdout.puts "Set #{key} in vault '#{vault.name}'" end rescue StdinSecretInput::InteractiveInput, StdinSecretInput::InvalidEncoding => e raise SetValueSourceError.new(:stdin, e.) rescue Vault::InvalidKeyName => e raise GroupSaveError, :invalid if [:group] abort_with e. CommandStatus.error rescue RuntimeError => e raise GroupSaveError, :collision if [:group] abort_with e. CommandStatus.error end |
#share(vault_name = nil) ⇒ Object
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
# File 'lib/localvault/cli.rb', line 852 def share(vault_name = nil) unless Config.token abort_with "Not logged in. Run: localvault login YOUR_TOKEN\n Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" return end unless Identity.exists? abort_with "No keypair found. Run: localvault keys generate && localvault keys publish" return end vault_name ||= resolve_vault_name vault = open_vault_by_name!(vault_name) secrets = vault.all if secrets.empty? abort_with "Vault '#{vault_name}' has no secrets to share." return end client = ApiClient.new(token: Config.token) target = [:with] recipients = resolve_recipients(client, target) if recipients.empty? abort_with "No recipients with public keys found for '#{target}'" return end recipients.each do |handle, pub_key| encrypted = ShareCrypto.encrypt_for(secrets, pub_key) client.create_share( vault_name: vault_name, recipient_handle: handle, encrypted_payload: encrypted ) $stdout.puts "Shared vault '#{vault_name}' with @#{handle}" end rescue ApiClient::ApiError => e abort_with e. end |
#show ⇒ Object
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
# File 'lib/localvault/cli.rb', line 520 def show vault = open_vault! secrets = vault.all named_group_query = [:group] && ![GROUP_ALL_SENTINEL, GROUP_OFF_SENTINEL].include?([:group]) if secrets.empty? && !named_group_query $stdout.puts "No secrets in vault '#{vault.name}'." return end if [:project] group = secrets[[:project]] unless group.is_a?(Hash) abort_with "No project '#{[:project]}' in vault '#{vault.name}'" return end render_table(group.sort.to_h, "#{vault.name}/#{[:project]}", reveal: [:reveal]) elsif [:group] && ![GROUP_ALL_SENTINEL, GROUP_OFF_SENTINEL].include?([:group]) match = GroupCatalog.new(secrets).resolve([:group]) if match.group entries = match.group.entries.to_h { |entry| [entry.label, entry.value] } render_table(entries, "#{vault.name}/#{match.group.name}", reveal: [:reveal]) elsif match.kind == :ambiguous raise GroupSelectionError.new(:ambiguous, query: [:group], candidates: match.groups.map(&:name)) else raise GroupSelectionError.new(:absent, query: [:group]) end elsif [:group] != GROUP_OFF_SENTINEL && ([:group] || secrets.values.any? { |v| v.is_a?(Hash) }) render_grouped_table(secrets, vault.name, reveal: [:reveal]) else render_table(secrets.sort.to_h, vault.name, reveal: [:reveal]) end end |
#switch(vault_name = nil) ⇒ Object
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 |
# File 'lib/localvault/cli.rb', line 1468 def switch(vault_name = nil) if vault_name.nil? current = Config.default_vault $stdout.puts "Current vault: #{current}" $stdout.puts $stdout.puts "Available vaults:" Store.list_vaults.each do |name| marker = name == current ? " ← current" : "" $stdout.puts " #{name}#{marker}" end return end unless Store.new(vault_name).exists? abort_with "Vault '#{vault_name}' does not exist. Run: localvault init #{vault_name}" return end Config.default_vault = vault_name $stdout.puts "Switched to vault '#{vault_name}'" end |
#unlock(vault_name = nil) ⇒ Object
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
# File 'lib/localvault/cli.rb', line 480 def unlock(vault_name = nil) vault_name ||= resolve_vault_name store = Store.new(vault_name) unless store.exists? abort_with "Vault '#{vault_name}' does not exist. Run: localvault init #{vault_name}" return end passphrase = prompt_passphrase("Passphrase: ") master_key = Crypto.derive_master_key(passphrase, store.salt) # Verify passphrase by attempting to decrypt vault = Vault.new(name: vault_name, master_key: master_key) vault.all SessionCache.set(vault_name, master_key) token = Base64.strict_encode64("#{vault_name}:#{Base64.strict_encode64(master_key)}") $stdout.puts "export LOCALVAULT_SESSION=\"#{token}\"" rescue Crypto::DecryptionError abort_with "Wrong passphrase for vault '#{vault_name}'" end |
#vaults ⇒ Object
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
# File 'lib/localvault/cli.rb', line 449 def vaults names = Store.list_vaults if names.empty? $stdout.puts "No vaults found. Run: localvault init" return end default_name = Config.default_vault rows = names.map do |name| store = Store.new(name) default_marker = name == default_name ? "✓" : "" [name, store.count.to_s, default_marker] end table = Lipgloss::Table.new .headers(["Vault", "Secrets", "Default"]) .rows(rows) .border(:rounded) .style_func(rows: rows.size, columns: 3) do |row, _col| if row == Lipgloss::Table::HEADER_ROW HEADER_STYLE else row.odd? ? ODD_STYLE : EVEN_STYLE end end .render $stdout.puts table end |
#verify(handle) ⇒ Object
Verify a user's handle and public key status before adding them.
Checks InventList for the handle and whether they have a published X25519 public key. Does not modify anything.
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
# File 'lib/localvault/cli.rb', line 986 def verify(handle) unless Config.token $stderr.puts "Error: Not logged in." $stderr.puts "\n localvault login YOUR_TOKEN\n" $stderr.puts "Get your token at: https://inventlist.com/@YOUR_HANDLE/edit#developer" return end handle = handle.delete_prefix("@") client = ApiClient.new(token: Config.token) result = client.get_public_key(handle) pub_key = result["public_key"] if pub_key && !pub_key.empty? fingerprint = pub_key.length > 12 ? "#{pub_key[0..7]}...#{pub_key[-4..]}" : pub_key $stdout.puts "@#{handle} — public key published" $stdout.puts " Fingerprint: #{fingerprint}" $stdout.puts " Ready for: localvault add @#{handle} -v VAULT" else $stderr.puts "@#{handle} exists but has no public key published." $stderr.puts "They need to run: localvault login TOKEN" end rescue ApiClient::ApiError => e if e.status == 404 $stderr.puts "Error: @#{handle} not found on InventList." else $stderr.puts "Error: #{e.}" end end |
#version ⇒ Object
1491 1492 1493 |
# File 'lib/localvault/cli.rb', line 1491 def version $stdout.puts "localvault #{VERSION}" end |