Class: LocalVault::CLI

Inherits:
Thor
  • Object
show all
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, 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

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


1466
1467
1468
# File 'lib/localvault/cli.rb', line 1466

def self.exit_on_failure?
  false
end

.help(shell, subcommand = false) ⇒ Object



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
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
# File 'lib/localvault/cli.rb', line 97

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 "  localvault set KEY VALUE      Store a secret"
  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 help [COMMAND]     Full help for any command"
  shell.say ""
end

.normalize_legacy_group_option(arguments) ⇒ Object



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
# File 'lib/localvault/cli.rb', line 65

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



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/localvault/cli.rb', line 53

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).



995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
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
# File 'lib/localvault/cli.rb', line 995

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 = options[:vault] || Config.default_vault
  scope_list = options[: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.message}"
        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.message}"
        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.message}"
  end
rescue SyncBundle::UnpackError => e
  $stderr.puts "Error: #{e.message}"
end

#copy(key) ⇒ Object



1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
# File 'lib/localvault/cli.rb', line 1425

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!(options[:to])
  dst_vault.set(key, value)
  $stdout.puts "Copied '#{key}' from '#{src_vault.name}' to '#{dst_vault.name}'"
end

#dashboardObject



1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
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
# File 'lib/localvault/cli.rb', line 1196

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.message}"
    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.message]
      next
    end

    next if blob.nil? || blob.empty?

    begin
      data = SyncBundle.unpack(blob)
    rescue SyncBundle::UnpackError => e
      skipped << [name, e.message]
      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



336
337
338
339
340
341
342
343
344
# File 'lib/localvault/cli.rb', line 336

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

#demoObject



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/localvault/cli.rb', line 683

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

#envObject



375
376
377
378
379
380
381
# File 'lib/localvault/cli.rb', line 375

def env
  vault = open_vault!
  skip_warn = ->(k) { $stderr.puts "Warning: skipping unsafe key '#{k}'" }
  $stdout.puts vault.export_env(**env_projection_options(on_skip: skip_warn))
rescue EnvProjection::InvalidMapping, EnvProjection::UnknownProfile => e
  abort_with e.message
end

#exec(*cmd) ⇒ Object



410
411
412
413
414
415
416
417
# File 'lib/localvault/cli.rb', line 410

def exec(*cmd)
  vault = open_vault!
  skip_warn = ->(k) { $stderr.puts "Warning: skipping unsafe key '#{k}'" }
  env_vars = vault.env_hash(**env_projection_options(on_skip: skip_warn))
  Kernel.exec(env_vars, *cmd)
rescue EnvProjection::InvalidMapping, EnvProjection::UnknownProfile => e
  abort_with e.message
end

#get(key) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/localvault/cli.rb', line 261

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



308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/localvault/cli.rb', line 308

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



1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
# File 'lib/localvault/cli.rb', line 1349

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 = options[: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.message
end

#init(name = nil) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/localvault/cli.rb', line 177

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.message
end

#install_mcp(client = "claude-code") ⇒ Object



672
673
674
675
676
677
678
679
680
# File 'lib/localvault/cli.rb', line 672

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

#keygenObject



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/localvault/cli.rb', line 736

def keygen
  if options[:show]
    unless Identity.exists?
      $stdout.puts "No keypair found. Run: localvault keygen"
      return
    end
    $stdout.puts Identity.public_key
    return
  end

  if Identity.exists? && !options[:force]
    $stdout.puts "Keypair already exists. Use --force to regenerate."
    return
  end

  Config.ensure_directories!
  Identity.generate!(force: options[:force])
  $stdout.puts "Keypair generated."
  $stdout.puts "Public key: #{Identity.public_key}"
end

#listObject



294
295
296
297
# File 'lib/localvault/cli.rb', line 294

def list
  vault = open_vault!
  vault.list.each { |key| $stdout.puts key }
end

#lock(name = nil) ⇒ Object



606
607
608
609
610
611
612
613
614
# File 'lib/localvault/cli.rb', line 606

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



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# File 'lib/localvault/cli.rb', line 759

def (token = nil)
  if options[: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.message}"
  end
end

#logoutObject



808
809
810
811
812
813
814
815
816
817
818
# File 'lib/localvault/cli.rb', line 808

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

#mcpObject



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/localvault/cli.rb', line 634

def mcp
  if options[:check]
    require_relative "mcp/tools"
    status = VaultResolver.readiness_status(options[: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

#receiveObject



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
893
894
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
# File 'lib/localvault/cli.rb', line 866

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.message}"
      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.message}"
    end
    imported += 1
  end

  $stdout.puts
  $stdout.puts "Done. #{imported} vault(s) imported."
rescue ApiClient::ApiError => e
  abort_with e.message
end

#rekey(name = nil) ⇒ Object



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
553
554
555
556
557
558
# File 'lib/localvault/cli.rb', line 526

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.message
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.



1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
# File 'lib/localvault/cli.rb', line 1133

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 = options[: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: options[:rotate], remove_scopes: options[: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.message}"
end

#rename(old_key, new_key) ⇒ Object



1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
# File 'lib/localvault/cli.rb', line 1399

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



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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/localvault/cli.rb', line 561

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.message
end

#revoke(share_id) ⇒ Object



934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/localvault/cli.rb', line 934

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.message
end

#set(key, value) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/localvault/cli.rb', line 223

def set(key, value)
  vault = open_vault!
  if options[:group]
    group = canonical_group_name(vault, options[:group])
    validate_group_segment!(group)
    validate_group_segment!(key)
    raise GroupSaveError, :collision if vault.all.key?(group) && !vault.all[group].is_a?(Hash)
    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
    vault.set(key, value)
    $stdout.puts "Set #{key} in vault '#{vault.name}'"
  end
rescue Vault::InvalidKeyName => e
  raise GroupSaveError, :invalid if options[:group]
  abort_with e.message
rescue RuntimeError => e
  raise GroupSaveError, :collision if options[:group]
  abort_with e.message
end

#share(vault_name = nil) ⇒ Object



823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# File 'lib/localvault/cli.rb', line 823

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     = options[: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.message
end

#showObject



491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/localvault/cli.rb', line 491

def show
  vault = open_vault!
  secrets = vault.all

  named_group_query = options[:group] && ![GROUP_ALL_SENTINEL, GROUP_OFF_SENTINEL].include?(options[:group])
  if secrets.empty? && !named_group_query
    $stdout.puts "No secrets in vault '#{vault.name}'."
    return
  end

  if options[:project]
    group = secrets[options[:project]]
    unless group.is_a?(Hash)
      abort_with "No project '#{options[:project]}' in vault '#{vault.name}'"
      return
    end
    render_table(group.sort.to_h, "#{vault.name}/#{options[:project]}", reveal: options[:reveal])
  elsif options[:group] && ![GROUP_ALL_SENTINEL, GROUP_OFF_SENTINEL].include?(options[:group])
    match = GroupCatalog.new(secrets).resolve(options[:group])
    if match.group
      entries = match.group.entries.to_h { |entry| [entry.label, entry.value] }
      render_table(entries, "#{vault.name}/#{match.group.name}", reveal: options[:reveal])
    elsif match.kind == :ambiguous
      raise GroupSelectionError.new(:ambiguous, query: options[:group], candidates: match.groups.map(&:name))
    else
      raise GroupSelectionError.new(:absent, query: options[:group])
    end
  elsif options[:group] != GROUP_OFF_SENTINEL && (options[:group] || secrets.values.any? { |v| v.is_a?(Hash) })
    render_grouped_table(secrets, vault.name, reveal: options[:reveal])
  else
    render_table(secrets.sort.to_h, vault.name, reveal: options[:reveal])
  end
end

#switch(vault_name = nil) ⇒ Object



1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
# File 'lib/localvault/cli.rb', line 1439

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



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/localvault/cli.rb', line 451

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

#vaultsObject



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/localvault/cli.rb', line 420

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.



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
# File 'lib/localvault/cli.rb', line 957

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.message}"
  end
end

#versionObject



1462
1463
1464
# File 'lib/localvault/cli.rb', line 1462

def version
  $stdout.puts "localvault #{VERSION}"
end