Linux + iPhone Continuity / iMessage / SMS
fix: browser -> mail race to otpcode
Zack Bartel618f37668d62
diff --git a/extension/build.sh b/extension/build.shindex 3c9ec3d..f03dcf8 100755--- a/extension/build.sh+++ b/extension/build.sh@@ -10,7 +10,7 @@ MAIL_DIR="$BUILD_DIR/mail"CHROME_DIR="$BUILD_DIR/chromium"mkdir -p "$BROWSER_DIR/src/background" "$BROWSER_DIR/src/content"-mkdir -p "$MAIL_DIR/src/background" "$MAIL_DIR/src/mail"+mkdir -p "$MAIL_DIR/src/mail"mkdir -p "$CHROME_DIR/src/background" "$CHROME_DIR/src/content"# Bundle Firefox Browser Extension@@ -23,7 +23,6 @@ if [ -d "extension/icons" ]; then cp -R extension/icons "$BROWSER_DIR/"; fi# Bundle Mail Extensionecho "Bundling mail extension..."-npx esbuild extension/src/background/background.js --bundle --outfile="$MAIL_DIR/src/background/background.js"npx esbuild extension/src/mail/extractor.js --bundle --outfile="$MAIL_DIR/src/mail/extractor.js"cp extension/manifest-mail.json "$MAIL_DIR/manifest.json"if [ -d "extension/icons" ]; then cp -R extension/icons "$MAIL_DIR/"; fidiff --git a/extension/manifest-mail.json b/extension/manifest-mail.jsonindex cafc0f4..120f536 100644--- a/extension/manifest-mail.json+++ b/extension/manifest-mail.json@@ -17,7 +17,6 @@],"background": {"scripts": [- "src/background/background.js","src/mail/extractor.js"]},diff --git a/extension/src/background/background.js b/extension/src/background/background.jsindex 1cf249e..c8d7bd5 100644--- a/extension/src/background/background.js+++ b/extension/src/background/background.js@@ -32,7 +32,7 @@ if (typeof chrome !== 'undefined' && chrome.runtime) {}if (request.action === "consume_otp") {- sendToNativeHost({ command: "consume_otp" });+ sendToNativeHost({ command: "consume_otp", otp_id: request.otp_id || 0 });sendResponse({ status: "consumed" });}return true;diff --git a/extension/src/content/autofill.js b/extension/src/content/autofill.jsindex 0b2878d..a6668e4 100644--- a/extension/src/content/autofill.js+++ b/extension/src/content/autofill.js@@ -94,6 +94,57 @@ export function detectSplitOtp(doc) {return null;}+function setNativeValue(el, value) {+ const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value')?.set;+ if (setter) setter.call(el, value);+ else el.value = value;+}++function fireInputEvents(el) {+ const view = el.ownerDocument?.defaultView;+ const Ev = view?.Event || Event;+ el.dispatchEvent(new Ev('input', { bubbles: true }));+ el.dispatchEvent(new Ev('change', { bubbles: true }));+}++// codes this page has already filled+const filledOtpIds = new Set();++export function _resetFilledOtps() { filledOtpIds.clear(); } // tests++// fill `msg.otp` into whatever OTP fields this document has.+export function handleFillOtp(doc, msg, io = {}) {+ const otp = msg?.otp?.toString();+ if (!otp) return { filled: false };++ const id = msg.otp_id || 0;+ if (id && filledOtpIds.has(id)) return { filled: false };++ const splitFields = detectSplitOtp(doc);+ if (splitFields) {+ 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+ fireInputEvents(splitFields[i]);+ }+ if (id) filledOtpIds.add(id);+ io.onFilled?.(id);+ return { filled: true };+ }++ const regularFields = findOtpInputs(doc);+ // fill when empty, or overwrite a stale/partial value+ if (regularFields.length > 0 && regularFields[0].value !== otp) {+ setNativeValue(regularFields[0], otp);+ fireInputEvents(regularFields[0]);+ if (id) filledOtpIds.add(id);+ io.onFilled?.(id);+ return { filled: true };+ }++ return { filled: false };+}+// ---------------------------------------------------------------------------// Browser-only code - only runs when loaded in actual browser context// ---------------------------------------------------------------------------@@ -101,6 +152,8 @@ if (typeof document === 'undefined') {// Test environment: skip browser-only code} else {let otpInterval = null;+// last code id this page was offered+let lastSeenOtpId = 0;function requestOtp() {chrome.runtime.sendMessage({@@ -109,18 +162,8 @@ function requestOtp() {});}-// Tell the daemon the code was used so it isn't re-served to the next page.-function consumeOtp() {- chrome.runtime.sendMessage({ action: "consume_otp" });-}--// React/Vue track input values via the prototype's value setter, so a plain-// `el.value = x` is ignored and reverted on re-render. Go through the native-// setter so controlled inputs actually register the change.-function setNativeValue(el, value) {- const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value')?.set;- if (setter) setter.call(el, value);- else el.value = value;+function consumeOtp(otpId) {+ chrome.runtime.sendMessage({ action: "consume_otp", otp_id: otpId || 0 });}function hasOtpFields() {@@ -141,11 +184,12 @@ function startOtpFlow() {const splits = detectSplitOtp(document);const regular = findOtpInputs(document);- // Stop trying after 2 minutes or if the user manually filled the field- if (attempts > 60 ||- (splits && splits[0].value !== "") ||- (regular.length > 0 && regular[0].value.length > 3)) {+ // stop trying after 2 minutes or if the user manually filled the field+ const userFilled = (splits && splits[0].value !== "") ||+ (regular.length > 0 && regular[0].value.length > 3);+ if (attempts > 60 || userFilled) {clearInterval(otpInterval);+ if (userFilled) consumeOtp(lastSeenOtpId);return;}requestOtp();@@ -156,8 +200,6 @@ const otpPresentAtLoad = hasOtpFields();if (otpPresentAtLoad) {startOtpFlow();} else {- // The OTP field often renders after load (SPA route, or after the user enters- // their email/phone). Watch for it instead of only checking once at load.const observer = new MutationObserver(() => {if (hasOtpFields()) {observer.disconnect();@@ -169,40 +211,17 @@ if (otpPresentAtLoad) {setTimeout(() => observer.disconnect(), 120000);}-// Listen for OTPs sent from the daemon+// listen for OTPs sent from the daemonchrome.runtime.onMessage.addListener((request, sender, sendResponse) => {- if (request.action === "fill_otp" && request.otp) {- const otp = request.otp.toString();- const splitFields = detectSplitOtp(document);-- if (splitFields) {- console.log("Autofilling split OTP:", otp);- for (let i = 0; i < Math.min(otp.length, splitFields.length); i++) {- setNativeValue(splitFields[i], otp[i]);-- // Dispatch events so React/Vue/Angular pick up the change- splitFields[i].dispatchEvent(new Event('input', { bubbles: true }));- splitFields[i].dispatchEvent(new Event('change', { bubbles: true }));- }+ if (request.action !== "fill_otp") return;++ lastSeenOtpId = request.otp_id || lastSeenOtpId;+ const result = handleFillOtp(document, request, {+ onFilled: () => {if (otpInterval) clearInterval(otpInterval);- consumeOtp();- } else {- const regularFields = findOtpInputs(document);- // Fill when empty, or overwrite a stale/partial value — but skip if the code- // is already present to avoid redundant re-fills and event storms.- if (regularFields.length > 0 && regularFields[0].value !== otp) {- console.log("Autofilling OTP:", otp);- setNativeValue(regularFields[0], otp);-- // Dispatch events so React/Vue/Angular pick up the change- regularFields[0].dispatchEvent(new Event('input', { bubbles: true }));- regularFields[0].dispatchEvent(new Event('change', { bubbles: true }));-- // Clean up the interval- if (otpInterval) clearInterval(otpInterval);- consumeOtp();- }}- }+ });+ if (result.filled) console.log("Autofilled OTP:", request.otp);+ sendResponse(result);});}diff --git a/extension/src/mail/extractor.js b/extension/src/mail/extractor.jsindex d6aa194..4752eb7 100644--- a/extension/src/mail/extractor.js+++ b/extension/src/mail/extractor.js@@ -1,9 +1,9 @@// Mail script for Thunderbird/Betterbird// This script extracts OTP codes from emails-import { connectToNativeHost, sendToNativeHost } from '../shared/native.js';--connectToNativeHost();+// single entry point for the mail extension+import '../background/background.js';+import { sendToNativeHost } from '../shared/native.js';const OTP_CONTEXT_KEYWORDS = ['code', 'otp', 'one-time', 'verification', 'confirm', 'passcode',@@ -47,6 +47,17 @@ function pruneOldSeen() {// Run pruning every minute so the Map doesn't grow foreversetInterval(pruneOldSeen, 60_000);+// distance from `target` to the closest occurrence of `needle` in `haystack`.+function nearestDistance(haystack, needle, target) {+ let best = Infinity;+ for (let i = haystack.indexOf(needle); i !== -1; i = haystack.indexOf(needle, i + 1)) {+ const d = Math.abs(target - i);+ if (d < best) best = d;+ if (i > target) break; // occurrences are ordered; past the target we only get worse+ }+ return best;+}+export function scoreCandidate(num, surroundingText) {let score = 0;// Squash whitespace for accurate proximity and keyword matching@@ -55,16 +66,12 @@ export function scoreCandidate(num, surroundingText) {const numIndex = lower.indexOf(num.toLowerCase());for (const kw of OTP_CONTEXT_KEYWORDS) {- if (lower.includes(kw)) {- score += 10;-- // Proximity bonus: keyword within 30 chars of the number- if (numIndex !== -1) {- const kwIndex = lower.indexOf(kw);- if (Math.abs(numIndex - kwIndex) <= 30) {- score += 20;- }- }+ if (lower.indexOf(kw) === -1) continue;+ score += 10;++ // proximity bonus: keyword within 30 chars of the number+ if (numIndex !== -1 && nearestDistance(lower, kw, numIndex) <= 30) {+ score += 20;}}@@ -283,7 +290,7 @@ if (typeof messenger !== 'undefined') {try {let page = await messenger.messages.query({ fromDate: since });- while (page) {+ while (page && Array.isArray(page.messages)) {for (const message of page.messages) {if (hasSeen(message.id)) continue;markSeen(message.id);diff --git a/extension/src/shared/native.js b/extension/src/shared/native.jsindex 5e7b570..50c24ac 100644--- a/extension/src/shared/native.js+++ b/extension/src/shared/native.js@@ -46,20 +46,36 @@ 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.+export function deliverOtpToTabs(message) {+ if (typeof chrome === 'undefined' || !chrome.tabs) return;++ chrome.tabs.query({}, function(tabs) {+ const ordered = [...(tabs || [])].sort((a, b) => (b.lastAccessed || 0) - (a.lastAccessed || 0));++ (function next(i) {+ if (i >= ordered.length) return;+ chrome.tabs.sendMessage(+ ordered[i].id,+ { action: "fill_otp", otp: message.otp, otp_id: message.otp_id },+ (response) => {+ // Tabs without a content script (about:, the web store, ...) set lastError.+ void chrome.runtime.lastError;+ if (response && response.filled) {+ sendToNativeHost({ command: "consume_otp", otp_id: message.otp_id });+ } else {+ next(i + 1);+ }+ }+ );+ })(0);+ });+}+function handleNativeMessage(message) {// Dispatch native messages to other parts of the extensionif (message.command === "otp_available" && message.otp) {- // Deliver to every tab; the content script only fills when the page actually- // has OTP fields, so we don't depend on which tab happens to be focused.- if (typeof chrome !== 'undefined' && chrome.tabs) {- chrome.tabs.query({}, function(tabs) {- for (const tab of tabs) {- chrome.tabs.sendMessage(tab.id, { action: "fill_otp", otp: message.otp }, () => {- // Ignore tabs without a content script listening.- void chrome.runtime.lastError;- });- }- });- }+ deliverOtpToTabs(message);}}diff --git a/extension/test/otp-consume.test.js b/extension/test/otp-consume.test.jsnew file mode 100644index 0000000..9992001--- /dev/null+++ b/extension/test/otp-consume.test.js@@ -0,0 +1,217 @@+// Regression tests for the OTP double-consumption bug.+//+// Symptom: A.com autofills correctly and the user logs in; later B.com is opened+// and gets A.com's code injected. Cause: consumeOtp() was sent from the content+// script, but filling dispatches input/change, the site auto-submits, and the+// navigation destroys the content script before the message is delivered. The+// 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.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { JSDOM } from 'jsdom';+import * as fs from 'fs';+import * as path from 'path';++const loadFixture = (filename) => {+ const html = fs.readFileSync(path.join(__dirname, 'fixtures', filename), 'utf8');+ return new JSDOM(html).window.document;+};++// --- native.js harness ------------------------------------------------------+// Captures the daemon->extension listener and the messages sent back to the daemon.+let messageListener = null;+let sentToDaemon = [];+let tabResponses = {}; // tabId -> { filled } handed back to sendMessage's callback+let messagedTabs = [];++const mockPort = {+ postMessage: vi.fn((msg) => sentToDaemon.push(msg)),+ onMessage: { addListener: vi.fn((cb) => { messageListener = cb; }) },+ onDisconnect: { addListener: vi.fn() }+};++function installChrome(tabs) {+ global.browser = undefined;+ global.chrome = {+ runtime: {+ connectNative: vi.fn().mockReturnValue(mockPort),+ lastError: null+ },+ tabs: {+ query: vi.fn((_filter, cb) => cb(tabs)),+ sendMessage: vi.fn((id, msg, cb) => {+ messagedTabs.push({ id, msg });+ if (cb) cb(tabResponses[id]);+ })+ }+ };+}++beforeEach(() => {+ messageListener = null;+ sentToDaemon = [];+ messagedTabs = [];+ tabResponses = {};+ mockPort.postMessage.mockClear();+ installChrome([{ id: 1, lastAccessed: 100 }]);+});++const { connectToNativeHost } = 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', () => {+ it('sends consume_otp with the otp_id when a tab reports it filled', () => {+ tabResponses[1] = { filled: true };+ connectToNativeHost();++ messageListener({ command: 'otp_available', otp: '123456', otp_id: 7 });++ // This is the whole bug: the content script cannot be relied on to send this,+ // because filling the field navigates the page away.+ expect(sentToDaemon).toContainEqual({ command: 'consume_otp', otp_id: 7 });+ });++ it('does not consume when no tab could fill the code', () => {+ tabResponses[1] = { filled: false };+ connectToNativeHost();++ messageListener({ command: 'otp_available', otp: '123456', otp_id: 7 });++ expect(sentToDaemon).not.toContainEqual(+ expect.objectContaining({ command: 'consume_otp' })+ );+ });++ 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 }+ ]);+ 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]);+ });++ 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 }+ ]);+ tabResponses[1] = { filled: false }; // no OTP field here+ tabResponses[2] = { filled: true };+ connectToNativeHost();++ messageListener({ command: 'otp_available', otp: '123456', otp_id: 11 });++ // 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(sentToDaemon).toContainEqual({ command: 'consume_otp', otp_id: 11 });+ });++ it('forwards otp_id to the content script', () => {+ tabResponses[1] = { filled: true };+ connectToNativeHost();++ messageListener({ command: 'otp_available', otp: '123456', otp_id: 42 });++ expect(messagedTabs[0].msg).toEqual({ action: 'fill_otp', otp: '123456', otp_id: 42 });+ });++ it('still ignores an otp_available with an empty code', () => {+ connectToNativeHost();+ messageListener({ command: 'otp_available', otp: '', otp_id: 3 });+ expect(messagedTabs).toHaveLength(0);+ });+});++describe('handleFillOtp', () => {+ beforeEach(() => _resetFilledOtps());++ it('fills a single field and reports filled', () => {+ const doc = loadFixture('std-autocomplete.html');+ const result = handleFillOtp(doc, { otp: '123456', otp_id: 1 });++ expect(result).toEqual({ filled: true });+ expect(doc.querySelector('input').value).toBe('123456');+ });++ it('fills split fields character by character', () => {+ const doc = loadFixture('split-otp.html');+ const result = handleFillOtp(doc, { otp: '123456', otp_id: 1 });++ expect(result).toEqual({ filled: true });+ const inputs = [...doc.querySelectorAll('input')];+ expect(inputs.slice(0, 6).map(i => i.value).join('')).toBe('123456');+ });++ it('refuses to fill the same otp_id twice', () => {+ const doc = loadFixture('std-autocomplete.html');+ expect(handleFillOtp(doc, { otp: '123456', otp_id: 5 }).filled).toBe(true);++ // The daemon replays the code on a service-worker restart (net.cpp subscribe+ // handler). Refilling causes event storms on controlled React inputs.+ doc.querySelector('input').value = '';+ expect(handleFillOtp(doc, { otp: '123456', otp_id: 5 }).filled).toBe(false);+ expect(doc.querySelector('input').value).toBe('');+ });++ it('overwrites a stale value when a NEW code arrives', () => {+ const doc = loadFixture('std-autocomplete.html');+ handleFillOtp(doc, { otp: '111111', otp_id: 1 });+ expect(doc.querySelector('input').value).toBe('111111');++ // Guards the behaviour introduced by 5bad703: a fresh code must replace a stale+ // field value without the user clearing it first.+ const result = handleFillOtp(doc, { otp: '222222', otp_id: 2 });+ expect(result).toEqual({ filled: true });+ expect(doc.querySelector('input').value).toBe('222222');+ });++ it('reports not-filled when the code is already present', () => {+ const doc = loadFixture('std-autocomplete.html');+ doc.querySelector('input').value = '123456';++ expect(handleFillOtp(doc, { otp: '123456', otp_id: 1 }).filled).toBe(false);+ });++ it('reports not-filled when the page has no OTP fields', () => {+ const doc = new JSDOM('<input type="password" name="pw">').window.document;+ expect(handleFillOtp(doc, { otp: '123456', otp_id: 1 }).filled).toBe(false);+ });++ it('ignores an empty or missing code', () => {+ const doc = loadFixture('std-autocomplete.html');+ expect(handleFillOtp(doc, { otp: '', otp_id: 1 }).filled).toBe(false);+ expect(handleFillOtp(doc, {}).filled).toBe(false);+ });++ it('dispatches input and change so framework-controlled inputs update', () => {+ const doc = loadFixture('std-autocomplete.html');+ const input = doc.querySelector('input');+ const seen = [];+ input.addEventListener('input', () => seen.push('input'));+ input.addEventListener('change', () => seen.push('change'));++ handleFillOtp(doc, { otp: '123456', otp_id: 1 });++ expect(seen).toEqual(['input', 'change']);+ });++ it('invokes onFilled so the caller can stop its poll loop', () => {+ const doc = loadFixture('std-autocomplete.html');+ const onFilled = vi.fn();++ handleFillOtp(doc, { otp: '123456', otp_id: 8 }, { onFilled });++ expect(onFilled).toHaveBeenCalledWith(8);+ });+});diff --git a/test/test_otp.cpp b/test/test_otp.cppnew file mode 100644index 0000000..4a615f5--- /dev/null+++ b/test/test_otp.cpp@@ -0,0 +1,141 @@+#include <gtest/gtest.h>+#include <tether/otp.hpp>++using namespace tether;++namespace {+ class OtpTest : public ::testing::Test {+ protected:+ void SetUp() override { otp_reset(); }+ void TearDown() override { otp_reset(); }++ OtpClock::time_point t0 = OtpClock::now();+ };+} // namespace++TEST_F(OtpTest, EmptyVaultServesNothing) {+ EXPECT_FALSE(otp_peek(t0));+ EXPECT_FALSE(otp_take_for_host("a.com", t0));+ EXPECT_FALSE(otp_is_claimed());+}++TEST_F(OtpTest, StoreAndPeek) {+ uint64_t id = otp_store("123456", t0);+ EXPECT_NE(id, 0u);++ Otp got = otp_peek(t0);+ EXPECT_TRUE(got);+ EXPECT_EQ(got.code, "123456");+ EXPECT_EQ(got.id, id);+}++TEST_F(OtpTest, IdsAreUniqueAndIncreasing) {+ 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);+ EXPECT_FALSE(otp_peek(t0));+}++TEST_F(OtpTest, ExpiresAfterTtl) {+ 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.+ EXPECT_FALSE(otp_peek(t0));+}++// 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 a = otp_take_for_host("a.com", t0);+ ASSERT_TRUE(a);+ EXPECT_EQ(a.code, "123456");+ EXPECT_TRUE(otp_is_claimed());++ EXPECT_FALSE(otp_take_for_host("b.com", t0)) << "b.com must not receive a.com's code";+}++TEST_F(OtpTest, ClaimingHostKeepsPollingSuccessfully) {+ 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);+ EXPECT_TRUE(again);+ EXPECT_EQ(again.code, "123456");+}++TEST_F(OtpTest, NewCodeResetsTheClaim) {+ 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);+ EXPECT_FALSE(otp_is_claimed());+ Otp b = otp_take_for_host("b.com", t0);+ ASSERT_TRUE(b);+ EXPECT_EQ(b.code, "222222");+}++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);+ 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);+ ASSERT_TRUE(otp_take_for_host("a.com", t0));+ EXPECT_FALSE(otp_take_for_host("", t0));+}++TEST_F(OtpTest, ConsumeClearsMatchingId) {+ uint64_t id = otp_store("123456", t0);+ otp_consume(id);+ EXPECT_FALSE(otp_peek(t0));+}++// 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);++ otp_consume(first);++ Otp got = otp_peek(t0);+ ASSERT_TRUE(got);+ EXPECT_EQ(got.code, "222222");+ EXPECT_EQ(got.id, second);+}++TEST_F(OtpTest, ConsumeWithoutIdClearsUnconditionally) {+ // Backwards compatibility with extension builds that predate otp_id.+ otp_store("123456", t0);+ otp_consume(0);+ EXPECT_FALSE(otp_peek(t0));+}++TEST_F(OtpTest, ConsumeIsIdempotent) {+ 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);+ uint64_t id = otp_take_for_host("a.com", t0).id;+ otp_consume(id);+ EXPECT_FALSE(otp_is_claimed());+}