Module: Lich::Common::Authentication::EntryStore

Defined in:
documented/common/authentication/entry_store.rb

Overview

Handles YAML-based state management for the Lich GUI login system Provides a more maintainable alternative to the Marshal-based state system Enhanced with password encryption support

Class Method Summary collapse

Class Method Details

.add_favorite(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset) ⇒ Boolean

Adds a character to the favorites list Marks the specified character as a favorite with proper ordering Optimized to preserve account ordering in YAML structure

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • frontend (String) (defaults to: nil) —

    Frontend identifier (optional for backward compatibility)

  • custom_launch (String, nil, Symbol) (defaults to: :__unset) —

    Exact custom launch command, or :__unset for legacy matching

Returns:

  • (Boolean) —

    True if operation was successful



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 'documented/common/authentication/entry_store.rb', line 528

def self.add_favorite(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
    yaml_data = migrate_to_favorites_format(yaml_data)

    # Find the character with frontend precision
    character = find_character(yaml_data, username, char_name, game_code, frontend, custom_launch)
    return false unless character

    # Don't add if already a favorite
    return true if character['is_favorite']

    # Mark as favorite and assign order
    character['is_favorite'] = true
    character['favorite_order'] = get_next_favorite_order(yaml_data)
    character['favorite_added'] = Time.now.to_s

    # Save updated data directly without conversion round-trip
    # This preserves the original YAML structure and account ordering
    content = generate_yaml_content(yaml_data)
    result = Lich::Common::GUI::Utilities.safe_file_operation(yaml_file, :write, content)

    result ? true : false
  rescue StandardError => e
    Lich.log "error: Error adding favorite: #{e.message}"
    false
  end
end

.change_encryption_mode(data_dir, new_mode, new_master_password = nil) ⇒ Boolean

Changes encryption mode for all accounts Re-encrypts all passwords from current mode to new mode Automatically retrieves old master password from keychain if leaving Enhanced mode Requires new_master_password if entering Enhanced mode (caller must check keychain first and prompt if needed) Restores the previous observable keychain value on handled failures before atomic file publication. File and keychain updates are not one transaction: process death or a failed keychain rollback still requires manual recovery.

Parameters:

  • data_dir (String) —

    Directory containing account data

  • new_mode (Symbol) —

    Target encryption mode (:plaintext, :standard, :enhanced)

  • new_master_password (String, nil) (defaults to: nil) —

    New master password (required if entering Enhanced)

Returns:

  • (Boolean) —

    true if successful, false on failure (errors logged to Lich.log)



360
361
362
363
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
397
398
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'documented/common/authentication/entry_store.rb', line 360

def self.change_encryption_mode(data_dir, new_mode, new_master_password = nil)
  yaml_file = yaml_file_path(data_dir)

  # Load YAML
  begin
    yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
  rescue StandardError => e
    Lich.log "error: Failed to load YAML for encryption mode change: #{e.message}"
    return false
  end

  current_mode = yaml_data['encryption_mode']&.to_sym || :plaintext

  # If already in target mode, return success
  if current_mode == new_mode
    Lich.log "info: Already in #{new_mode} encryption mode"
    return true
  end

  # Validate new_master_password if entering Enhanced mode
  if new_mode == :enhanced && new_master_password.nil?
    Lich.log "error: New master password required for Enhanced mode encryption"
    return false
  end

  keychain_touched = false
  previous_master_password = nil
  backup_file = "#{yaml_file}.bak"
  begin
    if current_mode == :enhanced || new_mode == :enhanced
      previous_master_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password(strict: true)
    end
    if current_mode == :enhanced && previous_master_password.nil?
      raise StandardError, "Master password not found in keychain for encryption mode change"
    end

    write_file_atomically(backup_file, File.binread(yaml_file))

    # Re-encrypt all accounts
    accounts = yaml_data['accounts'] || {}
    accounts.each do |, |
      # Decrypt with current mode
      plaintext = decrypt_password(
        ['password'],
        mode: current_mode,
        account_name: ,
        master_password: previous_master_password
      )

      if plaintext.nil?
        raise StandardError, "Failed to decrypt password for #{}"
      end

      # Encrypt with new mode
      encrypted = encrypt_password(
        plaintext,
        mode: new_mode,
        account_name: ,
        master_password: new_master_password
      )

      if encrypted.nil?
        raise StandardError, "Failed to encrypt password for #{}"
      end

      ['password'] = encrypted
    end

    # Update encryption_mode
    yaml_data['encryption_mode'] = new_mode.to_s

    # Handle Enhanced mode metadata
    if new_mode == :enhanced
      # Create validation test
      validation_test = Lich::Common::GUI::MasterPasswordManager.create_validation_test(new_master_password)
      raise StandardError, "Failed to create master password validation test" if validation_test.nil?
      yaml_data['master_password_validation_test'] = validation_test

      # A failed store may already have removed or changed the old value.
      keychain_touched = true
      unless Lich::Common::GUI::MasterPasswordManager.store_master_password(new_master_password)
        raise StandardError, "Failed to store master password in keychain"
      end
    elsif current_mode == :enhanced
      # Remove validation test and keychain when leaving Enhanced
      # Refuse the transition if deletion fails; success must not leave a
      # stale master password behind in the credential store.
      yaml_data.delete('master_password_validation_test')
      keychain_touched = true
      unless Lich::Common::GUI::MasterPasswordManager.delete_master_password
        raise StandardError, "Failed to delete master password from keychain"
      end
    end

    # Save YAML with headers
    write_yaml_file(yaml_file, yaml_data)
  rescue StandardError => e
    # Retain the owner-only backup for recovery after any failed transition.
    restore_master_password(previous_master_password) if keychain_touched
    Lich.log "error: Encryption mode change failed: #{e.class}: #{e.message}"
    return false
  end

  # Publication succeeded; a backup cleanup failure must not roll back the
  # keychain while the entry file already uses the new encryption mode.
  begin
    FileUtils.rm(backup_file) if File.exist?(backup_file)
  rescue StandardError => e
    Lich.log "warning: Could not remove encryption mode backup: #{e.class}: #{e.message}"
  end
  Lich.log "info: Encryption mode changed successfully: #{current_mode} -> #{new_mode}"
  true
end

.convert_legacy_to_yaml_format(entry_data, validation_test = nil) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Converts legacy format to YAML data structure Transforms legacy entry data into the YAML structure for storage Enhanced with case normalization to prevent duplicate accounts and ensure consistent formatting Preserves encryption_mode from entries and master_password_validation_test if provided

Parameters:

  • entry_data (Array) —

    Array of entry data in legacy format

  • validation_test (Hash, nil) (defaults to: nil) —

    Master password validation test to preserve (optional)

Returns:

  • (Hash) —

    YAML data structure



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
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
# File 'documented/common/authentication/entry_store.rb', line 781

def self.convert_legacy_to_yaml_format(entry_data, validation_test = nil)
  yaml_data = { 'accounts' => {} }

  # Preserve encryption_mode if present in entries
  encryption_mode = entry_data.first&.[](:encryption_mode) || :plaintext
  yaml_data['encryption_mode'] = encryption_mode.to_s

  # Preserve master_password_validation_test if provided
  yaml_data['master_password_validation_test'] = validation_test

  entry_data.each do |entry|
    # Normalize account name to UPCASE for consistent storage
    normalized_username = (entry[:user_id])

    # Initialize account if not exists, with password at account level
    yaml_data['accounts'][normalized_username] ||= {
      'password'   => entry[:password],
      'characters' => []
    }

    character_data = {
      'char_name'         => normalize_character_name(entry[:char_name]),
      'game_code'         => entry[:game_code],
      'game_name'         => entry[:game_name],
      'frontend'          => entry[:frontend],
      'custom_launch'     => entry[:custom_launch],
      'custom_launch_dir' => entry[:custom_launch_dir],
      'is_favorite'       => entry[:is_favorite] || false
    }

    # Add favorite metadata if character is a favorite
    if entry[:is_favorite]
      character_data['favorite_order'] = entry[:favorite_order]
      character_data['favorite_added'] = entry[:favorite_added] || Time.now.to_s
    end

    # Check for duplicate character using precision matching (account/character/game_code/frontend)
    # Including custom_launch allows multiple entries for the same character with different launch configurations
    existing_character = yaml_data['accounts'][normalized_username]['characters'].find do |char|
      char['char_name'] == character_data['char_name'] &&
        char['game_code'] == character_data['game_code'] &&
        char['frontend'] == character_data['frontend'] &&
        char['custom_launch'] == character_data['custom_launch']
    end

    # Only add if no exact match exists
    unless existing_character
      yaml_data['accounts'][normalized_username]['characters'] << character_data
    end
  end

  yaml_data
end

.convert_yaml_to_legacy_format(yaml_data) ⇒ Array

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Converts YAML data structure to legacy format Transforms the YAML structure into the format expected by existing code Maintains normalized case formatting from YAML storage Handles encrypted passwords transparently

Parameters:

  • yaml_data (Hash) —

    YAML data structure

Returns:

  • (Array) —

    Array of entry data in legacy format with decrypted passwords



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'documented/common/authentication/entry_store.rb', line 728

def self.convert_yaml_to_legacy_format(yaml_data)
  entries = []

  return entries unless yaml_data['accounts']

  encryption_mode = (yaml_data['encryption_mode'] || 'plaintext').to_sym

  yaml_data['accounts'].each do |username, |
    next unless ['characters']

    # Decrypt password if needed (with recovery for missing master password)
    password = if encryption_mode == :plaintext
                 ['password']
               else
                 decrypt_password_with_recovery(
                   ['password'],
                   mode: encryption_mode,
                   account_name: username,
                   validation_test: yaml_data['master_password_validation_test']
                 )
               end

    ['characters'].each do |character|
      entry = {
        user_id: username, # Already normalized to UPCASE in YAML
        password: password, # Decrypted password
        char_name: character['char_name'], # Already normalized to Title case in YAML
        game_code: character['game_code'],
        game_name: character['game_name'],
        frontend: character['frontend'],
        custom_launch: character['custom_launch'],
        custom_launch_dir: character['custom_launch_dir'],
        is_favorite: character['is_favorite'] || false,
        favorite_order: character['favorite_order'],
        encryption_mode: encryption_mode
      }

      entries << entry
    end
  end

  entries
end

.decrypt_password(encrypted_password, mode:, account_name: nil, master_password: nil) ⇒ String

Decrypts a password based on the current encryption mode

Parameters:

  • encrypted_password (String) —

    Encrypted password

  • mode (Symbol) —

    Encryption mode (:plaintext, :standard, :enhanced)

  • account_name (String, nil) (defaults to: nil) —

    Account name for :standard mode

  • master_password (String, nil) (defaults to: nil) —

    Master password for :enhanced mode

Returns:

  • (String) —

    Decrypted plaintext password



253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'documented/common/authentication/entry_store.rb', line 253

def self.decrypt_password(encrypted_password, mode:, account_name: nil, master_password: nil)
  return encrypted_password if mode == :plaintext || mode.to_sym == :plaintext

  # For enhanced mode: auto-retrieve from Keychain if not provided
  if mode.to_sym == :enhanced && master_password.nil?
    master_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password
    raise StandardError, "Master password not found in Keychain - cannot decrypt" if master_password.nil?
  end

  Lich::Common::GUI::PasswordCipher.decrypt(encrypted_password, mode: mode.to_sym, account_name: , master_password: master_password)
rescue StandardError => e
  Lich.log "error: decrypt_password failed - #{e.class}: #{e.message}"
  raise
end

.decrypt_password_with_recovery(encrypted_password, mode:, account_name: nil, master_password: nil, validation_test: nil) ⇒ String?

Decrypts password with recovery mechanism for missing master password If master password is missing from Keychain but validation test exists, prompts user to re-enter master password, validates it, and saves to Keychain

Parameters:

  • encrypted_password (String) —

    Encrypted password to decrypt

  • mode (Symbol) —

    Encryption mode (:plaintext, :standard, :enhanced)

  • account_name (String) (defaults to: nil) —

    Account name for :standard mode

  • master_password (String, nil) (defaults to: nil) —

    Master password if already known

  • validation_test (Hash, nil) (defaults to: nil) —

    Validation test hash from YAML (optional)

Returns:

  • (String, nil) —

    Decrypted password, or nil if the user cancels master password recovery and Lich begins shutting down

Raises:

  • (StandardError) —

    If decryption fails and cannot be recovered



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'documented/common/authentication/entry_store.rb', line 280

def self.decrypt_password_with_recovery(encrypted_password, mode:, account_name: nil, master_password: nil, validation_test: nil)
  # Try normal decryption first
  return decrypt_password(encrypted_password, mode: mode, account_name: , master_password: master_password)
rescue StandardError => e
  # Only attempt recovery for enhanced mode with missing master password
  if mode.to_sym == :enhanced && e.message.include?("Master password not found") && validation_test && !validation_test.empty?
    Lich.log "info: Master password missing from Keychain, attempting recovery via user prompt"

    # Show appropriate dialog based on context - use data access for conversion, recovery for actual recovery
    recovery_result = Lich::Common::GUI::MasterPasswordPromptUI.show_password_for_data_access(validation_test)

    if recovery_result.nil? || recovery_result[:password].nil?
      Lich.log "info: User cancelled master password recovery"
      Lich::Common.quit_gtk_main_loop
      return nil
    end

    recovered_password = recovery_result[:password]
    continue_session = recovery_result[:continue_session]

    # Password was validated by the UI layer, proceed with recovery
    Lich.log "info: Master password recovered and validated, storing to Keychain"

    # Save recovered password to Keychain for future use
    unless Lich::Common::GUI::MasterPasswordManager.store_master_password(recovered_password)
      Lich.log "warning: Failed to store recovered master password to Keychain"
      # Continue anyway - decryption will still work with in-memory password
    end

    # Handle session continuation decision
    if !continue_session
      Lich.log "info: User chose to close application after password recovery"
      # Exit the application gracefully
      Lich::Common.quit_gtk_main_loop
    end

    # Retry decryption with recovered password
    return decrypt_password(encrypted_password, mode: mode, account_name: , master_password: recovered_password)
  else
    # Re-raise if not recoverable
    raise
  end
end

.encrypt_all_passwords(yaml_data, mode, master_password: nil) ⇒ Hash

Encrypts all passwords in yaml_data structure

Parameters:

  • yaml_data (Hash) —

    YAML data structure

  • mode (Symbol) —

    Encryption mode

  • master_password (String, nil) (defaults to: nil) —

    Master password if using :enhanced mode

Returns:

  • (Hash) —

    YAML data with encrypted passwords



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'documented/common/authentication/entry_store.rb', line 330

def self.encrypt_all_passwords(yaml_data, mode, master_password: nil)
  return yaml_data if mode == :plaintext

  yaml_data['accounts'].each do |, |
    next unless ['password']

    # Encrypt password based on mode
    ['password'] = encrypt_password(
      ['password'],
      mode: mode,
      account_name: ,
      master_password: master_password
    )
  end

  yaml_data
end

.encrypt_password(password, mode:, account_name: nil, master_password: nil) ⇒ String

Encrypts a password based on the current encryption mode

Parameters:

  • password (String) —

    Plaintext password

  • mode (Symbol) —

    Encryption mode (:plaintext, :standard, :enhanced)

  • account_name (String, nil) (defaults to: nil) —

    Account name for :standard mode

  • master_password (String, nil) (defaults to: nil) —

    Master password for :enhanced mode

Returns:

  • (String) —

    Encrypted password or plaintext if mode is :plaintext



237
238
239
240
241
242
243
244
# File 'documented/common/authentication/entry_store.rb', line 237

def self.encrypt_password(password, mode:, account_name: nil, master_password: nil)
  return password if mode == :plaintext || mode.to_sym == :plaintext

  Lich::Common::GUI::PasswordCipher.encrypt(password, mode: mode.to_sym, account_name: , master_password: master_password)
rescue StandardError => e
  Lich.log "error: encrypt_password failed - #{e.class}: #{e.message}"
  raise
end

.ensure_master_password_exists ⇒ Hash, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Ensures master password exists for master_password mode conversions Shows UI prompt to user if not found in Keychain Creates validation test and stores in Keychain

Returns:

  • (Hash, String, nil) —

    Hash with validation_test if new, password string if existing, nil if cancelled



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
# File 'documented/common/authentication/entry_store.rb', line 1156

def self.ensure_master_password_exists
  # Check if master password already in Keychain
  existing = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password
  return existing if !existing.nil? && !existing.empty?

  # Show UI prompt to CREATE master password
  master_password = Lich::Common::GUI::MasterPasswordPrompt.show_create_master_password_dialog

  if master_password.nil?
    Lich.log "info: User declined to create master password"
    return nil
  end

  # Create validation test (expensive 100k iterations, one-time)
  validation_test = Lich::Common::GUI::MasterPasswordManager.create_validation_test(master_password)

  if validation_test.nil?
    Lich.log "error: Failed to create validation test"
    return nil
  end

  # Store in Keychain
  stored = Lich::Common::GUI::MasterPasswordManager.store_master_password(master_password)

  unless stored
    Lich.log "error: Failed to store master password in Keychain"
    return nil
  end

  Lich.log "info: Master password created and stored in Keychain"
  # Return both password and validation test for YAML storage
  { password: master_password, validation_test: validation_test }
end

.find_character(yaml_data, username, char_name, game_code, frontend = nil, custom_launch = :__unset) ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Finds a character in the YAML data with precise matching Prioritizes exact frontend matches for newly added characters

Parameters:

  • yaml_data (Hash) —

    YAML data structure

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • frontend (String, nil) (defaults to: nil) —

    Frontend identifier

  • custom_launch (String, nil, Symbol) (defaults to: :__unset) —

    Exact custom launch command, or :__unset for legacy matching

Returns:

  • (Hash, nil) —

    Character hash or nil if not found



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
# File 'documented/common/authentication/entry_store.rb', line 897

def self.find_character(yaml_data, username, char_name, game_code, frontend = nil, custom_launch = :__unset)
  return nil unless yaml_data['accounts'] && yaml_data['accounts'][username]
   = yaml_data['accounts'][username]
  return nil unless ['characters']

  # If frontend is specified, find exact match first
  if frontend
    exact_match = ['characters'].find do |character|
      character['char_name'] == char_name &&
        character['game_code'] == game_code &&
        character['frontend'] == frontend &&
        (custom_launch == :__unset || character['custom_launch'].to_s.strip == custom_launch.to_s.strip)
    end
    return exact_match if exact_match
  end

  # Fallback to basic matching only if no exact match found and frontend is nil
  if frontend.nil?
    ['characters'].find do |character|
      character['char_name'] == char_name &&
        character['game_code'] == game_code &&
        (custom_launch == :__unset || character['custom_launch'].to_s.strip == custom_launch.to_s.strip)
    end
  else
    # If frontend was specified but no exact match found, return nil
    nil
  end
end

.find_entry_in_legacy_format(entry_data, username, char_name, game_code, frontend = nil, custom_launch = :__unset) ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Finds an entry in legacy format array using the same matching logic as find_character Searches for an entry based on key identifying fields rather than exact hash equality This method reuses the proven matching logic from find_character for consistency

Parameters:

  • entry_data (Array) —

    Array of entry data in legacy format

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • frontend (String) (defaults to: nil) —

    Frontend identifier (optional for backward compatibility)

  • custom_launch (String, nil, Symbol) (defaults to: :__unset) —

    Exact custom launch command, or :__unset for legacy matching

Returns:

  • (Hash, nil) —

    Entry hash if found, nil otherwise



959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
# File 'documented/common/authentication/entry_store.rb', line 959

def self.find_entry_in_legacy_format(entry_data, username, char_name, game_code, frontend = nil, custom_launch = :__unset)
  entry_data.find do |entry|
    # Match on username first
    next unless entry[:user_id] == username

    # Apply same matching logic as find_character
    matches_basic = entry[:char_name] == char_name && entry[:game_code] == game_code

    matches_custom_launch = custom_launch == :__unset || entry[:custom_launch].to_s.strip == custom_launch.to_s.strip

    if frontend.nil?
      # Backward compatibility: if no frontend specified, match any frontend
      matches_basic && matches_custom_launch
    else
      # Frontend precision: must match exact frontend
      matches_basic && entry[:frontend] == frontend && matches_custom_launch
    end
  end
end

.generate_yaml_content(yaml_data) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Generates YAML file content with standard header and dumped data Reduces code duplication by providing a common method for formatting YAML output

Parameters:

  • yaml_data (Hash) —

    YAML data structure to dump

Returns:

  • (String) —

    Complete YAML file content with header



1068
1069
1070
1071
1072
1073
1074
1075
1076
# File 'documented/common/authentication/entry_store.rb', line 1068

def self.generate_yaml_content(yaml_data)
  # Prepare YAML with password preservation (clones to avoid mutation)
  prepared_yaml = prepare_yaml_for_serialization(yaml_data)

  content = "# Lich 5 Login Entries - YAML Format\n" \
          + "# Generated: #{Time.now}\n" \
          + YAML.dump(prepared_yaml, permitted_classes: [Symbol])
  return content
end

.get_existing_master_password_for_migration ⇒ Hash?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Gets existing master password and creates validation test for migration scenarios Used when converting DAT to YAML and a master password already exists in keychain This handles the case: no YAML, DAT exists, master password in keychain

Returns:

  • (Hash, nil) —

    Hash with validation_test or nil if error



1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
# File 'documented/common/authentication/entry_store.rb', line 1196

def self.get_existing_master_password_for_migration
  # Retrieve existing master password from keychain
  existing_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password

  if existing_password.nil? || existing_password.empty?
    Lich.log "info: No existing master password found in keychain - user should create one"
    return nil
  end

  Lich.log "info: Found existing master password in keychain - creating validation test for migration"

  # Create a NEW validation test with the existing password
  # This is needed because we don't have the old validation test in YAML yet
  validation_test = Lich::Common::GUI::MasterPasswordManager.create_validation_test(existing_password)

  if validation_test.nil?
    Lich.log "error: Failed to create validation test for existing master password"
    return nil
  end

  Lich.log "info: Validation test created for existing master password"
  { password: existing_password, validation_test: validation_test }
end

.get_favorites(data_dir) ⇒ Array

Gets all favorite characters across all accounts Returns an array of favorite characters sorted by favorite order

Parameters:

  • data_dir (String) —

    Directory containing entry data

Returns:

  • (Array) —

    Array of favorite character data in legacy format



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
664
665
666
667
668
669
670
# File 'documented/common/authentication/entry_store.rb', line 635

def self.get_favorites(data_dir)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
    yaml_data = migrate_to_favorites_format(yaml_data)

    favorites = []

    yaml_data['accounts'].each do |username, |
      next unless ['characters']

      ['characters'].each do |character|
        if character['is_favorite']
          favorites << {
            user_id: username,
            char_name: character['char_name'],
            game_code: character['game_code'],
            game_name: character['game_name'],
            frontend: character['frontend'],
            custom_launch: character['custom_launch'],
            favorite_order: character['favorite_order'] || 999,
            favorite_added: character['favorite_added']
          }
        end
      end
    end

    # Sort by favorite order
    favorites.sort_by { |fav| fav[:favorite_order] }
  rescue StandardError => e
    Lich.log "error: Error getting favorites: #{e.message}"
    []
  end
end

.get_next_favorite_order(yaml_data) ⇒ Integer

Gets the next available favorite order number Finds the highest current favorite order and returns the next number

Parameters:

  • yaml_data (Hash) —

    YAML data structure

Returns:

  • (Integer) —

    Next available favorite order number



931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
# File 'documented/common/authentication/entry_store.rb', line 931

def self.get_next_favorite_order(yaml_data)
  max_order = 0

  yaml_data['accounts'].each do |_username, |
    next unless ['characters']

    ['characters'].each do |character|
      if character['is_favorite'] && character['favorite_order']
        max_order = [max_order, character['favorite_order']].max
      end
    end
  end

  max_order + 1
end

.is_favorite?(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset) ⇒ Boolean

Checks if a character is marked as a favorite Returns true if the specified character is in the favorites list

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • frontend (String) (defaults to: nil) —

    Frontend identifier (optional for backward compatibility)

  • custom_launch (String, nil, Symbol) (defaults to: :__unset) —

    Exact custom launch command, or :__unset for legacy matching

Returns:

  • (Boolean) —

    True if character is a favorite



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'documented/common/authentication/entry_store.rb', line 614

def self.is_favorite?(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
    yaml_data = migrate_to_favorites_format(yaml_data)

    character = find_character(yaml_data, username, char_name, game_code, frontend, custom_launch)
    character && character['is_favorite'] == true
  rescue StandardError => e
    Lich.log "error: Error checking favorite status: #{e.message}"
    false
  end
end

.load_saved_entries(data_dir, autosort_state) ⇒ Array

Loads saved entry data from YAML file Reads and deserializes entry data from the entry.yaml file, with fallback to entry.dat Enhanced to support favorites functionality and encryption with backward compatibility

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • autosort_state (Boolean) —

    Whether to use auto-sorting

Returns:

  • (Array) —

    Array of saved login entries in the legacy format with favorites info



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
# File 'documented/common/authentication/entry_store.rb', line 46

def self.load_saved_entries(data_dir, autosort_state)
  # Guard against nil data_dir
  return [] if data_dir.nil?

  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  dat_file = File.join(data_dir, "entry.dat")

  if File.exist?(yaml_file)
    # Load from YAML format
    begin
      yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])

      # Migrate data structure if needed to support favorites and encryption
      yaml_data = migrate_to_favorites_format(yaml_data)
      yaml_data = migrate_to_encryption_format(yaml_data)

      entries = convert_yaml_to_legacy_format(yaml_data)

      # Apply sorting with favorites priority if enabled
      entries = sort_entries_with_favorites(entries, autosort_state)

      entries
    rescue StandardError => e
      Lich.log "error: Error loading YAML entry file: #{e.message}"
      []
    end
  elsif File.exist?(dat_file)
    # Fall back to legacy format if YAML doesn't exist
    Lich.log "info: YAML entry file not found, falling back to legacy format"
    Lich::Common::GUI::State.load_saved_entries(data_dir, autosort_state)
  else
    # No entry file exists
    []
  end
end

.migrate_from_legacy(data_dir, encryption_mode: :plaintext) ⇒ Boolean

Migrates from legacy Marshal format to YAML format with encryption support Converts entry.dat to entry.yaml format for improved maintainability

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • encryption_mode (Symbol) (defaults to: :plaintext) —

    Encryption mode (:plaintext, :standard, :enhanced)

Returns:

  • (Boolean) —

    True if migration was successful



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'documented/common/authentication/entry_store.rb', line 154

def self.migrate_from_legacy(data_dir, encryption_mode: :plaintext)
  dat_file = File.join(data_dir, "entry.dat")
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Skip if YAML file already exists or DAT file doesn't exist
  return false unless File.exist?(dat_file)
  return false if File.exist?(yaml_file)

  # ====================================================================
  # Handle master_password mode - check for existing or create new
  # ====================================================================
  master_password = nil
  validation_test = nil
  if encryption_mode == :enhanced
    # First check if master password already exists in keychain
    result = get_existing_master_password_for_migration

    # If no existing password, prompt user to create one
    if result.nil?
      result = ensure_master_password_exists
    end

    if result.nil?
      Lich.log "error: Master password not available for migration"
      return false
    end

    # Handle both new (Hash) and existing (String) password returns
    if result.is_a?(Hash)
      master_password = result[:password]
      validation_test = result[:validation_test]
    else
      master_password = result
    end
  end

  # Load legacy data
  legacy_entries = Lich::Common::GUI::State.load_saved_entries(data_dir, false)

  # Add encryption_mode to entries
  legacy_entries.each do |entry|
    entry[:encryption_mode] = encryption_mode
  end

  # Encrypt passwords if not plaintext mode
  if encryption_mode != :plaintext
    legacy_entries.each do |entry|
      entry[:password] = encrypt_password(
        entry[:password],
        mode: encryption_mode,
        account_name: entry[:user_id],
        master_password: master_password # NEW: Pass master password
      )
    end
  end

  # Use save_entries to maintain test compatibility
  save_entries(data_dir, legacy_entries)

  # Save validation test to YAML if it was created
  if validation_test && encryption_mode == :enhanced
    yaml_file = yaml_file_path(data_dir)
    if File.exist?(yaml_file)
      yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
      yaml_data['master_password_validation_test'] = validation_test
      write_yaml_file(yaml_file, yaml_data)
    end
  end

  # Log conversion summary
   = legacy_entries.map { |entry| entry[:user_id] }.uniq.sort.join(', ')
  Lich.log "info: Migration complete - Encryption mode: #{encryption_mode.upcase}, Converted accounts: #{}"

  true
end

.migrate_to_encryption_format(yaml_data) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Migrates YAML data to support encryption format Adds encryption_mode field if not present

Parameters:

  • yaml_data (Hash) —

    YAML data structure

Returns:

  • (Hash) —

    YAML data structure with encryption support



506
507
508
509
510
511
512
513
514
515
# File 'documented/common/authentication/entry_store.rb', line 506

def self.migrate_to_encryption_format(yaml_data)
  return yaml_data unless yaml_data.is_a?(Hash)

  # Add encryption_mode if not present (defaults to plaintext for backward compatibility)
  yaml_data['encryption_mode'] ||= 'plaintext'
  # Add validation test field if master_password mode (for Phase 2)
  yaml_data['master_password_validation_test'] ||= nil

  yaml_data
end

.migrate_to_favorites_format(yaml_data) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Migrates YAML data to support favorites format Adds favorites fields to existing character records if not present

Parameters:

  • yaml_data (Hash) —

    YAML data structure

Returns:

  • (Hash) —

    YAML data structure with favorites support



870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'documented/common/authentication/entry_store.rb', line 870

def self.migrate_to_favorites_format(yaml_data)
  return yaml_data unless yaml_data.is_a?(Hash) && yaml_data['accounts']

  yaml_data['accounts'].each do |_username, |
    next unless ['characters'].is_a?(Array)

    ['characters'].each do |character|
      # Add favorites fields if not present
      character['is_favorite'] ||= false
      # Don't add favorite_order or favorite_added unless character is actually a favorite
    end
  end

  yaml_data
end

.normalize_account_name(name) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Normalizes account names to UPCASE for consistent storage and comparison Prevents duplicate accounts due to case variations

Parameters:

  • name (String) —

    Raw account name

Returns:

  • (String) —

    Normalized account name in UPCASE



1042
1043
1044
1045
# File 'documented/common/authentication/entry_store.rb', line 1042

def self.(name)
  return '' if name.nil?
  name.to_s.strip.upcase
end

.normalize_character_name(name) ⇒ String

Normalizes character names to Title case per word, stripping and collapsing whitespace. The single normalization used for every char_name write and comparison (EntryStore, AccountManager, CLIPassword, manual login), so a name always compares equal to the form it was stored in. Comparisons must normalize both sides: entry.yaml can hold names written in older forms.

Per word rather than String#capitalize, which downcases everything after the first character and so turns "Alpha Beta" into "Alpha beta".

Parameters:

  • name (String, nil) —

    Raw character name

Returns:

  • (String) —

    Normalized character name, '' for nil or blank input



1058
1059
1060
# File 'documented/common/authentication/entry_store.rb', line 1058

def self.normalize_character_name(name)
  name.to_s.strip.split.map(&:capitalize).join(' ')
end

.prepare_yaml_for_serialization(yaml_data) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Prepares YAML data for serialization with password preservation Ensures encrypted passwords are serialized as quoted strings to prevent YAML multiline formatting Clones the data to avoid mutating the caller's object Ensures required top-level fields exist (encryption_mode, master_password_validation_test)

Parameters:

  • yaml_data (Hash) —

    YAML data structure to prepare for serialization

Returns:

  • (Hash) —

    Cloned yaml_data with passwords forced to plain strings and required fields set



1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
# File 'documented/common/authentication/entry_store.rb', line 1014

def self.prepare_yaml_for_serialization(yaml_data)
  # Clone to avoid mutating caller's object
  prepared_data = Marshal.load(Marshal.dump(yaml_data))

  # Ensure top-level fields are explicitly present (defensive programming)
  prepared_data['encryption_mode'] ||= 'plaintext'
  prepared_data['master_password_validation_test'] ||= nil

  # Preserve encrypted passwords by ensuring they are serialized as quoted strings
  # This prevents YAML from using multiline formatting (|, >) which breaks Base64 decoding
  if prepared_data['accounts']
    prepared_data['accounts'].each do |_username, |
      if .is_a?(Hash) && ['password']
        # Force password to be treated as a plain scalar string
        ['password'] = ['password'].to_s
      end
    end
  end

  prepared_data
end

.remove_favorite(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset) ⇒ Boolean

Removes a character from the favorites list Unmarks the specified character as a favorite and reorders remaining favorites

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • frontend (String) (defaults to: nil) —

    Frontend identifier (optional for backward compatibility)

  • custom_launch (String, nil, Symbol) (defaults to: :__unset) —

    Exact custom launch command, or :__unset for legacy matching

Returns:

  • (Boolean) —

    True if operation was successful



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
# File 'documented/common/authentication/entry_store.rb', line 570

def self.remove_favorite(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
    yaml_data = migrate_to_favorites_format(yaml_data)

    # Find the character with frontend precision
    character = find_character(yaml_data, username, char_name, game_code, frontend, custom_launch)
    return false unless character

    # Don't remove if not a favorite
    return true unless character['is_favorite']

    # Remove favorite status
    character['is_favorite'] = false
    character.delete('favorite_order')
    character.delete('favorite_added')

    # Reorder remaining favorites
    reorder_all_favorites(yaml_data)

    # Save updated data
    content = generate_yaml_content(yaml_data)
    result = Lich::Common::GUI::Utilities.safe_file_operation(yaml_file, :write, content)

    result ? true : false
  rescue StandardError => e
    Lich.log "error: Error removing favorite: #{e.message}"
    false
  end
end

.reorder_all_favorites(yaml_data) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Reorders all favorites to have consecutive order numbers Ensures favorite_order values are consecutive starting from 1

Parameters:

  • yaml_data (Hash) —

    YAML data structure



985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
# File 'documented/common/authentication/entry_store.rb', line 985

def self.reorder_all_favorites(yaml_data)
  # Collect all favorites
  all_favorites = []

  yaml_data['accounts'].each do |_username, |
    next unless ['characters']

    ['characters'].each do |character|
      if character['is_favorite']
        all_favorites << character
      end
    end
  end

  # Sort by current order and reassign consecutive numbers
  all_favorites.sort_by! { |char| char['favorite_order'] || 999 }
  all_favorites.each_with_index do |character, index|
    character['favorite_order'] = index + 1
  end
end

.reorder_favorites(data_dir, ordered_favorites) ⇒ Boolean

Reorders favorites based on provided character list Updates the favorite order for all favorites based on new ordering

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • ordered_favorites (Array) —

    Array of hashes with username, char_name, game_code, frontend

Returns:

  • (Boolean) —

    True if operation was successful



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
# File 'documented/common/authentication/entry_store.rb', line 678

def self.reorder_favorites(data_dir, ordered_favorites)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
    yaml_data = migrate_to_favorites_format(yaml_data)

    # Update favorite order for each character in the provided order
    ordered_favorites.each_with_index do |favorite_info, index|
      custom_launch = if favorite_info.key?(:custom_launch)
                        favorite_info[:custom_launch]
                      elsif favorite_info.key?('custom_launch')
                        favorite_info['custom_launch']
                      else
                        :__unset
                      end
      character = find_character(
        yaml_data,
        favorite_info[:username] || favorite_info['username'],
        favorite_info[:char_name] || favorite_info['char_name'],
        favorite_info[:game_code] || favorite_info['game_code'],
        favorite_info[:frontend] || favorite_info['frontend'],
        custom_launch
      )

      if character && character['is_favorite']
        character['favorite_order'] = index + 1
      end
    end

    # Save updated data
    content = generate_yaml_content(yaml_data)
    result = Lich::Common::GUI::Utilities.safe_file_operation(yaml_file, :write, content)

    result ? true : false
  rescue StandardError => e
    Lich.log "error: Error reordering favorites: #{e.message}"
    false
  end
end

.save_entries(data_dir, entry_data) ⇒ Boolean

Saves entry data to YAML file Converts and serializes entry data to the entry.yaml file with encryption support Preserves master_password_validation_test from existing YAML during round-trip conversion Encrypts passwords based on the file's encryption_mode before writing Publishes the backup and replacement through protected temporary files. A failed publication leaves the previous entry file unchanged.

Parameters:

  • data_dir (String) —

    Directory to save entry data

  • entry_data (Array) —

    Array of entry data in legacy format

Returns:

  • (Boolean) —

    True if save was successful



92
93
94
95
96
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
# File 'documented/common/authentication/entry_store.rb', line 92

def self.save_entries(data_dir, entry_data)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Preserve validation test and encryption_mode from existing YAML if it exists
  original_validation_test = nil
  original_encryption_mode = :plaintext
  if File.exist?(yaml_file)
    begin
      original_data = YAML.safe_load_file(yaml_file, permitted_classes: [Symbol])
      if original_data.is_a?(Hash)
        original_validation_test = original_data['master_password_validation_test']
        original_encryption_mode = (original_data['encryption_mode'] || 'plaintext').to_sym
      end
    rescue StandardError => e
      Lich.log "warning: Could not load existing YAML to preserve validation test: #{e.message}"
    end
  end

  # Convert legacy format to YAML structure, passing validation test to preserve it
  yaml_data = convert_legacy_to_yaml_format(entry_data, original_validation_test)

  # Encrypt passwords based on original file's encryption mode
  # entry_data contains plaintext passwords (decrypted on load or from user input)
  if original_encryption_mode != :plaintext
    master_password = nil
    if original_encryption_mode == :enhanced
      master_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password
      if master_password.nil?
        Lich.log "error: Enhanced mode enabled but master password not found in Keychain"
        return false
      end
    end

    yaml_data['accounts'].each do |, |
      next unless ['password']

      ['password'] = encrypt_password(
        ['password'],
        mode: original_encryption_mode,
        account_name: ,
        master_password: master_password
      )
    end
  end

  # Write YAML data to file with secure permissions
  begin
    write_file_atomically("#{yaml_file}.bak", File.binread(yaml_file)) if File.exist?(yaml_file)
    write_yaml_file(yaml_file, yaml_data)
    true
  rescue StandardError => e
    Lich.log "error: Error saving YAML entry file: #{e.message}"
    false
  end
end

.sort_entries_with_favorites(entries, autosort_state) ⇒ Array

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Sorts entries with favorites priority based on autosort setting When autosort is enabled, favorites are placed first and all entries are sorted When autosort is disabled, original order is preserved without reordering

Parameters:

  • entries (Array) —

    Array of entry data

  • autosort_state (Boolean) —

    Whether to use auto-sorting

Returns:

  • (Array) —

    Sorted array of entries (if autosort enabled) or original order (if disabled)



843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
# File 'documented/common/authentication/entry_store.rb', line 843

def self.sort_entries_with_favorites(entries, autosort_state)
  # If autosort is disabled, preserve original order without any reordering
  return entries unless autosort_state

  # Autosort enabled: apply favorites-first sorting
  # Separate favorites and non-favorites
  favorites = entries.select { |entry| entry[:is_favorite] }
  non_favorites = entries.reject { |entry| entry[:is_favorite] }

  # Sort favorites by favorite_order
  favorites.sort_by! { |entry| entry[:favorite_order] || 999 }

  # Sort non-favorites by account name (upcase), game name, and character name
  sorted_non_favorites = non_favorites.sort do |a, b|
    [a[:user_id].upcase, a[:game_name], a[:char_name]] <=> [b[:user_id].upcase, b[:game_name], b[:char_name]]
  end

  # Return favorites first, then non-favorites
  favorites + sorted_non_favorites
end

.write_yaml_file(yaml_file, yaml_data, backup: false) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Writes YAML data to file with standard headers and secure permissions Handles preparation and formatting of YAML data for all save operations Serializes before publication so serialization errors cannot truncate data.

Parameters:

  • yaml_file (String) —

    Path to YAML file to write

  • yaml_data (Hash) —

    YAML data structure to save

  • backup (Boolean) (defaults to: false) —

    preserve the previous bytes in an owner-only .bak



1087
1088
1089
1090
1091
# File 'documented/common/authentication/entry_store.rb', line 1087

def self.write_yaml_file(yaml_file, yaml_data, backup: false)
  content = generate_yaml_content(yaml_data)
  write_file_atomically("#{yaml_file}.bak", File.binread(yaml_file)) if backup && File.exist?(yaml_file)
  write_file_atomically(yaml_file, content)
end

.write_yaml_with_master_password(yaml_file, yaml_data, password) ⇒ void

This method returns an undefined value.

Publishes prepared credentials with a new keychain password. On handled failure, restores the previously observed keychain value; file publication is atomic, but process death between resources is not recoverable here.

Parameters:

  • yaml_file (String) —

    credential destination

  • yaml_data (Hash) —

    already re-encrypted credentials and validation data

  • password (String) —

    new master password

Raises:

  • (StandardError) —

    on publication failure or incomplete rollback



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# File 'documented/common/authentication/entry_store.rb', line 1102

def self.write_yaml_with_master_password(yaml_file, yaml_data, password)
  content = generate_yaml_content(yaml_data)
  manager = Lich::Common::GUI::MasterPasswordManager
  previous_password = manager.retrieve_master_password(strict: true)
  begin
    unless manager.store_master_password(password)
      raise StandardError, "Failed to update keychain"
    end
    write_file_atomically(yaml_file, content)
  rescue StandardError
    unless restore_master_password(previous_password)
      raise StandardError, "Credential update failed; manual keychain recovery is required"
    end
    raise
  end
end

.yaml_file_path(data_dir) ⇒ String

Generates the full path to the entry.yaml file.

Parameters:

  • data_dir (String) —

    The directory where the entry.yaml file is located.

Returns:

  • (String) —

    The full path to the entry.yaml file.



35
36
37
# File 'documented/common/authentication/entry_store.rb', line 35

def self.yaml_file_path(data_dir)
  File.join(data_dir, "entry.yaml")
end