Skip to content

Linux + iPhone Continuity / iMessage / SMS

feat: handle OTP codes from messages and notifications

Zack Bartel42e4add1efd4
diff --git a/README.md b/README.md
index c00f9df..516f9a5 100644
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ Streamline two-factor authentication across your devices:
- iOS Share Extension: Send OTP codes from your iPhone to your Linux clipboard.
- Thunderbird Addon: Automatically parse OTP codes from incoming email messages.
- Browser Extension: Autofill OTP codes into login forms from the iOS app or the mail extension.
-- SMS / iMessage: Receive OTP codes from SMS or iMessage and send them to the Linux clipboard (Experimental).
+- SMS / iMessage: Detects OTP codes in incoming messages and notifications and offers them to the browser extension for autofill.
### Browser & Mail Extensions
A unified WebExtension that works in Thunderbird/Betterbird and Firefox/Chromium browsers:
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 02a2737..676d9d5 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -184,6 +184,8 @@ Offloads an entire file transfer to the daemon. The daemon spawns a thread to re
Tether uses the local UNIX socket to coordinate OTP syncing between mail clients (Thunderbird/Betterbird) and web browsers (Firefox/Chrome). The daemon acts as an ephemeral secure vault for these codes.
+The daemon also fills the vault itself: incoming Bluetooth messages (MAP) and iPhone notifications (ANCS) are scanned for OTP codes, and a hit is pushed to local subscribers as `otp_available` exactly as a `new_otp` from the mail extension would be. The same code arriving twice (once over MAP, once over ANCS) is published only once.
+
### `new_otp` (Mail Extension -> Daemon)
**Description**: Sent by the mail extension via native messaging when an OTP code is scraped from a new email.
**Payload**:
diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hpp
index fd1d616..844ee8f 100644
--- a/src/core/include/tether/net.hpp
+++ b/src/core/include/tether/net.hpp
@@ -25,6 +25,9 @@ namespace tether {
void register_local_subscriber(int fd);
void unregister_local_subscriber(int fd);
void broadcast_local_event(const std::string& msg, int exclude_fd = -1);
+
+ // Store an OTP and push it to local subscribers (browser extension, GTK).
+ void otp_publish(const std::string& code, int exclude_fd = -1);
void record_received_file(const std::filesystem::path& path, size_t bytes_written);
size_t broadcast_tcp_message(const std::string& msg, int exclude_fd = -1);
diff --git a/src/core/include/tether/otp.hpp b/src/core/include/tether/otp.hpp
index eda3473..82083d8 100644
--- a/src/core/include/tether/otp.hpp
+++ b/src/core/include/tether/otp.hpp
@@ -32,4 +32,7 @@ namespace tether {
void otp_reset(); // tests
+ // Best OTP candidate in a short message body or notification, or "" when no OTP.
+ std::string otp_extract(const std::string& text);
+
} // namespace tether
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index fac9da5..33fb24e 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -103,6 +103,15 @@ namespace tether {
return event;
}
+ void otp_publish(const std::string& code, int exclude_fd) {
+ if (code.empty())
+ return;
+ if (Otp current = otp_peek(); current && current.code == code)
+ return;
+ uint64_t id = otp_store(code);
+ broadcast_local_event(make_otp_event({code, id}).dump(), exclude_fd);
+ }
+
void register_local_subscriber(int fd) {
std::lock_guard<std::mutex> lock(g_subscribers_mutex);
local_subscribers.insert(fd);
@@ -903,11 +912,7 @@ namespace tether {
continue;
}
} else if (j.contains("command") && j["command"] == "new_otp" && j.contains("otp")) {
- std::string code = otp_from_json(j["otp"]);
- uint64_t id = otp_store(code);
- // Push the code to local subscribers (browser extension, GTK, etc.)
- // so the browser fills it without depending on its polling timing.
- broadcast_local_event(make_otp_event({code, id}).dump(), client_fd);
+ otp_publish(otp_from_json(j["otp"]), client_fd);
std::string payload = "{\"status\":\"ok\"}\n";
write_plain_packet(client_fd, payload);
continue;
@@ -1328,12 +1333,7 @@ namespace tether {
}
} else if (j.contains("command") && j["command"] == "new_otp" && j.contains("otp")) {
// OTP sent from a mobile client (iPhone Share Extension) over mTLS.
- // Store it in the global vault so the browser extension can retrieve it.
- std::string code = otp_from_json(j["otp"]);
- uint64_t id = otp_store(code);
- // Notify local subscribers (GTK, browser ext, etc.) using the
- // otp_available shape the browser extension listens for.
- broadcast_local_event(make_otp_event({code, id}).dump());
+ otp_publish(otp_from_json(j["otp"]));
std::string payload = "{\"status\":\"ok\"}\n";
robust_ssl_write(ssl, payload.c_str(), payload.size());
continue;
diff --git a/src/core/src/otp.cpp b/src/core/src/otp.cpp
index f257ae7..470ee1a 100644
--- a/src/core/src/otp.cpp
+++ b/src/core/src/otp.cpp
@@ -1,6 +1,10 @@
#include "tether/otp.hpp"
+#include <algorithm>
+#include <cctype>
#include <mutex>
+#include <regex>
+#include <string_view>
namespace tether {
@@ -87,4 +91,116 @@ namespace tether {
g_next_id = 1;
}
+ namespace {
+ // Words an OTP message uses
+ constexpr std::string_view kCues[] = {"code",
+ "otp",
+ "one-time",
+ "one time",
+ "verification",
+ "verify",
+ "passcode",
+ "password",
+ "authenticate",
+ "login",
+ "log in",
+ "sign in",
+ "2fa",
+ "token",
+ "pin",
+ "security",
+ "confirm",
+ "do not share",
+ "expires"};
+
+ std::string to_lower(std::string s) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
+ return s;
+ }
+
+ // Distance from `target` to the closest occurrence of `needle`, or npos.
+ size_t nearest(const std::string& haystack, std::string_view needle, size_t target) {
+ size_t best = std::string::npos;
+ for (size_t i = haystack.find(needle); i != std::string::npos; i = haystack.find(needle, i + 1)) {
+ size_t d = i > target ? i - target : target - i;
+ if (best == std::string::npos || d < best)
+ best = d;
+ if (i > target)
+ break; // occurrences are ordered; past the target they only get worse
+ }
+ return best;
+ }
+
+ int score_at(const std::string& lower_text, size_t index) {
+ int score = 0;
+ for (std::string_view cue : kCues) {
+ size_t d = nearest(lower_text, cue, index);
+ if (d == std::string::npos)
+ continue;
+ score += 10;
+ if (d <= 30)
+ score += 20;
+ }
+ return score;
+ }
+
+ bool looks_bogus(const std::string& code, const std::string& lower_context) {
+ static const std::regex kYear(R"(^(19|20)\d{2}$)");
+ if (std::regex_match(code, kYear))
+ return true;
+ if (code.size() > 6 && code.front() == '0')
+ return true; // phone-like
+ if (lower_context.find('$') != std::string::npos || lower_context.find("usd") != std::string::npos)
+ return true;
+ return lower_context.find("order") != std::string::npos ||
+ lower_context.find("tracking") != std::string::npos;
+ }
+
+ std::string strip_separators(std::string s) {
+ std::erase_if(s, [](char c) { return c == '-' || c == ' '; });
+ return s;
+ }
+ } // namespace
+
+ std::string otp_extract(const std::string& text) {
+ if (text.empty() || text.size() > 4096)
+ return {};
+
+ const std::string lower = to_lower(text);
+ if (std::none_of(std::begin(kCues), std::end(kCues), [&lower](std::string_view cue) {
+ return lower.find(cue) != std::string::npos;
+ }))
+ return {};
+
+ static const std::regex kPatterns[] = {
+ std::regex(R"(\b\d{3}[- ]\d{3}\b)"),
+ std::regex(R"(\b\d{4,8}\b)"),
+ std::regex(R"(\b(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{6,8}\b)"),
+ };
+
+ std::string best;
+ int best_score = -1;
+ for (const std::regex& pattern : kPatterns) {
+ for (auto it = std::sregex_iterator(text.begin(), text.end(), pattern), end = std::sregex_iterator();
+ it != end;
+ ++it) {
+ const size_t index = static_cast<size_t>(it->position());
+ const size_t length = static_cast<size_t>(it->length());
+ const size_t from = index > 40 ? index - 40 : 0;
+ const std::string context = lower.substr(from, length + 80);
+ const std::string code = strip_separators(it->str());
+
+ if (looks_bogus(code, context))
+ continue;
+
+ int score = score_at(lower, index);
+ if (score > best_score) {
+ best_score = score;
+ best = code;
+ }
+ }
+ }
+ return best;
+ }
+
} // namespace tether
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index f19c538..75258f6 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -14,6 +14,7 @@
#include <tether/file_transfer.hpp>
#include <tether/log.hpp>
#include <tether/net.hpp>
+#include <tether/otp.hpp>
#include <tether/wayland.hpp>
#include <unistd.h>
@@ -129,6 +130,9 @@ int main(int argc, char** argv) {
event["command"] = "bt_message";
tether::broadcast_local_event(event.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace));
+ if (!backfill && !message.outgoing)
+ tether::otp_publish(tether::otp_extract(message.body));
+
// ANCS deliberately shows no popup for Messages, because MAP is the
// copy whose read state stays in sync with the phone. This is that popup.
if (backfill || message.outgoing || message.read)
@@ -183,6 +187,9 @@ int main(int argc, char** argv) {
static_cast<int64_t>(std::time(nullptr)));
}
+ tether::otp_publish(tether::otp_extract(notification.title + "\n" + notification.subtitle + "\n" +
+ notification.body));
+
nlohmann::json event = tether::bluetooth::ancs::to_json(notification);
event["command"] = "bt_notification";
tether::broadcast_local_event(event.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace));
diff --git a/test/test_otp.cpp b/test/test_otp.cpp
index 4a615f5..dd16c9c 100644
--- a/test/test_otp.cpp
+++ b/test/test_otp.cpp
@@ -139,3 +139,28 @@ TEST_F(OtpTest, ConsumingClearsTheClaim) {
otp_consume(id);
EXPECT_FALSE(otp_is_claimed());
}
+
+TEST(OtpExtractTest, TypicalSmsCodes) {
+ EXPECT_EQ(otp_extract("Your verification code is 123456"), "123456");
+ EXPECT_EQ(otp_extract("847291 is your Amazon OTP. Do not share it."), "847291");
+ EXPECT_EQ(otp_extract("G-593012 is your Google verification code."), "593012");
+ EXPECT_EQ(otp_extract("Your login code: 123 456"), "123456");
+ EXPECT_EQ(otp_extract("Your code is 4821. Expires in 10 minutes."), "4821");
+ EXPECT_EQ(otp_extract("Use passcode X7F2QK9 to sign in."), "X7F2QK9");
+}
+
+TEST(OtpExtractTest, IgnoresTextWithoutAnOtpCue) {
+ EXPECT_EQ(otp_extract("Running late, be there at 1830"), "");
+ EXPECT_EQ(otp_extract("Call me back on 5551234"), "");
+ EXPECT_EQ(otp_extract(""), "");
+}
+
+TEST(OtpExtractTest, RejectsLookalikes) {
+ EXPECT_EQ(otp_extract("Your order 8891234 shipped, tracking code below"), "");
+ EXPECT_EQ(otp_extract("Security alert: charge of $4500 confirmed"), "");
+ EXPECT_EQ(otp_extract("Your code is here"), "");
+}
+
+TEST(OtpExtractTest, PrefersTheNumberNearestTheCue) {
+ EXPECT_EQ(otp_extract("Ref 987654 for the ticket. Your verification code is 112233."), "112233");
+}