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



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'documented/common/authentication/entry_store.rb', line 499

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)

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)



347
348
349
350
351
352
353
354
355
356
357
358
359
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
# File 'documented/common/authentication/entry_store.rb', line 347

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

  # Determine old_master_password
  old_master_password = nil
  if current_mode == :enhanced
    # Auto-retrieve from keychain when leaving Enhanced
    old_master_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password
    if old_master_password.nil?
      Lich.log "error: Master password not found in keychain for encryption mode change"
      return false
    end
  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

  # Create backup
  backup_file = "#{yaml_file}.bak"
  begin
    FileUtils.cp(yaml_file, backup_file)
    Lich.log "info: Backup created for encryption mode change: #{backup_file}"
  rescue StandardError => e
    Lich.log "error: Failed to create backup: #{e.message}"
    return false
  end

  begin
    # 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: old_master_password
      )

      if plaintext.nil?
        Lich.log "error: Failed to decrypt password for #{}"
        return restore_backup_and_return_false(backup_file, yaml_file)
      end

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

      if encrypted.nil?
        Lich.log "error: Failed to encrypt password for #{}"
        return restore_backup_and_return_false(backup_file, yaml_file)
      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)
      yaml_data['master_password_validation_test'] = validation_test

      # Store in keychain
      unless Lich::Common::GUI::MasterPasswordManager.store_master_password(new_master_password)
        Lich.log "error: Failed to store master password in keychain"
        return restore_backup_and_return_false(backup_file, yaml_file)
      end
    elsif current_mode == :enhanced
      # Remove validation test and keychain when leaving Enhanced
      yaml_data.delete('master_password_validation_test')
      Lich::Common::GUI::MasterPasswordManager.delete_master_password
    end

    # Save YAML with headers
    write_yaml_file(yaml_file, yaml_data)

    # Clean up backup on success
    FileUtils.rm(backup_file) if File.exist?(backup_file)

    Lich.log "info: Encryption mode changed successfully: #{current_mode} -> #{new_mode}"
    true
  rescue StandardError => e
    Lich.log "error: Encryption mode change failed: #{e.class}: #{e.message}"
    restore_backup_and_return_false(backup_file, yaml_file)
  end
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



752
753
754
755
756
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'documented/common/authentication/entry_store.rb', line 752

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



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
732
733
734
735
736
737
738
739
740
741
# File 'documented/common/authentication/entry_store.rb', line 699

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



243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'documented/common/authentication/entry_store.rb', line 243

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



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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'documented/common/authentication/entry_store.rb', line 270

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



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'documented/common/authentication/entry_store.rb', line 320

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



227
228
229
230
231
232
233
234
# File 'documented/common/authentication/entry_store.rb', line 227

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_existsHash, ...

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



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

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



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

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



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

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



1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'documented/common/authentication/entry_store.rb', line 1035

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_migrationHash?

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



1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
# File 'documented/common/authentication/entry_store.rb', line 1108

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



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'documented/common/authentication/entry_store.rb', line 606

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



902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
# File 'documented/common/authentication/entry_store.rb', line 902

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



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'documented/common/authentication/entry_store.rb', line 585

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



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

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



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
# File 'documented/common/authentication/entry_store.rb', line 144

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



477
478
479
480
481
482
483
484
485
486
# File 'documented/common/authentication/entry_store.rb', line 477

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



841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# File 'documented/common/authentication/entry_store.rb', line 841

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



1013
1014
1015
1016
# File 'documented/common/authentication/entry_store.rb', line 1013

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

.normalize_character_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 character names to Title case (first letter capitalized) Ensures consistent character name formatting across the application

Parameters:

  • name (String)

    Raw character name

Returns:

  • (String)

    Normalized character name in Title case



1024
1025
1026
1027
# File 'documented/common/authentication/entry_store.rb', line 1024

def self.normalize_character_name(name)
  return '' if name.nil?
  name.to_s.strip.capitalize
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



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

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



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'documented/common/authentication/entry_store.rb', line 541

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



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

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



649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# File 'documented/common/authentication/entry_store.rb', line 649

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

.restore_backup_and_return_false(backup_file, yaml_file) ⇒ Object

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.

Restores backup and returns false



462
463
464
465
466
467
468
469
# File 'documented/common/authentication/entry_store.rb', line 462

def self.restore_backup_and_return_false(backup_file, yaml_file)
  if File.exist?(backup_file)
    FileUtils.cp(backup_file, yaml_file)
    FileUtils.rm(backup_file)
    Lich.log "info: Backup restored after encryption mode change failure"
  end
  false
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

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



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
# File 'documented/common/authentication/entry_store.rb', line 77

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

  # Create backup of existing file if it exists
  if File.exist?(yaml_file)
    backup_file = "#{yaml_file}.bak"
    FileUtils.cp(yaml_file, backup_file)
  end

  # Write YAML data to file with secure permissions
  begin
    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)



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 814

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

Parameters:

  • yaml_file (String)

    Path to YAML file to write

  • yaml_data (Hash)

    YAML data structure to save



1052
1053
1054
1055
1056
1057
1058
1059
1060
# File 'documented/common/authentication/entry_store.rb', line 1052

def self.write_yaml_file(yaml_file, yaml_data)
  prepared_yaml = prepare_yaml_for_serialization(yaml_data)

  File.open(yaml_file, 'w', 0o600) do |file|
    file.puts "# Lich 5 Login Entries - YAML Format"
    file.puts "# Generated: #{Time.now}"
    file.write(YAML.dump(prepared_yaml, permitted_classes: [Symbol]))
  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.



22
23
24
# File 'documented/common/authentication/entry_store.rb', line 22

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