Skip to content

Linux + iPhone Continuity / iMessage / SMS

feat(otp): pin mail-sourced OTPs to the sender's domain

c10l44b6cc590d0f
diff --git a/extension/src/mail/extractor.js b/extension/src/mail/extractor.js
index 469984f..f690a49 100644
--- a/extension/src/mail/extractor.js
+++ b/extension/src/mail/extractor.js
@@ -94,6 +94,16 @@ export function isFalsePositive(num, context) {
return false;
}
+// Pull the registrable domain out of a From header such as
+// "Amazon <[email protected]>" or a bare "[email protected]".
+export function extractSenderDomain(author) {
+ if (!author || typeof author !== 'string') return '';
+ const match = author.match(/[\w.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+/);
+ if (!match) return '';
+ const domain = match[0].split('@')[1];
+ return domain.toLowerCase().replace(/\.+$/, '');
+}
+
// ---------------------------------------------------------------------------
// FALLBACK text extraction: manually walk getFull() parts.
// Recovery path for messages whose MIME tree makes listInlineTextParts() throw.
@@ -268,7 +278,8 @@ export async function processMessage(message) {
sendToNativeHost({
command: "new_otp",
otp: best.num.replace(/[-\s]/g, ''),
- source: message.subject
+ source: message.subject,
+ sender_domain: extractSenderDomain(message.author)
});
}
}
diff --git a/extension/src/shared/native.js b/extension/src/shared/native.js
index eedc69a..ff8ef7b 100644
--- a/extension/src/shared/native.js
+++ b/extension/src/shared/native.js
@@ -77,21 +77,40 @@ function isValidOtp(value) {
return typeof value === 'string' && value.length > 0 && value.length <= 64;
}
+function normalizeDomain(d) {
+ return String(d || '').toLowerCase().replace(/\.+$/, '');
+}
+
+// A page host matches a pinned sender domain when it is equal or a subdomain:
+// "amazon.com" matches "amazon.com" and "www.amazon.com", but not
+// "amazon.com.evil.com" or "evilamazon.com". An empty domain means the OTP is
+// not pinned and any host may take it.
+export function hostMatchesDomain(host, domain) {
+ const d = normalizeDomain(domain);
+ if (!d) return true;
+ const h = normalizeDomain(host);
+ if (h === d) return true;
+ return h.endsWith('.' + d);
+}
+
// Deliver an OTP only to tabs that asked for one, most-relevant first, and stop
// at the first tab that reports it actually filled a field. We never blast the
// code to unrelated tabs: a page with an OTP-shaped input must not be handed a
-// code it did not request.
+// code it did not request, and when the code came from email we only hand it to
+// the domain the email was sent by.
export function deliverOtpToTabs(message) {
if (typeof chrome === 'undefined' || !chrome.tabs) return;
if (!message || !isValidOtp(message.otp)) return;
pruneOtpRequests();
+ const senderDomain = typeof message.sender_domain === 'string' ? message.sender_domain : '';
+
chrome.tabs.query({}, function(tabs) {
const byId = new Map((tabs || []).map((t) => [t.id, t]));
const candidates = [...requestingTabs.entries()]
- .filter(([id]) => byId.has(id))
+ .filter(([id, req]) => byId.has(id) && hostMatchesDomain(req.host, senderDomain))
.sort((a, b) => {
const ta = byId.get(a[0]);
const tb = byId.get(b[0]);
diff --git a/extension/test/extractor.test.js b/extension/test/extractor.test.js
index d8d3e44..55c9c86 100644
--- a/extension/test/extractor.test.js
+++ b/extension/test/extractor.test.js
@@ -32,7 +32,17 @@ global.messenger = {
}
};
-import { scoreCandidate, isFalsePositive, OTP_PATTERNS } from '../src/mail/extractor.js';
+global.browser = {
+ runtime: {
+ connectNative: vi.fn().mockReturnValue({
+ postMessage: vi.fn(),
+ onMessage: { addListener: vi.fn() },
+ onDisconnect: { addListener: vi.fn() }
+ })
+ }
+};
+
+import { scoreCandidate, isFalsePositive, OTP_PATTERNS, processMessage, extractSenderDomain } from '../src/mail/extractor.js';
function extractOtpCandidates(text) {
const candidates = [];
@@ -133,6 +143,50 @@ describe('OTP pattern matching', () => {
});
});
+describe('extractSenderDomain', () => {
+ it('extracts the domain from a display-name header', () => {
+ expect(extractSenderDomain('Amazon <[email protected]>')).toBe('amazon.com');
+ expect(extractSenderDomain('Google <[email protected]>')).toBe('accounts.google.com');
+ });
+
+ it('extracts the domain from a bare address', () => {
+ expect(extractSenderDomain('[email protected]')).toBe('amazon.com');
+ });
+
+ it('returns empty string for missing or malformed input', () => {
+ expect(extractSenderDomain('')).toBe('');
+ expect(extractSenderDomain(null)).toBe('');
+ expect(extractSenderDomain('not an email')).toBe('');
+ });
+
+ it('lowercases and strips trailing dots', () => {
+ expect(extractSenderDomain('[email protected].')).toBe('amazon.com');
+ });
+});
+
+describe('processMessage sends the sender domain', () => {
+ it('includes sender_domain in the new_otp message', async () => {
+ global.messenger.messages.listInlineTextParts.mockResolvedValueOnce([
+ { contentType: 'text/plain', content: 'Your verification code is 123456' }
+ ]);
+
+ await processMessage({
+ id: 42,
+ subject: 'Your verification code',
+ author: 'Amazon <[email protected]>'
+ });
+
+ const postMessage = global.browser.runtime.connectNative.mock.results[0].value.postMessage;
+ expect(postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ command: 'new_otp',
+ otp: '123456',
+ sender_domain: 'amazon.com'
+ })
+ );
+ });
+});
+
describe('Real email fixtures', () => {
it('extracts OTP from MyBank email', () => {
const text = `PREVENT FRAUD: DO NOT SHARE THIS CODE. MyBank will never contact you asking for it. Only use verification code: 171792 in Online Banking or the MyBank App.`;
diff --git a/extension/test/native.test.js b/extension/test/native.test.js
index dfb3fe2..5d7e44d 100644
--- a/extension/test/native.test.js
+++ b/extension/test/native.test.js
@@ -31,7 +31,7 @@ beforeEach(() => {
installChrome([{ id: 1 }, { id: 2 }, { id: 3 }]);
});
-const { connectToNativeHost, registerOtpRequest, _resetOtpRequests } =
+const { connectToNativeHost, registerOtpRequest, _resetOtpRequests, hostMatchesDomain } =
await import('../src/shared/native.js');
describe('native host receive/routing', () => {
@@ -76,6 +76,47 @@ describe('native host receive/routing', () => {
expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
});
+ it('only delivers a pinned OTP to a matching requesting domain', () => {
+ connectToNativeHost();
+ registerOtpRequest(1, 'evil.com');
+ registerOtpRequest(2, 'www.amazon.com');
+
+ messageListener({
+ command: 'otp_available',
+ otp: '123456',
+ otp_id: 9,
+ sender_domain: 'amazon.com'
+ });
+
+ const tabIds = chrome.tabs.sendMessage.mock.calls.map((c) => c[0]);
+ expect(tabIds).toEqual([2]);
+ expect(tabIds).not.toContain(1);
+ });
+
+ it('delivers an unpinned OTP to any requesting domain', () => {
+ connectToNativeHost();
+ registerOtpRequest(1, 'evil.com');
+
+ messageListener({ command: 'otp_available', otp: '123456', otp_id: 9 });
+
+ const tabIds = chrome.tabs.sendMessage.mock.calls.map((c) => c[0]);
+ expect(tabIds).toEqual([1]);
+ });
+
+ it('does not deliver a pinned OTP when no requesting tab matches', () => {
+ connectToNativeHost();
+ registerOtpRequest(1, 'evil.com');
+
+ messageListener({
+ command: 'otp_available',
+ otp: '123456',
+ otp_id: 9,
+ sender_domain: 'amazon.com'
+ });
+
+ expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
+ });
+
it('ignores an otp_available event with an empty code', () => {
connectToNativeHost();
registerOtpRequest(1, 'a.example.com');
@@ -92,3 +133,26 @@ describe('native host receive/routing', () => {
expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
});
});
+
+describe('hostMatchesDomain', () => {
+ it('matches exact and subdomain hosts', () => {
+ expect(hostMatchesDomain('amazon.com', 'amazon.com')).toBe(true);
+ expect(hostMatchesDomain('www.amazon.com', 'amazon.com')).toBe(true);
+ expect(hostMatchesDomain('login.amazon.com', 'amazon.com')).toBe(true);
+ });
+
+ it('rejects suffix spoofs', () => {
+ expect(hostMatchesDomain('amazon.com.evil.com', 'amazon.com')).toBe(false);
+ expect(hostMatchesDomain('evilamazon.com', 'amazon.com')).toBe(false);
+ expect(hostMatchesDomain('notamazon.com', 'amazon.com')).toBe(false);
+ });
+
+ it('treats an empty domain as unpinned', () => {
+ expect(hostMatchesDomain('anything.example.com', '')).toBe(true);
+ expect(hostMatchesDomain('', '')).toBe(true);
+ });
+
+ it('normalizes case and trailing dots', () => {
+ expect(hostMatchesDomain('www.amazon.com', 'Amazon.COM.')).toBe(true);
+ });
+});
diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hpp
index 6f29b50..d39c38e 100644
--- a/src/core/include/tether/net.hpp
+++ b/src/core/include/tether/net.hpp
@@ -29,7 +29,9 @@ namespace tether {
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);
+ // sender_domain is the registrable domain of the email sender, "" when the
+ // code did not come from email.
+ void otp_publish(const std::string& code, const std::string& sender_domain = "", 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 82083d8..8caab57 100644
--- a/src/core/include/tether/otp.hpp
+++ b/src/core/include/tether/otp.hpp
@@ -9,6 +9,7 @@ namespace tether {
// single-slot OTP vault shared by every transport
struct Otp {
std::string code;
+ std::string sender_domain; // registrable domain of the source; "" when unknown
uint64_t id = 0; // 0 == no code
explicit operator bool() const { return id != 0 && !code.empty(); }
};
@@ -18,7 +19,11 @@ namespace tether {
inline constexpr auto kOtpTtl = std::chrono::minutes(5);
// Store a code, assign it the next id, drop any previous host claim.
- uint64_t otp_store(const std::string& code, OtpClock::time_point now = OtpClock::now());
+ // sender_domain is the registrable domain of the email sender ("" when the
+ // code did not come from email, e.g. Bluetooth/ANCS).
+ uint64_t otp_store(const std::string& code,
+ const std::string& sender_domain = "",
+ OtpClock::time_point now = OtpClock::now());
// Current code if still within the TTL, else {}. Expires the slot as a side effect.
Otp otp_peek(OtpClock::time_point now = OtpClock::now());
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index 2d24eee..dabaf47 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -104,16 +104,18 @@ namespace tether {
event["command"] = "otp_available";
event["otp"] = otp.code;
event["otp_id"] = otp.id;
+ if (!otp.sender_domain.empty())
+ event["sender_domain"] = otp.sender_domain;
return event;
}
- void otp_publish(const std::string& code, int exclude_fd) {
+ void otp_publish(const std::string& code, const std::string& sender_domain, 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);
+ uint64_t id = otp_store(code, sender_domain);
+ broadcast_local_event(make_otp_event({code, sender_domain, id}).dump(), exclude_fd);
}
void register_local_subscriber(int fd) {
@@ -1008,7 +1010,9 @@ namespace tether {
continue;
}
} else if (j.contains("command") && j["command"] == "new_otp" && j.contains("otp")) {
- otp_publish(otp_from_json(j["otp"]), client_fd);
+ otp_publish(otp_from_json(j["otp"]),
+ j.value("sender_domain", std::string{}),
+ client_fd);
std::string payload = "{\"status\":\"ok\"}\n";
write_plain_packet(client_fd, payload);
continue;
@@ -1442,7 +1446,8 @@ 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.
- otp_publish(otp_from_json(j["otp"]));
+ otp_publish(otp_from_json(j["otp"]),
+ j.value("sender_domain", std::string{}));
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 470ee1a..df8bdf2 100644
--- a/src/core/src/otp.cpp
+++ b/src/core/src/otp.cpp
@@ -11,6 +11,7 @@ namespace tether {
namespace {
std::mutex g_mutex;
std::string g_code;
+ std::string g_sender_domain; // registrable domain of the code's source; "" = unknown
uint64_t g_id = 0;
uint64_t g_next_id = 1;
std::string g_claimed_host; // empty until some host takes the code
@@ -19,6 +20,7 @@ namespace tether {
// Caller holds g_mutex.
void clear_locked() {
g_code.clear();
+ g_sender_domain.clear();
g_id = 0;
g_claimed_host.clear();
}
@@ -31,17 +33,39 @@ namespace tether {
clear_locked();
return {};
}
- return {g_code, g_id};
+ return {g_code, g_sender_domain, g_id};
+ }
+
+ std::string normalize_domain(std::string d) {
+ std::transform(d.begin(), d.end(), d.begin(), [](unsigned char c) { return std::tolower(c); });
+ while (!d.empty() && d.back() == '.')
+ d.pop_back();
+ return d;
+ }
+
+ // A page host matches a pinned sender domain when it is equal or a
+ // subdomain: "amazon.com" matches "amazon.com" and "www.amazon.com", but
+ // not "amazon.com.evil.com" or "evilamazon.com". An empty domain means the
+ // code is not pinned and any host may claim it.
+ bool host_matches_domain(const std::string& host, const std::string& domain) {
+ const std::string h = normalize_domain(host);
+ const std::string d = normalize_domain(domain);
+ if (d.empty())
+ return true;
+ if (h == d)
+ return true;
+ return h.size() > d.size() && h.ends_with("." + d);
}
} // namespace
- uint64_t otp_store(const std::string& code, OtpClock::time_point now) {
+ uint64_t otp_store(const std::string& code, const std::string& sender_domain, OtpClock::time_point now) {
std::lock_guard<std::mutex> lock(g_mutex);
if (code.empty()) {
clear_locked();
return 0;
}
g_code = code;
+ g_sender_domain = normalize_domain(sender_domain);
g_id = g_next_id++;
g_claimed_host.clear();
g_set_at = now;
@@ -59,6 +83,11 @@ namespace tether {
if (!current)
return {};
+ // If the code came from email, only serve it to the domain the email was
+ // sent by. A phishing page on a different domain gets nothing.
+ if (!host_matches_domain(host, g_sender_domain))
+ return {};
+
// An unknown host (older extension that doesn't send url) may take an unclaimed
// code but never claims it, so it can't lock other sites out.
if (host.empty())
diff --git a/test/test_otp.cpp b/test/test_otp.cpp
index dd16c9c..de02eaa 100644
--- a/test/test_otp.cpp
+++ b/test/test_otp.cpp
@@ -20,7 +20,7 @@ TEST_F(OtpTest, EmptyVaultServesNothing) {
}
TEST_F(OtpTest, StoreAndPeek) {
- uint64_t id = otp_store("123456", t0);
+ uint64_t id = otp_store("123456", "", t0);
EXPECT_NE(id, 0u);
Otp got = otp_peek(t0);
@@ -30,19 +30,19 @@ TEST_F(OtpTest, StoreAndPeek) {
}
TEST_F(OtpTest, IdsAreUniqueAndIncreasing) {
- uint64_t first = otp_store("111111", t0);
- uint64_t second = otp_store("222222", t0);
+ uint64_t first = otp_store("111111", "", t0);
+ uint64_t second = otp_store("222222", "", t0);
EXPECT_GT(second, first);
}
TEST_F(OtpTest, StoringEmptyCodeClearsVault) {
- otp_store("123456", t0);
- EXPECT_EQ(otp_store("", t0), 0u);
+ otp_store("123456", "", t0);
+ EXPECT_EQ(otp_store("", "", t0), 0u);
EXPECT_FALSE(otp_peek(t0));
}
TEST_F(OtpTest, ExpiresAfterTtl) {
- otp_store("123456", t0);
+ otp_store("123456", "", t0);
EXPECT_TRUE(otp_peek(t0 + std::chrono::minutes(4)));
EXPECT_FALSE(otp_peek(t0 + kOtpTtl));
// Expiry is destructive: the slot is empty even back at t0.
@@ -52,7 +52,7 @@ TEST_F(OtpTest, ExpiresAfterTtl) {
// The reported bug: a code taken by one site must not be served to the next site
// the user visits, even while it is still within its TTL.
TEST_F(OtpTest, CodeIsClaimedByTheFirstHostThatTakesIt) {
- otp_store("123456", t0);
+ otp_store("123456", "", t0);
Otp a = otp_take_for_host("a.com", t0);
ASSERT_TRUE(a);
@@ -63,7 +63,7 @@ TEST_F(OtpTest, CodeIsClaimedByTheFirstHostThatTakesIt) {
}
TEST_F(OtpTest, ClaimingHostKeepsPollingSuccessfully) {
- otp_store("123456", t0);
+ otp_store("123456", "", t0);
ASSERT_TRUE(otp_take_for_host("a.com", t0));
// a.com's content script polls every 2s until it fills; it must keep getting the code.
Otp again = otp_take_for_host("a.com", t0);
@@ -72,12 +72,12 @@ TEST_F(OtpTest, ClaimingHostKeepsPollingSuccessfully) {
}
TEST_F(OtpTest, NewCodeResetsTheClaim) {
- otp_store("111111", t0);
+ otp_store("111111", "", t0);
ASSERT_TRUE(otp_take_for_host("a.com", t0));
EXPECT_FALSE(otp_take_for_host("b.com", t0));
// A fresh email arrives; b.com is now entitled to it.
- otp_store("222222", t0);
+ otp_store("222222", "", t0);
EXPECT_FALSE(otp_is_claimed());
Otp b = otp_take_for_host("b.com", t0);
ASSERT_TRUE(b);
@@ -87,20 +87,72 @@ TEST_F(OtpTest, NewCodeResetsTheClaim) {
TEST_F(OtpTest, UnknownHostTakesButDoesNotClaim) {
// Older extension builds don't send `url`. They may still fill, but must not
// lock every other site out of the code.
- otp_store("123456", t0);
+ otp_store("123456", "", t0);
EXPECT_TRUE(otp_take_for_host("", t0));
EXPECT_FALSE(otp_is_claimed());
EXPECT_TRUE(otp_take_for_host("a.com", t0));
}
TEST_F(OtpTest, UnknownHostDoesNotStealAClaimedCode) {
- otp_store("123456", t0);
+ otp_store("123456", "", t0);
ASSERT_TRUE(otp_take_for_host("a.com", t0));
EXPECT_FALSE(otp_take_for_host("", t0));
}
+TEST_F(OtpTest, PinnedCodeServesOnlyMatchingDomain) {
+ otp_store("123456", "amazon.com", t0);
+
+ EXPECT_FALSE(otp_take_for_host("evil.com", t0));
+ EXPECT_FALSE(otp_is_claimed()) << "a mismatched host must not claim the code";
+
+ Otp got = otp_take_for_host("amazon.com", t0);
+ ASSERT_TRUE(got);
+ EXPECT_EQ(got.code, "123456");
+}
+
+TEST_F(OtpTest, PinnedCodeServesSubdomains) {
+ otp_store("123456", "amazon.com", t0);
+ EXPECT_TRUE(otp_take_for_host("www.amazon.com", t0));
+}
+
+TEST_F(OtpTest, PinnedCodeRejectsSuffixSpoofs) {
+ otp_store("123456", "amazon.com", t0);
+ EXPECT_FALSE(otp_take_for_host("amazon.com.evil.com", t0));
+ EXPECT_FALSE(otp_take_for_host("evilamazon.com", t0));
+ EXPECT_FALSE(otp_take_for_host("notamazon.com", t0));
+}
+
+TEST_F(OtpTest, PinnedCodeRejectsUnknownHost) {
+ otp_store("123456", "amazon.com", t0);
+ EXPECT_FALSE(otp_take_for_host("", t0));
+}
+
+TEST_F(OtpTest, UnpinnedCodeKeepsLegacyBehaviour) {
+ otp_store("123456", "", t0);
+ EXPECT_TRUE(otp_take_for_host("", t0));
+ EXPECT_FALSE(otp_is_claimed());
+ EXPECT_TRUE(otp_take_for_host("a.com", t0));
+}
+
+TEST_F(OtpTest, PinnedCodeClaimIsScopedToHostWithinDomain) {
+ otp_store("111111", "amazon.com", t0);
+ ASSERT_TRUE(otp_take_for_host("www.amazon.com", t0));
+ // The claiming host keeps polling successfully.
+ EXPECT_TRUE(otp_take_for_host("www.amazon.com", t0));
+ // A different host — even within the same domain — does not steal the claim.
+ EXPECT_FALSE(otp_take_for_host("amazon.com", t0));
+ // A different domain still gets nothing.
+ EXPECT_FALSE(otp_take_for_host("evil.com", t0));
+}
+
+TEST_F(OtpTest, SenderDomainIsNormalized) {
+ otp_store("123456", "Amazon.COM.", t0);
+ EXPECT_TRUE(otp_take_for_host("www.amazon.com", t0));
+ EXPECT_FALSE(otp_take_for_host("amazon.com.evil.com", t0));
+}
+
TEST_F(OtpTest, ConsumeClearsMatchingId) {
- uint64_t id = otp_store("123456", t0);
+ uint64_t id = otp_store("123456", "", t0);
otp_consume(id);
EXPECT_FALSE(otp_peek(t0));
}
@@ -108,8 +160,8 @@ TEST_F(OtpTest, ConsumeClearsMatchingId) {
// A consume can arrive late (service worker wake-up, native host restart). It must
// not delete the code that arrived in the meantime for the page now waiting.
TEST_F(OtpTest, StaleConsumeDoesNotClearNewerCode) {
- uint64_t first = otp_store("111111", t0);
- uint64_t second = otp_store("222222", t0);
+ uint64_t first = otp_store("111111", "", t0);
+ uint64_t second = otp_store("222222", "", t0);
otp_consume(first);
@@ -121,20 +173,20 @@ TEST_F(OtpTest, StaleConsumeDoesNotClearNewerCode) {
TEST_F(OtpTest, ConsumeWithoutIdClearsUnconditionally) {
// Backwards compatibility with extension builds that predate otp_id.
- otp_store("123456", t0);
+ otp_store("123456", "", t0);
otp_consume(0);
EXPECT_FALSE(otp_peek(t0));
}
TEST_F(OtpTest, ConsumeIsIdempotent) {
- uint64_t id = otp_store("123456", t0);
+ uint64_t id = otp_store("123456", "", t0);
otp_consume(id);
otp_consume(id);
EXPECT_FALSE(otp_peek(t0));
}
TEST_F(OtpTest, ConsumingClearsTheClaim) {
- otp_store("111111", t0);
+ otp_store("111111", "", t0);
uint64_t id = otp_take_for_host("a.com", t0).id;
otp_consume(id);
EXPECT_FALSE(otp_is_claimed());