Repository Public
1// SP Music iOS2// File: Core/Sources/SPMusicCore/Security/Security.swift3// Description: Logging, Base64URL, identifier validation, file hashing, session token stores (Keychain).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import CryptoKit9import Foundation10import os11import Security1213public enum Log {14 /// Messages never carry tokens, cookies or file contents; identifiers are opaque UUIDs.15 public static let app = Logger(subsystem: "ai.spboucher.spmusic", category: "app")16 public static let net = Logger(subsystem: "ai.spboucher.spmusic", category: "network")17 public static let audio = Logger(subsystem: "ai.spboucher.spmusic", category: "audio")18 public static let downloads = Logger(subsystem: "ai.spboucher.spmusic", category: "downloads")19 public static let sync = Logger(subsystem: "ai.spboucher.spmusic", category: "sync")20}2122public enum Base64URL {23 public static func encode(_ data: Data) -> String {24 data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")25 }26 public static func decode(_ s: String) -> Data? {27 var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")28 while b.count % 4 != 0 { b.append("=") }29 return Data(base64Encoded: b)30 }31}3233/// Identifiers come from the server and end up in file names and URLs: only canonical UUIDs are ever accepted,34/// so a hostile or corrupted value ("../../x") can never become a path.35public enum SafeID {36 public static func isValid(_ s: String) -> Bool {37 guard s.utf8.count == 36 else { return false }38 for (i, c) in s.utf8.enumerated() {39 if i == 8 || i == 13 || i == 18 || i == 23 { if c != UInt8(ascii: "-") { return false } }40 else if !((c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70)) { return false }41 }42 return true43 }44 public static func require(_ s: String) throws -> String {45 guard isValid(s) else { throw SafeIDError.invalid }46 return s.lowercased()47 }48 public enum SafeIDError: Error { case invalid }49}5051public enum FileHash {52 /// SHA-256 of a file read in 1 MB pieces: a 100 MB FLAC never sits in memory.53 public static func sha256(of url: URL) throws -> String {54 let handle = try FileHandle(forReadingFrom: url)55 defer { try? handle.close() }56 var hasher = SHA256()57 while true {58 let chunk = try handle.read(upToCount: 1 << 20) ?? Data()59 if chunk.isEmpty { break }60 hasher.update(data: chunk)61 }62 return hasher.finalize().map { String(format: "%02x", $0) }.joined()63 }64}6566/// Where the session token lives. The app uses the Keychain; tests use memory.67public protocol SessionTokenStore: Sendable {68 func read() -> String?69 func write(_ token: String?)70}7172public final class InMemoryTokenStore: SessionTokenStore, @unchecked Sendable {73 private let lock = NSLock()74 private var token: String?75 public init(_ token: String? = nil) { self.token = token }76 public func read() -> String? { lock.withLock { token } }77 public func write(_ token: String?) { lock.withLock { self.token = token } }78}7980/// Generic-password item, this device only (never synced, never in a backup of another device). Readable after the81/// first unlock so that playback and background downloads keep working while the phone is locked.82public final class KeychainTokenStore: SessionTokenStore, Sendable {83 private let service: String84 private let account: String85 public init(service: String = "ai.spboucher.spmusic.session", account: String = "session-token") {86 self.service = service; self.account = account87 }88 private var base: [String: Any] {89 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]90 }91 public func read() -> String? {92 var q = base93 q[kSecReturnData as String] = true94 q[kSecMatchLimit as String] = kSecMatchLimitOne95 var out: CFTypeRef?96 guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }97 return String(data: d, encoding: .utf8)98 }99 public func write(_ token: String?) {100 SecItemDelete(base as CFDictionary)101 guard let token, let data = token.data(using: .utf8) else { return }102 var q = base103 q[kSecValueData as String] = data104 q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly105 let status = SecItemAdd(q as CFDictionary, nil)106 if status != errSecSuccess { Log.app.error("keychain write failed: \(status)") }107 }108}109