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/guard.rb,
lib/localvault/cli/help_shell.rb,
lib/localvault/cli/identity_cmd.rb,
lib/localvault/cli/team_helpers.rb,
lib/localvault/cli/error_presenter.rb

Defined Under Namespace

Modules: TeamHelpers Classes: CommandStatus, ErrorPresenter, GroupSaveError, GroupSelectionError, Guard, HelpShell, IdentityCommand, Keys, SetValueSourceError, Sync, Team

Constant Summary collapse

USAGE_EXIT_STATUS =
1
GROUP_ALL_SENTINEL =
"\0localvault-all-groups"
GROUP_OFF_SENTINEL =
"\0localvault-groups-off"
HELP_SECTIONS =

Grouped help, generated from the command registry. Only command NAMES are declared per section — usage strings and descriptions come from Thor, and any command missing from this map lands in OTHER instead of disappearing from help.

[
  ["GETTING STARTED",                                       %w[login config init demo]],
  ["SECRETS",                                               %w[set get show reveal groups list delete import env exec]],
  ["VAULT MANAGEMENT",                                      %w[vaults switch rekey unlock lock reset rename copy]],
  ["SYNC  (requires localvault login)",                     %w[sync]],
  ["TEAM SHARING  (requires localvault login)",             %w[dashboard verify add remove team]],
  ["KEYS  (X25519 identity for vault sharing)",             %w[keys identity]],
  ["AI / MCP",                                              %w[install-mcp mcp guard]],
  ["LEGACY SHARING  (pre-v1.2 direct share, still works)",  %w[keygen share receive revoke]],
  ["OTHER",                                                 %w[logout version doctor help]]
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


1652
1653
1654
# File 'lib/localvault/cli.rb', line 1652

def self.exit_on_failure?
  false
end

.help(shell, subcommand = false) ⇒ Object



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

def self.help(shell, subcommand = false)
  sections = HELP_SECTIONS.map { |title, names| [title, names.dup] }
  known    = HELP_SECTIONS.flat_map { |_, names| names.map { |n| n.tr("-", "_") } }
  leftovers = all_commands.reject { |_, c| c.hidden? }.keys - known
  sections.last[1].concat(leftovers.map { |n| n.tr("_", "-") })

  rendered = sections.map { |title, names| [title, names.flat_map { |n| help_rows_for(n) }] }
  width = rendered.flat_map { |_, rows| rows.map { |usage, _| usage.length } }.max + 4

  shell.say ""
  shell.say shell.set_color("LocalVault", :cyan, true) + " — encrypted local secrets vault with MCP support for AI agents"
  shell.say "  https://inventlist.com/tools/localvault"

  rendered.each do |title, rows|
    next if rows.empty?
    shell.say ""
    shell.say title
    rows.each do |usage, desc|
      shell.say "  localvault #{shell.set_color(usage.ljust(width), :green)}#{desc}"
    end
  end

  shell.say ""
  shell.say("SAFE SECRET INPUT  (preferred over passing values as arguments)")
  shell.say "  printf '%s' \"$SECRET\" | localvault set KEY --stdin"
  shell.say ""
  shell.say("PROJECTS  (dot-notation groups inside one vault)")
  shell.say "  localvault set platepose.API_KEY v    Store a key in the 'platepose' group"
  shell.say "  Filter any command with -p:  show -p platepose, exec -p platepose -- CMD"
  shell.say "  Delete a whole group:        localvault delete 'platepose.*'"
  shell.say ""
  shell.say("USING SECRETS WITH ANY CLI")
  shell.say "  localvault exec -- inventlist ships list"
  shell.say "  localvault exec -- curl -H \"Authorization: Bearer $API_KEY\" ..."
  shell.say ""
  shell.say "Own sync host: localvault config set server URL (default: inventlist.com)"
  shell.say "Subcommands:   localvault help team|keys|guard|identity|sync"
  shell.say "Full help for any command: localvault help COMMAND"
  shell.say ""
end

.help_rows_for(name) ⇒ Object

One row per plain command; registered subcommands (sync, team, keys, guard, identity, ...) expand to a row per action, straight from that registry — so sync push or a newly added guard action is always visible without touching this method.



133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/localvault/cli.rb', line 133

def self.help_rows_for(name)
  command = all_commands[name.tr("-", "_")]
  return [] if command.nil? || command.hidden?

  registry = subcommand_classes[command.name]
  return [[command.usage, command.description]] unless registry

  registry.all_commands.filter_map do |sub_name, sub|
    next if sub.hidden? || %w[help tree].include?(sub_name)  # Thor built-ins, redundant per-namespace
    ["#{command.name} #{sub.usage}", sub.description]
  end
end

.normalize_legacy_group_option(arguments) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/localvault/cli.rb', line 81

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



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/localvault/cli.rb', line 67

def self.start(given_args = ARGV, config = {})
  require_relative "cli/error_presenter"
  require_relative "cli/help_shell"
  Thor::Base.shell = HelpShell   # subcommand namespaces build their own shells
  config[:shell] ||= HelpShell.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).



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

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

#config(action = "get", field = nil, value = nil) ⇒ Object



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

def config(action = "get", field = nil, value = nil)
  unless field == "server" || (action == "get" && field.nil?)
    return abort_with "Unknown config field '#{field}'. Supported: server"
  end

  case action
  when "get"
    $stdout.puts "server: #{Config.api_url}"
  when "set"
    return abort_with "Usage: localvault config set server URL" unless value
    unless value.match?(%r{\Ahttps?://\S+\z})
      return abort_with "Server must be an http(s) URL, e.g. https://vaulthost.example"
    end
    Config.api_url = value
    $stdout.puts "server set to #{value}"
    $stdout.puts "Note: tokens are per-server — run `localvault login YOUR_TOKEN` for this host."
  when "unset"
    data = Config.load
    data.delete("api_url")
    Config.save(data)
    $stdout.puts "server reset to #{Config.api_url}"
  else
    abort_with "Usage: localvault config [get|set|unset] server [URL]"
  end
end

#copy(key) ⇒ Object



1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
# File 'lib/localvault/cli.rb', line 1571

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



1342
1343
1344
1345
1346
1347
1348
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
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
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
# File 'lib/localvault/cli.rb', line 1342

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



383
384
385
386
387
388
389
390
391
# File 'lib/localvault/cli.rb', line 383

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



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

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

#doctorObject



1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
# File 'lib/localvault/cli.rb', line 1621

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

#envObject



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/localvault/cli.rb', line 422

def env
  vault = open_vault!
  unless PlaintextOutput.permitted?(purpose: "Export plaintext values")
    abort_with <<~MSG.strip
      refusing to print plaintext env exports: stdout is a captured stream, not an interactive terminal.
      Use process-scoped injection instead:
        localvault exec [--only KEYS|--map KEY=ENV_NAME|--profile aws] -- your-command
      A human at a terminal is asked to confirm; agents and CI must use injection.
    MSG
    return
  end
  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



466
467
468
469
470
471
472
473
# File 'lib/localvault/cli.rb', line 466

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



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/localvault/cli.rb', line 285

def get(key)
  vault = open_vault!
  lookup = KeyLookup.lookup(vault, key)

  if lookup.exact?
    print_plaintext(key, lookup.value)
  elsif lookup.single_match?
    print_plaintext(lookup.matches.first, 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



355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/localvault/cli.rb', line 355

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



1495
1496
1497
1498
1499
1500
1501
1502
1503
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
# File 'lib/localvault/cli.rb', line 1495

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



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/localvault/cli.rb', line 188

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



752
753
754
755
756
757
758
759
760
# File 'lib/localvault/cli.rb', line 752

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



828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# File 'lib/localvault/cli.rb', line 828

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



318
319
320
321
# File 'lib/localvault/cli.rb', line 318

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

#lock(name = nil) ⇒ Object



686
687
688
689
690
691
692
693
694
# File 'lib/localvault/cli.rb', line 686

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



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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
# File 'lib/localvault/cli.rb', line 852

def (token = nil)
  Config.api_url = options[:server] if options[:server]

  if options[:status]
    handle = Config.inventlist_handle
    if handle
      $stdout.puts "Logged in as @#{handle} (server: #{Config.api_url})"
    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 "Local vault encryption works without any account or server."
    $stdout.puts "Sync and team features need a sync server. LocalVault is server-agnostic —"
    $stdout.puts "pick either:"
    $stdout.puts
    $stdout.puts "  1. Your own host (any server implementing the 4-endpoint protocol):"
    $stdout.puts "       localvault config set server https://vaulthost.example"
    $stdout.puts "       localvault login YOUR_TOKEN"
    $stdout.puts "     (or one-shot: localvault login YOUR_TOKEN --server https://vaulthost.example)"
    $stdout.puts
    $stdout.puts "  2. InventList (free account):"
    $stdout.puts "       Sign up at https://inventlist.com, then get your token at"
    $stdout.puts "       https://inventlist.com/@YOUR_HANDLE/edit#developer"
    $stdout.puts
    $stdout.puts "Login generates your X25519 keypair and publishes the public key"
    $stdout.puts "automatically. To do it manually:"
    $stdout.puts "  localvault keys generate      # create keypair in ~/.localvault/keys/"
    $stdout.puts "  localvault keys publish       # upload public key so others can share with you"
    $stdout.puts "  localvault keys show          # print your public key"
    $stdout.puts
    $stdout.puts "Docs: https://kuickr.co/localvault/series"
    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} (server: #{Config.api_url})"
  $stdout.puts "Public key published to your profile."
  $stdout.puts
  $stdout.puts "Next: localvault sync push   # sync your vault to the server"
rescue ApiClient::ApiError => e
  if e.status == 401
    $stdout.puts "Invalid token for #{Config.api_url}."
    $stdout.puts "InventList tokens: https://inventlist.com/@YOUR_HANDLE/edit#developer"
  else
    $stdout.puts "Error connecting to #{Config.api_url}: #{e.message}"
  end
end

#logoutObject



954
955
956
957
958
959
960
961
962
963
964
# File 'lib/localvault/cli.rb', line 954

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



714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
# File 'lib/localvault/cli.rb', line 714

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



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

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



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
633
634
635
636
637
638
# File 'lib/localvault/cli.rb', line 606

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.



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

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 "Or use your own server: localvault config set server URL (free InventList account: https://inventlist.com)"
    $stderr.puts "Docs: https://kuickr.co/localvault/series"
    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



1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
# File 'lib/localvault/cli.rb', line 1545

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



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/localvault/cli.rb', line 641

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

#reveal(group = nil) ⇒ Object



545
546
547
548
549
550
# File 'lib/localvault/cli.rb', line 545

def reveal(group = nil)
  merged = options.merge("reveal" => true)
  merged["group"] = group if group && merged["project"].nil?
  self.options = merged
  show
end

#revoke(share_id) ⇒ Object



1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
# File 'lib/localvault/cli.rb', line 1080

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 = nil) ⇒ Object



240
241
242
243
244
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
# File 'lib/localvault/cli.rb', line 240

def set(key, value = nil)
  validate_secret_value_source!(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)
    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.message)
rescue Vault::InvalidKeyName => e
  raise GroupSaveError, :invalid if options[:group]
  abort_with e.message
  CommandStatus.error
rescue RuntimeError => e
  raise GroupSaveError, :collision if options[:group]
  abort_with e.message
  CommandStatus.error
end

#share(vault_name = nil) ⇒ Object



969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'lib/localvault/cli.rb', line 969

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



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 570

def show
  vault = open_vault!
  secrets = vault.all
  reveal = options[:reveal] && reveal_permitted?

  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: 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: 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: reveal)
  else
    render_table(secrets.sort.to_h, vault.name, reveal: reveal)
  end
end

#switch(vault_name = nil) ⇒ Object



1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
# File 'lib/localvault/cli.rb', line 1585

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



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/localvault/cli.rb', line 507

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



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/localvault/cli.rb', line 476

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.



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

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



1608
1609
1610
# File 'lib/localvault/cli.rb', line 1608

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