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

Defined Under Namespace

Modules: TeamHelpers Classes: Keys, Sync, Team

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


1266
1267
1268
# File 'lib/localvault/cli.rb', line 1266

def self.exit_on_failure?
  true
end

.help(shell, subcommand = false) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/localvault/cli.rb', line 11

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 get KEY            Retrieve a secret"
  shell.say "  localvault show               Display all secrets (masked by default)"
  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 ""
  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

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



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
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
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
915
916
917
918
919
920
921
# File 'lib/localvault/cli.rb', line 795

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



1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
# File 'lib/localvault/cli.rb', line 1225

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



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
1122
1123
1124
# File 'lib/localvault/cli.rb', line 996

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



208
209
210
211
212
213
214
215
216
# File 'lib/localvault/cli.rb', line 208

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



483
484
485
486
487
488
489
490
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
# File 'lib/localvault/cli.rb', line 483

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



237
238
239
240
241
# File 'lib/localvault/cli.rb', line 237

def env
  vault = open_vault!
  skip_warn = ->(k) { $stderr.puts "Warning: skipping unsafe key '#{k}'" }
  $stdout.puts vault.export_env(project: options[:project], on_skip: skip_warn)
end

#exec(*cmd) ⇒ Object



261
262
263
264
265
266
# File 'lib/localvault/cli.rb', line 261

def exec(*cmd)
  vault = open_vault!
  skip_warn = ->(k) { $stderr.puts "Warning: skipping unsafe key '#{k}'" }
  env_vars = vault.env_hash(project: options[:project], on_skip: skip_warn)
  Kernel.exec(env_vars, *cmd)
end

#get(key) ⇒ Object



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

def get(key)
  vault = open_vault!
  value = vault.get(key)

  if value.nil?
    # Fall back to case-insensitive substring match
    all_keys = vault.list
    matches  = all_keys.select { |k| k.downcase.include?(key.downcase) }

    if matches.size == 1
      value = vault.get(matches.first)
      $stdout.puts value
      return
    elsif matches.size > 1
      $stderr.puts "Error: Multiple keys match '#{key}'. Be more specific:"
      matches.sort.each { |k| $stderr.puts "  #{k}" }
      return
    else
      abort_with "Key '#{key}' not found in vault '#{vault.name}'"
      return
    end
  end

  $stdout.puts value
end

#import(file) ⇒ Object



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

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



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

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



472
473
474
475
476
477
478
479
480
# File 'lib/localvault/cli.rb', line 472

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



536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/localvault/cli.rb', line 536

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



190
191
192
193
# File 'lib/localvault/cli.rb', line 190

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

#lock(name = nil) ⇒ Object



444
445
446
447
448
449
450
451
452
# File 'lib/localvault/cli.rb', line 444

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



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/localvault/cli.rb', line 559

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



608
609
610
611
612
613
614
615
616
617
618
# File 'lib/localvault/cli.rb', line 608

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



455
456
457
458
# File 'lib/localvault/cli.rb', line 455

def mcp
  require "localvault/mcp/server"
  MCP::Server.new.start
end

#receiveObject



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
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
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/localvault/cli.rb', line 666

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



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/localvault/cli.rb', line 364

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.



933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/localvault/cli.rb', line 933

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



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
# File 'lib/localvault/cli.rb', line 1199

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



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/localvault/cli.rb', line 399

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



734
735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/localvault/cli.rb', line 734

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



127
128
129
130
131
# File 'lib/localvault/cli.rb', line 127

def set(key, value)
  vault = open_vault!
  vault.set(key, value)
  $stdout.puts "Set #{key} in vault '#{vault.name}'"
end

#share(vault_name = nil) ⇒ Object



623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/localvault/cli.rb', line 623

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



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/localvault/cli.rb', line 340

def show
  vault = open_vault!
  secrets = vault.all

  if secrets.empty?
    $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] || 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



1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/localvault/cli.rb', line 1239

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



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/localvault/cli.rb', line 300

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



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/localvault/cli.rb', line 269

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.



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

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



1262
1263
1264
# File 'lib/localvault/cli.rb', line 1262

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