From 8de59dea24eba8a3a4b9f1d4ea0f3170a4ab5d56 Mon Sep 17 00:00:00 2001 From: Terry Yiu <963907+tyiu@users.noreply.github.com> Date: Sat, 4 Feb 2023 16:33:36 -0500 Subject: [PATCH] Refactor private key detection logic --- damus/Util/Keys.swift | 14 ++++++++++++++ damus/Views/DMChatView.swift | 7 +------ damus/Views/PostView.swift | 7 +------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/damus/Util/Keys.swift b/damus/Util/Keys.swift index fb38cdd7..b5565d81 100644 --- a/damus/Util/Keys.swift +++ b/damus/Util/Keys.swift @@ -158,6 +158,20 @@ func get_saved_privkey() -> String? { return mkey.map { $0.trimmingCharacters(in: .whitespaces) } } +/** + Detects whether a string might contain an nsec1 prefixed private key. + It does not determine if it's the current user's private key and does not verify if it is properly encoded or has the right length. + */ +func contentContainsPrivateKey(_ content: String) -> Bool { + if #available(iOS 16.0, *) { + return content.contains(/nsec1[02-9ac-z]+/) + } else { + let regex = try! NSRegularExpression(pattern: "nsec1[02-9ac-z]+") + return (regex.firstMatch(in: content, range: NSRange(location: 0, length: content.count)) != nil) + } + +} + fileprivate func removePrivateKeyFromUserDefaults() throws { guard let privKey = UserDefaults.standard.string(forKey: "privkey") else { return } try save_privkey(privkey: privKey) diff --git a/damus/Views/DMChatView.swift b/damus/Views/DMChatView.swift index 5e2c8dc0..8111c506 100644 --- a/damus/Views/DMChatView.swift +++ b/damus/Views/DMChatView.swift @@ -97,12 +97,7 @@ struct DMChatView: View { Button( role: .none, action: { - if #available(iOS 16.0, *) { - showPrivateKeyWarning = message.contains(/nsec1[02-9ac-z]+/) - } else { - let regex = try! NSRegularExpression(pattern: "nsec1[02-9ac-z]+") - showPrivateKeyWarning = (regex.firstMatch(in: message, range: NSRange(location: 0, length: message.count)) != nil) - } + showPrivateKeyWarning = contentContainsPrivateKey(message) if !showPrivateKeyWarning { send_message() diff --git a/damus/Views/PostView.swift b/damus/Views/PostView.swift index dd1c01cd..0cc0d38e 100644 --- a/damus/Views/PostView.swift +++ b/damus/Views/PostView.swift @@ -66,12 +66,7 @@ struct PostView: View { if !is_post_empty { Button(NSLocalizedString("Post", comment: "Button to post a note.")) { - if #available(iOS 16.0, *) { - showPrivateKeyWarning = self.post.contains(/nsec1[02-9ac-z]+/) - } else { - let regex = try! NSRegularExpression(pattern: "nsec1[02-9ac-z]+") - showPrivateKeyWarning = (regex.firstMatch(in: self.post, range: NSRange(location: 0, length: self.post.count)) != nil) - } + showPrivateKeyWarning = contentContainsPrivateKey(self.post) if !showPrivateKeyWarning { self.send_post()