Без опису

OpenAIConfiguration.swift 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import Foundation
  2. enum OpenAIConfiguration {
  3. private static let obfuscationKey: [UInt8] = [0xA7, 0x3C, 0x91, 0x5E]
  4. /// XOR-obfuscated default API key (not stored in plaintext).
  5. private static let obfuscatedDefaultKey: [UInt8] = [
  6. 212, 87, 188, 45, 209, 95, 240, 61, 196, 72, 188, 23,
  7. 200, 12, 244, 24, 223, 121, 197, 110, 214, 82, 243, 4,
  8. 224, 73, 213, 61, 201, 88, 203, 56, 227, 84, 200, 56,
  9. 230, 12, 219, 1, 203, 112, 218, 40, 236, 126, 163, 108,
  10. 223, 76, 246, 27, 240, 109, 203, 26, 237, 125, 229, 19,
  11. 227, 111, 169, 43, 200, 86, 233, 21, 197, 70, 221, 13,
  12. 200, 74, 254, 56, 198, 102, 218, 51, 203, 86, 227, 11,
  13. 192, 104, 162, 28, 203, 94, 250, 24, 237, 109, 221, 61,
  14. 247, 80, 249, 10, 150, 95, 222, 102, 146, 100, 226, 21,
  15. 201, 127, 195, 9, 222, 99, 247, 36, 138, 77, 220, 109,
  16. 205, 99, 240, 63, 240, 85, 197, 55, 214, 112, 240, 55,
  17. 194, 112, 221, 11, 158, 17, 225, 16, 215, 12, 192, 106,
  18. 193, 117, 221, 14, 241, 17, 218, 46, 204, 88, 247, 6,
  19. 228, 75, 240, 26, 213, 9, 225, 26, 233, 87, 208,
  20. ]
  21. /// `OPENAI_API_KEY` for local debug, otherwise the embedded obfuscated default.
  22. static var apiKey: String {
  23. let fromEnvironment = ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? ""
  24. let trimmedEnvironment = fromEnvironment.trimmingCharacters(in: .whitespacesAndNewlines)
  25. if !trimmedEnvironment.isEmpty {
  26. return trimmedEnvironment
  27. }
  28. return deobfuscate(obfuscatedDefaultKey)
  29. }
  30. /// Whether `apiKey` is currently populated with a real value.
  31. static var hasAPIKey: Bool {
  32. !apiKey.isEmpty
  33. }
  34. private static func deobfuscate(_ bytes: [UInt8]) -> String {
  35. let decoded = bytes.enumerated().map { index, byte in
  36. byte ^ obfuscationKey[index % obfuscationKey.count]
  37. }
  38. return String(bytes: decoded, encoding: .utf8) ?? ""
  39. }
  40. }