Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix(extension): scope OTP delivery to requesting tab and block hidden-field harvest

c10l790f43441150
diff --git a/extension/src/background/background.js b/extension/src/background/background.js
index c8d7bd5..b1a15ec 100644
--- a/extension/src/background/background.js
+++ b/extension/src/background/background.js
@@ -3,38 +3,62 @@
// Import the native messaging module if supported (MV3 modules)
// For MV2 (Thunderbird), we might need to load this differently or bundle it.
-import { connectToNativeHost, sendToNativeHost } from '../shared/native.js';
+import {
+ connectToNativeHost,
+ sendToNativeHost,
+ registerOtpRequest,
+ clearOtpRequest,
+} from '../shared/native.js';
let nativePort = connectToNativeHost();
+function isValidHostname(host) {
+ return typeof host === 'string' && host.length > 0 && host.length <= 253;
+}
+
// Listen for messages from content scripts or the mail extractor
if (typeof chrome !== 'undefined' && chrome.runtime) {
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
+ if (!request || typeof request !== 'object') return;
+
+ // Only accept messages that originate from one of our own content scripts
+ // running in a tab. Web pages and other extensions cannot reach us here,
+ // but validate the sender explicitly anyway.
+ const fromTab = sender && sender.tab && typeof sender.tab.id === 'number';
+ if (!fromTab) return;
+
if (request.action === "found_otp_in_email") {
- console.log("Found OTP in email, sending to Tether daemon:", request.otp);
- // Send the extracted OTP to the C++ daemon
- sendToNativeHost({
- command: "new_otp",
- otp: request.otp,
- source: request.source
- });
+ // Legacy path from older mail builds; the mail extractor now talks to the
+ // daemon directly. Kept for compatibility.
+ if (typeof request.otp === 'string' && request.otp.length > 0) {
+ sendToNativeHost({
+ command: "new_otp",
+ otp: request.otp,
+ source: typeof request.source === 'string' ? request.source : ''
+ });
+ }
sendResponse({ status: "sent_to_daemon" });
+ return;
}
-
+
if (request.action === "request_otp_for_site") {
- console.log("Content script requesting OTP for:", request.url);
- // Query the C++ daemon for an OTP
- sendToNativeHost({
- command: "request_otp",
- url: request.url
- });
+ if (!isValidHostname(request.url)) {
+ sendResponse({ status: "invalid_host" });
+ return;
+ }
+ // Remember which tab asked, so the OTP is delivered back to it alone.
+ registerOtpRequest(sender.tab.id, request.url);
+ // Query the C++ daemon for an OTP.
+ sendToNativeHost({ command: "request_otp", url: request.url });
sendResponse({ status: "requested" });
+ return;
}
if (request.action === "consume_otp") {
+ clearOtpRequest(sender.tab.id);
sendToNativeHost({ command: "consume_otp", otp_id: request.otp_id || 0 });
sendResponse({ status: "consumed" });
+ return;
}
- return true;
});
}
diff --git a/extension/src/content/autofill.js b/extension/src/content/autofill.js
index a6668e4..b76b86c 100644
--- a/extension/src/content/autofill.js
+++ b/extension/src/content/autofill.js
@@ -107,6 +107,38 @@ function fireInputEvents(el) {
el.dispatchEvent(new Ev('change', { bubbles: true }));
}
+// A field is only eligible for filling if it is actually rendered. This stops a
+// malicious page from planting a hidden "OTP" input to siphon a real code.
+export function isFieldVisible(el) {
+ if (!el || el.hidden || el.type === 'hidden') return false;
+ for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
+ if (n.hidden) return false;
+ const s = n.style;
+ if (s && (s.display === 'none' || s.visibility === 'hidden' || s.visibility === 'collapse')) {
+ return false;
+ }
+ }
+ // In a real browser, also reject elements with no rendered box. jsdom has no
+ // layout engine, so only enforce this where getComputedStyle is meaningful.
+ const view = el.ownerDocument?.defaultView;
+ if (view && typeof view.getComputedStyle === 'function') {
+ try {
+ const cs = view.getComputedStyle(el);
+ if (cs && (cs.display === 'none' || cs.visibility === 'hidden' || cs.visibility === 'collapse')) {
+ return false;
+ }
+ } catch (e) { /* ignore */ }
+ }
+ return true;
+}
+
+// The page must be the tab the user is actually looking at before we request or
+// fill an OTP. Engines without visibility reporting are treated as visible.
+export function isPageVisible(doc) {
+ const vs = doc?.visibilityState;
+ return !vs || vs === 'visible';
+}
+
// codes this page has already filled
const filledOtpIds = new Set();
@@ -121,7 +153,7 @@ export function handleFillOtp(doc, msg, io = {}) {
if (id && filledOtpIds.has(id)) return { filled: false };
const splitFields = detectSplitOtp(doc);
- if (splitFields) {
+ if (splitFields && splitFields.every(isFieldVisible)) {
for (let i = 0; i < Math.min(otp.length, splitFields.length); i++) {
setNativeValue(splitFields[i], otp[i]);
// dispatch events so react/vue/angular crap pick up the change
@@ -132,7 +164,7 @@ export function handleFillOtp(doc, msg, io = {}) {
return { filled: true };
}
- const regularFields = findOtpInputs(doc);
+ const regularFields = findOtpInputs(doc).filter(isFieldVisible);
// fill when empty, or overwrite a stale/partial value
if (regularFields.length > 0 && regularFields[0].value !== otp) {
setNativeValue(regularFields[0], otp);
@@ -174,12 +206,17 @@ function hasOtpFields() {
// Check every 2 seconds for up to 2 minutes
let otpFlowStarted = false;
function startOtpFlow() {
+ // Never request codes while the tab is hidden in the background.
+ if (!isPageVisible(document)) return;
if (otpFlowStarted) return;
otpFlowStarted = true;
requestOtp();
let attempts = 0;
otpInterval = setInterval(() => {
+ // While the tab is hidden, neither request nor fill. Don't burn attempts.
+ if (!isPageVisible(document)) return;
+
attempts++;
const splits = detectSplitOtp(document);
const regular = findOtpInputs(document);
@@ -211,17 +248,28 @@ if (otpPresentAtLoad) {
setTimeout(() => observer.disconnect(), 120000);
}
+// If the page was hidden when OTP fields appeared, start the flow once it
+// becomes visible.
+document.addEventListener('visibilitychange', () => {
+ if (hasOtpFields()) startOtpFlow();
+});
+
// listen for OTPs sent from the daemon
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action !== "fill_otp") return;
+ // Only fill into a page the user is actually looking at.
+ if (!isPageVisible(document)) {
+ sendResponse({ filled: false });
+ return;
+ }
+
lastSeenOtpId = request.otp_id || lastSeenOtpId;
const result = handleFillOtp(document, request, {
onFilled: () => {
if (otpInterval) clearInterval(otpInterval);
}
});
- if (result.filled) console.log("Autofilled OTP:", request.otp);
sendResponse(result);
});
}
diff --git a/extension/src/mail/extractor.js b/extension/src/mail/extractor.js
index 396d18d..469984f 100644
--- a/extension/src/mail/extractor.js
+++ b/extension/src/mail/extractor.js
@@ -227,7 +227,7 @@ async function getEmailText(messageId) {
}
export async function processMessage(message) {
- console.log("Processing message:", message.subject);
+ console.log("Processing message");
const bodyText = await getEmailText(message.id);
@@ -264,7 +264,7 @@ export async function processMessage(message) {
const best = candidates[0];
if (best.score > 0) {
- console.log("Found OTP candidate in email:", best.num, "with score:", best.score);
+ console.log("Found OTP candidate in email with score:", best.score);
sendToNativeHost({
command: "new_otp",
otp: best.num.replace(/[-\s]/g, ''),
diff --git a/extension/src/shared/native.js b/extension/src/shared/native.js
index 50c24ac..eedc69a 100644
--- a/extension/src/shared/native.js
+++ b/extension/src/shared/native.js
@@ -1,6 +1,34 @@
// Native messaging connection logic
let port = null;
+// Tabs that have asked for an OTP. Delivery is scoped to these tabs only so a
+// code meant for the site the user is logging into can't be harvested by some
+// other tab the user happens to have open.
+// tabId -> { host, ts }
+const requestingTabs = new Map();
+const REQUEST_TTL_MS = 3 * 60 * 1000; // an OTP flow runs ~2 minutes
+
+export function registerOtpRequest(tabId, host) {
+ if (typeof tabId !== 'number') return;
+ requestingTabs.set(tabId, { host: String(host || ''), ts: Date.now() });
+}
+
+export function clearOtpRequest(tabId) {
+ requestingTabs.delete(tabId);
+}
+
+// Tests need to reset the module-level registry between runs.
+export function _resetOtpRequests() {
+ requestingTabs.clear();
+}
+
+function pruneOtpRequests() {
+ const cutoff = Date.now() - REQUEST_TTL_MS;
+ for (const [id, req] of requestingTabs) {
+ if (req.ts < cutoff) requestingTabs.delete(id);
+ }
+}
+
export function connectToNativeHost() {
const hostName = "com.tether.extension";
if (typeof browser !== 'undefined' && browser.runtime && browser.runtime.connectNative) {
@@ -13,7 +41,6 @@ export function connectToNativeHost() {
}
port.onMessage.addListener((message) => {
- console.log("Received message from Tether daemon:", message);
handleNativeMessage(message);
});
@@ -46,18 +73,40 @@ export function sendToNativeHost(message) {
}
}
-// offer the code to tabs one at a time, most-recently-used first, and stop at the
-// first tab that reports it actually filled a field.
+function isValidOtp(value) {
+ return typeof value === 'string' && value.length > 0 && value.length <= 64;
+}
+
+// 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.
export function deliverOtpToTabs(message) {
if (typeof chrome === 'undefined' || !chrome.tabs) return;
+ if (!message || !isValidOtp(message.otp)) return;
+
+ pruneOtpRequests();
chrome.tabs.query({}, function(tabs) {
- const ordered = [...(tabs || [])].sort((a, b) => (b.lastAccessed || 0) - (a.lastAccessed || 0));
+ const byId = new Map((tabs || []).map((t) => [t.id, t]));
+
+ const candidates = [...requestingTabs.entries()]
+ .filter(([id]) => byId.has(id))
+ .sort((a, b) => {
+ const ta = byId.get(a[0]);
+ const tb = byId.get(b[0]);
+ // Prefer the tab the user is actually looking at.
+ if (!!ta.active !== !!tb.active) return ta.active ? -1 : 1;
+ // Then the most recently requesting tab.
+ return (b[1].ts || 0) - (a[1].ts || 0);
+ })
+ .map(([id]) => id);
(function next(i) {
- if (i >= ordered.length) return;
+ if (i >= candidates.length) return;
+ const tabId = candidates[i];
chrome.tabs.sendMessage(
- ordered[i].id,
+ tabId,
{ action: "fill_otp", otp: message.otp, otp_id: message.otp_id },
(response) => {
// Tabs without a content script (about:, the web store, ...) set lastError.
@@ -74,8 +123,9 @@ export function deliverOtpToTabs(message) {
}
function handleNativeMessage(message) {
- // Dispatch native messages to other parts of the extension
- if (message.command === "otp_available" && message.otp) {
+ if (!message || typeof message !== 'object') return;
+ // Only react to the commands we understand; ignore anything else.
+ if (message.command === "otp_available") {
deliverOtpToTabs(message);
}
}
diff --git a/extension/test/native.test.js b/extension/test/native.test.js
index 22430b9..dfb3fe2 100644
--- a/extension/test/native.test.js
+++ b/extension/test/native.test.js
@@ -10,51 +10,85 @@ const mockPort = {
onDisconnect: { addListener: vi.fn() }
};
-beforeEach(() => {
- messageListener = null;
- mockPort.postMessage.mockClear();
-
+// By default the tab reports that it filled the field, so delivery stops there.
+function installChrome(tabs) {
+ global.browser = undefined;
global.chrome = {
runtime: {
connectNative: vi.fn().mockReturnValue(mockPort),
lastError: null
},
tabs: {
- // native.js uses the callback form of query()
- query: vi.fn((_filter, cb) => cb([{ id: 1 }, { id: 2 }, { id: 3 }])),
- sendMessage: vi.fn((_id, _msg, cb) => { if (cb) cb(); })
+ query: vi.fn((_filter, cb) => cb(tabs)),
+ sendMessage: vi.fn((_id, _msg, cb) => { if (cb) cb({ filled: true }); })
}
};
- // Force native.js down the chrome.* branch.
- global.browser = undefined;
+}
+
+beforeEach(() => {
+ messageListener = null;
+ mockPort.postMessage.mockClear();
+ installChrome([{ id: 1 }, { id: 2 }, { id: 3 }]);
});
-import { connectToNativeHost } from '../src/shared/native.js';
+const { connectToNativeHost, registerOtpRequest, _resetOtpRequests } =
+ await import('../src/shared/native.js');
describe('native host receive/routing', () => {
- it('delivers otp_available to every tab, not just the active one', () => {
+ beforeEach(() => _resetOtpRequests());
+
+ it('delivers only to tabs that requested an OTP', () => {
connectToNativeHost();
+ registerOtpRequest(2, 'login.example.com');
expect(messageListener).toBeTypeOf('function');
messageListener({ command: 'otp_available', otp: '123456' });
expect(chrome.tabs.query).toHaveBeenCalledWith({}, expect.any(Function));
- expect(chrome.tabs.sendMessage).toHaveBeenCalledTimes(3);
- for (const id of [1, 2, 3]) {
- expect(chrome.tabs.sendMessage).toHaveBeenCalledWith(
- id,
- { action: 'fill_otp', otp: '123456' },
- expect.any(Function)
- );
- }
+ expect(chrome.tabs.sendMessage).toHaveBeenCalledTimes(1);
+ const [tabId, msg] = chrome.tabs.sendMessage.mock.calls[0];
+ expect(tabId).toBe(2);
+ expect(msg).toMatchObject({ action: 'fill_otp', otp: '123456' });
});
- it('ignores an otp_available event with an empty code', () => {
+ it('prefers the active tab among requesters', () => {
+ installChrome([
+ { id: 1, active: false },
+ { id: 2, active: true },
+ { id: 3, active: false }
+ ]);
connectToNativeHost();
- expect(messageListener).toBeTypeOf('function');
+ registerOtpRequest(1, 'a.example.com');
+ registerOtpRequest(2, 'b.example.com');
+ registerOtpRequest(3, 'c.example.com');
+ messageListener({ command: 'otp_available', otp: '123456', otp_id: 9 });
+
+ const tabIds = chrome.tabs.sendMessage.mock.calls.map((c) => c[0]);
+ expect(tabIds[0]).toBe(2);
+ expect(tabIds).not.toContain(1);
+ expect(tabIds).not.toContain(3);
+ });
+
+ it('does not deliver to any tab when none requested', () => {
+ connectToNativeHost();
+ messageListener({ command: 'otp_available', otp: '123456' });
+ expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('ignores an otp_available event with an empty code', () => {
+ connectToNativeHost();
+ registerOtpRequest(1, 'a.example.com');
messageListener({ command: 'otp_available', otp: '' });
+ expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
+ });
+ it('ignores malformed native messages', () => {
+ connectToNativeHost();
+ registerOtpRequest(1, 'a.example.com');
+ messageListener(null);
+ messageListener('garbage');
+ messageListener({ command: 'something_else', otp: '123456' });
expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
});
});
diff --git a/extension/test/otp-consume.test.js b/extension/test/otp-consume.test.js
index 9992001..2cde438 100644
--- a/extension/test/otp-consume.test.js
+++ b/extension/test/otp-consume.test.js
@@ -7,8 +7,12 @@
// daemon then kept serving that code for the rest of its 5 minute TTL.
//
// The fix moves the consume into the background worker, driven by the tab's reply.
+//
+// A follow-up change also scoped delivery: an OTP is only offered to tabs that
+// requested one (registerOtpRequest), so a background tab with an OTP-shaped
+// input can no longer harvest a code meant for the site the user is logging into.
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { JSDOM } from 'jsdom';
import * as fs from 'fs';
import * as path from 'path';
@@ -48,22 +52,37 @@ function installChrome(tabs) {
};
}
+let nowSpy;
beforeEach(() => {
messageListener = null;
sentToDaemon = [];
messagedTabs = [];
tabResponses = {};
mockPort.postMessage.mockClear();
- installChrome([{ id: 1, lastAccessed: 100 }]);
+
+ // Deterministic, monotonically increasing clock so the "most recently
+ // requested" ordering is stable in these tests.
+ let clock = 0;
+ nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock++);
+
+ installChrome([{ id: 1 }]);
});
-const { connectToNativeHost } = await import('../src/shared/native.js');
+afterEach(() => {
+ nowSpy.mockRestore();
+});
+
+const { connectToNativeHost, registerOtpRequest, _resetOtpRequests } =
+ await import('../src/shared/native.js');
const { handleFillOtp, _resetFilledOtps } = await import('../src/content/autofill.js');
describe('background consumes the OTP on behalf of the filling tab', () => {
+ beforeEach(() => _resetOtpRequests());
+
it('sends consume_otp with the otp_id when a tab reports it filled', () => {
tabResponses[1] = { filled: true };
connectToNativeHost();
+ registerOtpRequest(1, 'login.example.com');
messageListener({ command: 'otp_available', otp: '123456', otp_id: 7 });
@@ -75,6 +94,7 @@ describe('background consumes the OTP on behalf of the filling tab', () => {
it('does not consume when no tab could fill the code', () => {
tabResponses[1] = { filled: false };
connectToNativeHost();
+ registerOtpRequest(1, 'login.example.com');
messageListener({ command: 'otp_available', otp: '123456', otp_id: 7 });
@@ -85,26 +105,35 @@ describe('background consumes the OTP on behalf of the filling tab', () => {
it('stops offering the code once a tab takes it', () => {
installChrome([
- { id: 1, lastAccessed: 100 },
- { id: 2, lastAccessed: 300 }, // most recently used
- { id: 3, lastAccessed: 200 }
+ { id: 1, active: false },
+ { id: 2, active: false },
+ { id: 3, active: false }
]);
+ // Register 1, 3, 2 so tab 2 is the most recently requested.
+ registerOtpRequest(1, 'a.example.com');
+ registerOtpRequest(3, 'c.example.com');
+ registerOtpRequest(2, 'b.example.com');
tabResponses[2] = { filled: true };
connectToNativeHost();
messageListener({ command: 'otp_available', otp: '123456', otp_id: 9 });
- // Most-recently-used first, and nothing after the tab that filled it. The old
- // code blasted every tab, so every open OTP page got the same code.
- expect(messagedTabs.map(t => t.id)).toEqual([2]);
+ // Only the requesting tabs are considered, and nothing after the tab that
+ // filled it. The old code blasted every tab, so every open OTP page got the
+ // same code.
+ expect(messagedTabs.map((t) => t.id)).toEqual([2]);
});
it('falls through to the next tab when the first cannot fill', () => {
installChrome([
- { id: 1, lastAccessed: 300 },
- { id: 2, lastAccessed: 200 },
- { id: 3, lastAccessed: 100 }
+ { id: 1, active: false },
+ { id: 2, active: false },
+ { id: 3, active: false }
]);
+ // Register 3, 2, 1 so tab 1 is the most recently requested.
+ registerOtpRequest(3, 'c.example.com');
+ registerOtpRequest(2, 'b.example.com');
+ registerOtpRequest(1, 'a.example.com');
tabResponses[1] = { filled: false }; // no OTP field here
tabResponses[2] = { filled: true };
connectToNativeHost();
@@ -113,13 +142,14 @@ describe('background consumes the OTP on behalf of the filling tab', () => {
// Unfocused tabs are still reachable - this is what commit 5bad703 fixed and
// it must keep working.
- expect(messagedTabs.map(t => t.id)).toEqual([1, 2]);
+ expect(messagedTabs.map((t) => t.id)).toEqual([1, 2]);
expect(sentToDaemon).toContainEqual({ command: 'consume_otp', otp_id: 11 });
});
it('forwards otp_id to the content script', () => {
tabResponses[1] = { filled: true };
connectToNativeHost();
+ registerOtpRequest(1, 'login.example.com');
messageListener({ command: 'otp_available', otp: '123456', otp_id: 42 });
@@ -128,9 +158,25 @@ describe('background consumes the OTP on behalf of the filling tab', () => {
it('still ignores an otp_available with an empty code', () => {
connectToNativeHost();
+ registerOtpRequest(1, 'login.example.com');
messageListener({ command: 'otp_available', otp: '', otp_id: 3 });
expect(messagedTabs).toHaveLength(0);
});
+
+ it('does not deliver to tabs that never requested an OTP', () => {
+ installChrome([
+ { id: 1, active: false },
+ { id: 2, active: false },
+ { id: 3, active: false }
+ ]);
+ registerOtpRequest(1, 'a.example.com');
+ tabResponses[2] = { filled: true }; // a non-requester that would "accept"
+ connectToNativeHost();
+
+ messageListener({ command: 'otp_available', otp: '123456', otp_id: 5 });
+
+ expect(messagedTabs.map((t) => t.id)).toEqual([1]);
+ });
});
describe('handleFillOtp', () => {
@@ -150,7 +196,7 @@ describe('handleFillOtp', () => {
expect(result).toEqual({ filled: true });
const inputs = [...doc.querySelectorAll('input')];
- expect(inputs.slice(0, 6).map(i => i.value).join('')).toBe('123456');
+ expect(inputs.slice(0, 6).map((i) => i.value).join('')).toBe('123456');
});
it('refuses to fill the same otp_id twice', () => {
@@ -214,4 +260,20 @@ describe('handleFillOtp', () => {
expect(onFilled).toHaveBeenCalledWith(8);
});
+
+ it('does not fill a hidden OTP field', () => {
+ const doc = new JSDOM(
+ '<input type="text" autocomplete="one-time-code" style="display:none">'
+ ).window.document;
+ expect(handleFillOtp(doc, { otp: '123456', otp_id: 1 }).filled).toBe(false);
+ expect(doc.querySelector('input').value).toBe('');
+ });
+
+ it('does not fill when an ancestor is hidden', () => {
+ const doc = new JSDOM(
+ '<div hidden><input type="text" autocomplete="one-time-code"></div>'
+ ).window.document;
+ expect(handleFillOtp(doc, { otp: '123456', otp_id: 1 }).filled).toBe(false);
+ expect(doc.querySelector('input').value).toBe('');
+ });
});