diff --git a/Sources/XMTPiOS/Client.swift b/Sources/XMTPiOS/Client.swift index 3a949a7b..e4e42fa1 100644 --- a/Sources/XMTPiOS/Client.swift +++ b/Sources/XMTPiOS/Client.swift @@ -53,6 +53,7 @@ public struct ClientOptions { public var mlsAlpha = false public var mlsEncryptionKey: Data? + public var mlsDbPath: String? public init( api: Api = Api(), @@ -128,13 +129,28 @@ public final class Client { signingKey: SigningKey? ) async throws -> FfiXmtpClient? { if options?.mlsAlpha == true, options?.api.env.supportsMLS == true { - let dbURL = URL.documentsDirectory.appendingPathComponent("xmtp-\(options?.api.env.rawValue ?? "")-\(address).db3") + let dbURL = options?.mlsDbPath ?? URL.documentsDirectory.appendingPathComponent("xmtp-\(options?.api.env.rawValue ?? "")-\(address).db3").path + + var encryptionKey = options?.mlsEncryptionKey + if (encryptionKey == nil) { + let preferences = UserDefaults.standard + let key = "xmtp-key" + if preferences.data(forKey: key) == nil { + let data = Data(try Crypto.secureRandomBytes(count: 32)) + preferences.set(data, forKey: key) + preferences.synchronize() + encryptionKey = data + } else { + encryptionKey = preferences.data(forKey: key) + } + } + let v3Client = try await LibXMTP.createClient( logger: XMTPLogger(), host: (options?.api.env ?? .local).url, isSecure: options?.api.env.isSecure == true, - db: dbURL.path, - encryptionKey: options?.mlsEncryptionKey, + db: dbURL, + encryptionKey: encryptionKey, accountAddress: address, legacyIdentitySource: source, legacySignedPrivateKeyProto: try privateKeyBundleV1.toV2().identityKey.serializedData()