keyIdForNamedSecretStorageKey method

String? keyIdForNamedSecretStorageKey(
  1. String name
)

Resolves the key id for a secret-storage key definition by its name field on m.secret_storage.key.<key_id> account data.

If several keys share the same name (e.g. an orphaned definition left on the server after rotation), returns the id that appears most often in encrypted secret account data from analyzeEncryptedSecrets. Ties use lexicographic key order. Returns null when no key with that name exists.

Implementation

String? keyIdForNamedSecretStorageKey(String name) {
  if (name.isEmpty) return null;
  const prefix = 'm.secret_storage.key.';
  final candidates = <String>[];
  for (final entry in client.accountData.entries) {
    if (!entry.key.startsWith(prefix)) continue;
    final keyName = entry.value.content['name'];
    if (keyName == name) {
      candidates.add(entry.key.substring(prefix.length));
    }
  }
  if (candidates.isEmpty) return null;

  if (candidates.length == 1) {
    return candidates.first;
  }

  final usage = <String, int>{for (final id in candidates) id: 0};
  for (final keyIds in analyzeEncryptedSecrets().values) {
    for (final kid in keyIds) {
      if (usage.containsKey(kid)) {
        usage[kid] = usage[kid]! + 1;
      }
    }
  }
  final ranked = usage.entries.toList()
    ..sort((a, b) {
      final byCount = b.value.compareTo(a.value);
      if (byCount != 0) return byCount;
      return a.key.compareTo(b.key);
    });
  if (ranked.first.value > 0) {
    return ranked.first.key;
  }
  return null;
}