\nHallo, \n \ngeben Sie bitte den folgenden Best&au...",
+ "body": "Bitte bestätigen Sie Ihre E-Mail-Adresse\n\nGuten Tag,\n\ngeben Sie bitte den folgenden Bestätigungscode in das Eingabefenster ein, das Ihnen angezeigt wird:\n\nF17DC\n\nZu Ihrer eigenen Sicherheit können wir so feststellen, dass die von Ihnen genannte E-Mail-Adresse korrekt ist und Sie Zugriff auf das Postfach haben.\nFalls Sie nicht fortfahren wollen, können Sie diese E-Mail einfach ignorieren.\n\nMit freundlichen Grüßen\nIhre Telekom\n\n© 2026 Telekom Deutschland GmbH\n\nDatenschutz | gesetzliche Pflichtangaben \nDies ist eine automatisch generierte Nachricht, bitte antworten Sie nicht auf diese E-Mail.",
+ "code": "F17DC"
+ },
+ {
+ "sender": "Slack",
+ "subject": "Slack confirmation code: 6ZA-BRE",
+ "preview": "Confirm your email address\n\nHere’s your confirmation code. You can copy it into the open browser window or click the link below to confirm this email address.\n\n6ZA-BRE\n\nConfirm and Sign In [https://go.slack.com/link?t=0f3a9c21",
+ "body": "Confirm your email address. Here’s your confirmation code. You can copy it into the open browser window or click the link below to confirm this email address.\n \u200c \u200c \u200c \u200c \u200c \u200c \nConfirm your email address\n Here’s your confirmation code. You can copy it into the open browser window or click the link below to confirm this email address.\n6ZA-BRE\nConfirm and Sign In \nIf you didn’t request this email, there’s nothing to worry about — you can safely ignore it.\nOur Blog | Policies | Help Center | Slack Community \n\n©2026 Slack Technologies, LLC, a Salesforce company.\n415 Mission Street, 3rd Floor, San Francisco, CA 94105\n\nAll rights reserved.",
+ "code": "6ZA-BRE"
+ },
+ {
+ "sender": "LinkedIn",
+ "subject": "Here's your verification code 001029",
+ "preview": "Hi Alex,\n\nEnter the 6-digit code below to verify your identity and regain access to your LinkedIn account.\n\n001029\n\nThanks for helping us keep your account secure.\n\nThe LinkedIn Team\n\n----------------------------------------\n\nThis email was intended fo...",
+ "body": "Please verify it's you.\n \u034f \u034f \u034f \u034f \u034f \u034f \nEnter the 6-digit code below to verify your identity and regain access to your LinkedIn account.\n001029\nThanks for helping us keep your account secure.\nThe LinkedIn Team\nWhen and where this happened:\nDate: August 28, 2026 at 7:54 PM GMT\nOperating System: Windows\nBrowser: Firefox\nApproximate Location: Wolfenbuttel, Niedersachsen, Germany\n Never miss an update with the LinkedIn app\n This email was intended for Alex Muster (“Jack of all trades, master of none, but oftentimes better than a master of one.”)\nLearn why we included this. \nYou are receiving LinkedIn notification emails.\nHelp \n Don’t share it with others.\nAmazon.de is a trading name for Amazon EU Sarl, for Amazon Europe Core Sarl, for Amazon Media EU Sarl and for Amazon EU Sarl, all of which have their registered office at 38 avenue John F. Kennedy, L-1855 Luxembourg and for the Amazon Digital Germany GmbH, with registered office at Domagkstr. 28, 80807 Munich, Germany. ©2026 Amazon.com, Inc. or its affiliates. Amazon and all ",
+ "code": "331543"
+ },
+ {
+ "sender": "Telekom Login",
+ "subject": "Ihr Bestätigungscode",
+ "preview": "img{display:block}#outlook a{padding:0}body{width:100%!important} body{-webkit-text-size-adjust:none}a a:link,a:visited{color:#369;font-weight:400;text-decoration:underline}.footerTable--hintText a,.footerTable--lastRowLinks a,.postContentDisclaimer a,i...",
+ "body": "Guten Tag,\n geben Sie den folgenden Bestätigungscode in das Eingabefeld auf der aktuellen Seite Ihres Browsers ein:\n311213\n Geben Sie diesen Code nicht an andere weiter. Durch die Eingabe bestätigen Sie, dass diese E-Mail-Adresse korrekt ist und Sie Zugriff auf das Postfach haben.\n Falls Sie diese Aktion nicht selbst veranlasst haben, können Sie diese E-Mail einfach ignorieren und müssen nichts weiter tun.\n Freundliche Grüße\n Ihre Telekom\n Die gesetzlichen Pflichtangaben finden Sie unter:\nwww.telekom.de/pflichtangaben \n 2-KO-IAM-AM2-1\nTelekom Deutschland GmbH\nHilfe & Service Datenschutz weiter.\nkleinanzeigen.de GmbH, Dernburgstrasse 50, 14057 Berlin, Deutschland \n Geschäftsführer: Paul Heimann, HRB-Nr.: 272623 B,\n Amtsgericht Charlottenburg, Sitz der Gesellschaft: Berlin\nAllgemein",
+ "code": "704626"
+ },
+ {
+ "sender": "TikTok Shop",
+ "subject": "TikTok Shop Partner Center verification code",
+ "preview": "Dear Partner,\nTo verify your account, enter this code in TikTok Shop :\n 24VURS\nVerification codes expire after 2 hours.\nDo not forward or give this code to anyone.\nThis is an automatically generated email. Replies to this email address aren't monitored....",
+ "body": "Dear Partner,\nTo verify your account, enter this code in TikTok Shop :\n24VURS\nVerification codes expire after 2 hours.\nDo not forward or give this code to anyone.\nThis is an automatically generated email. Replies to this email address aren't monitored.\n\nBest regards,\nTikTok Shop Partner Center",
+ "code": "24VURS"
+ },
+ {
+ "sender": "Steam",
+ "subject": "Ihr Steam-Account: Zugriff von einem neuen Web- oder Mobilgerät",
+ "preview": "\nHallo alexm,\n\nEs scheint, als ob Sie versuchen, sich über ein neues Gerät anzumelden. Bitte\nverwenden Sie den folgenden Steam-Guard-Code, um auf Ihren Account zuzugreifen:\n\nAnfrage von\nCalifornia, Vereinigte Staaten von Amerika\n\nAnmeldecode\nY9DG...",
+ "body": "alexm,\nEs scheint, als ob Sie versuchen, sich über ein neues Gerät anzumelden. Bitte verwenden Sie den folgenden Steam-Guard-Code, um auf Ihren Account zuzugreifen:\n Anfrage von\n California, Vereinigte Staaten von Amerika\n Y9DGP\n\nDas waren nicht Sie?\nDiese E-Mail wurde gesendet, weil jemand versucht hat, sich auf Ihrem Steam-Account anzumelden. Beim Anmeldeversuch wurde der korrekte Name und das korrekte Passwort Ihres Accounts verwendet.\n\n Falls dieser Anmeldeversuch nicht von Ihnen vorgenommen wurde, sollten Sie Ihr Steam-Passwort umgehend zurücksetzen .\n\n Der in dieser E-Mail enthaltene Anmeldecode wird benötigt, um auf Ihren Account zuzugreifen. Teilen Sie diese",
+ "code": "Y9DGP"
+ },
+ {
+ "sender": "Google",
+ "subject": "Google-Bestätigungscode",
+ "preview": "Google-Bestätigungscode\n\n\n\n\n\n\n\n\n\nLieber Google-Nutzer,\n\nwir haben eine Anfrage für den Zugriff auf Ihr Google-Konto \nalex@example.org über Ihre E-Mail-Adresse erhalten. Ihr \nGoogle-Bestätigungscode lautet:\n\n\n067647\n\n\nFalls Sie diesen Code ...",
+ "body": "Google-Bestätigungscode\nLieber Google-Nutzer,\nwir haben eine Anfrage für den Zugriff auf Ihr Google-Konto alex@example.org über Ihre E-Mail-Adresse erhalten. Ihr Google-Bestätigungscode lautet:\n067647\nFalls Sie diesen Code nicht angefordert haben, versucht möglicherweise eine andere Person, auf das Google-Konto alex@example.org zuzugreifen. Geben Sie diesen Code nicht weiter.\nSie haben diese Nachricht erhalten, weil diese E-Mail-Adresse als Wiederherstellungs-E-Mail-Adresse für das Google-Konto alex@example.org angegeben wurde. Sollte dies nicht stimmen, klicken Sie bitte hier , um Ihre E-Mail-Adresse aus diesem Google-Konto zu entfernen.\nMit ",
+ "code": "067647"
+ },
+ {
+ "sender": "ChatGPT",
+ "subject": "Your temporary ChatGPT login code",
+ "preview": "\nEnter this temporary verification code to continue:\n714810\nIf you were not trying to log in to ChatGPT, please reset your password.\n\nBest,\nThe ChatGPT team\n\n ChatGPT\nHelp center\n",
+ "body": "Enter this temporary verification code to continue:\n 714810\n If you were not trying to log in to ChatGPT, please reset your password .\n\nBest,\nThe ChatGPT team\nChatGPT \nHelp center ",
+ "code": "714810"
+ },
+ {
+ "sender": "Facebook",
+ "subject": "86771674 ist dein Facebook-Code.",
+ "preview": "Hallo Alex,\n\nNur noch ein Schritt, um dein Konto zu verifizieren\n\nHallo Alex,Wir haben von jemandem, der Facebook verwendet, eine Anfrage zur Verifizierung deines Kontos erhalten. Gib diesen Code ein:86771674Teile diesen Code mit niemandem.Wenn dich j...",
+ "body": "Alex, nur noch ein Schritt, um dein Konto zu verifizieren.\nAlex Muster\nNur noch ein Schritt, um dein Konto zu verifizieren\nHallo Alex,\nWir haben von jemandem, der Facebook verwendet, eine Anfrage zur Verifizierung deines Kontos erhalten. Gib diesen Code ein:\n86771674\nTeile diesen Code mit niemandem.\n\nWenn dich jemand nach diesem Code fragt\nTeile diesen Code mit niemandem, insbesondere nicht, wenn dir die Person sagt, dass sie für Facebook oder Meta arbeitet. Möglicherweise handelt es sich um einen Versuch, dein Konto zu hacken.\n\nDie Anfrage kam nicht von dir?\nWenn du diese E-Mail erhalten hast, aber gar nicht versuchst, dein Konto zu verifizieren, teile uns das mit . Solange du diesen Code mit niemandem tei",
+ "code": "86771674"
+ },
+ {
+ "sender": "Autodesk",
+ "subject": "Einmaliger Passcode",
+ "preview": "Autodesk ( https://u51843908.ct.sendgrid.net/link?t=0f3a9c21",
+ "body": "Einmaliger Passcode\n Hi Alex Muster!\n\n Geben Sie den einmaligen Passcode ein, um die Aktion für Ihr Autodesk-Konto abzuschließen.\n\nCode:\n747189\n\nGeben Sie diesen Code nicht an Dritte weiter und leiten Sie diese E-Mail nicht weiter.\nAutodesk, Inc. • One Market, Ste. 400 San Francisco, CA 94105, USA\n© Autodesk, Inc. All rights reserved. Rechtliche Hinweise & Marken . Autodesk-Datenschutzerklärung \nDies ist eine vertragsrelevante E-Mail.\nAntworten Sie nicht auf diese E-Mail. Antworten auf diese E-Mail werden weder gelesen noch beantwortet.\nAutodesk und das Autodesk-Logo sind in den USA und/ode",
+ "code": "747189"
+ },
+ {
+ "sender": "Booking.com",
+ "subject": "Booking.com\u00a0– HUK6QR ist Ihr Bestätigungscode",
+ "preview": " Booking.com\n\nE-Mail-Adresse bestätigen\n\n Guten Tag alex@example.org,\n\n Dies ist Ihr individueller Code, mit dem Sie Ihre E-Mail-Adresse\n bestätigen können..\n HUK6QR\n\n Bitte beachten Sie, dass dieser Code nur einmal verwendet werden kann...",
+ "body": "E-Mail-Adresse bestätigen\nGuten Tag alex@example.org,\nDies ist Ihr individueller Code, mit dem Sie Ihre E-Mail-Adresse bestätigen können..\nHUK6QR\n Bitte beachten Sie, dass dieser Code nur einmal verwendet werden kann und nach 10 Minuten verfällt. Geben Sie den Code nicht an Dritte weiter.\nWenn Sie keinen Bestätigungscode für alex@example.org angefordert haben, können Sie diese E-Mail ignorieren.\n Urheberrecht © 1996–2026 Booking.com. Alle Rechte vorbehalten.\n Diese E-Mail wurde von Booking.com gesendet, Oosterdokskade 163, 1011 DL Amsterdam, Niederlande\nDatenschutz und Cookies | Kundenservice ",
+ "code": "HUK6QR"
+ },
+ {
+ "sender": "Instagram",
+ "subject": "557 260 is your Instagram recovery code",
+ "preview": "\u00a0\u00a0\u00a0\u00a0Hi alex.muster,\nHere are three easy ways to get back into Instagram.\n\u00a0\u00a0\u00a0\u00a0Log\u00a0in\u00a0without\u00a0password\u00a0\u00a0\u00a0\u00a0Reset\u00a0your\u00a0password\u00a0\u00a0\u00a0\u00a0\u00a0Or use this code in the app:557 260If you didn’t request a login link or a password reset, you can ign...",
+ "body": "Hi alex.muster,\nHere are three easy ways to get back into Instagram.\nLog in without password \nReset your password \nOr use this code in the app:\n557 260\nIf you didn’t request a login link or a password reset, you can ignore this message and learn more about why you may have received it .\n\nOnly people who know your Instagram password or click the login link in this email can log into your account.\n\n© Instagram. Meta Platforms, Inc., 1601 Willow Road, Menlo Park, CA 94025\nThis message was sent to alex@example.org and intended for alex.muster. Not your profile? Remove your email from this account.",
+ "code": "557260"
+ },
+ {
+ "sender": "STACKIT",
+ "subject": "Verify your email",
+ "preview": "Verify your email. Dear STACKIT customer, To verify your email and activate your account, click to the button below. Verify your email or use the temporary code below Verification code 08MPI6 This code is valid for 1 h. from the time this email was sent...",
+ "body": "Verify your email\nDear STACKIT customer,\nTo verify your email and activate your account, click to the button below.\nVerify your email \nor use the temporary code below\nVerification code\n08MPI6\nThis code is valid for 1 h from the time this email was sent.\nBest regards\nYour STACKIT team\nSTACKIT – EINFACH. SICHER. STABIL.\nSTACKIT GmbH & Co. KG - Stiftsbergstraße 1 D-74172 Neckarsulm\nView our data privacy policy. ",
+ "code": "08MPI6"
+ },
+ {
+ "sender": "Schramme Media",
+ "subject": "123277 — E-Mail-Adresse bestätigen · Schramme Media & Development",
+ "preview": "Hallo test,\n\nvielen Dank für deine Registrierung bei Schramme Media & Development. Bitte bestätige deine E-Mail-Adresse mit folgendem Code:\n\nCode: 123277\n\nDieser Code ist 15 Minuten gültig. Falls du diese Aktion nicht angefordert hast, ignoriere dies...",
+ "body": "Schramme Media & Development\nE-Mail-Adresse bestätigen\nHallo test,\nvielen Dank für deine Registrierung bei Schramme Media & Development. Bitte bestätige deine E-Mail-Adresse mit folgendem Code:\n 123277\n Dieser Code ist 15 Minuten gültig. Falls du diese Aktion nicht angefordert hast, kannst du diese E-Mail ignorieren.",
+ "code": "123277"
+ },
+ {
+ "sender": "UNiDAYS",
+ "subject": "292326 ist dein UNiDAYS-Passcode",
+ "preview": "EINMALIGER PASSCODE\n\n292326\n\nHier ist dein Passcode.\n\n----------------------------------------\n\nWenn du Hilfe zu deiner UNiDAYS-iD benötigst, wende dich bitte an Support https://www.myunidays.com/link?t=0f3a9c21",
+ "body": "Einmaliger Passcode\n292326\nHier ist dein Passcode.\nWenn du Hilfe zu deiner UNiDAYS-iD benötigst, wende dich bitte an Support ",
+ "code": "292326"
+ },
+ {
+ "sender": "Amazon Visa",
+ "subject": "Bestätigungscode",
+ "preview": "\n\n\n\n \n \n \n Du hast noch Fragen? Weite",
+ "code": "1699"
+ },
+ {
+ "sender": "Klarna",
+ "subject": "093761 is your 6-digit code",
+ "preview": "093761 is your 6-digit code\n\nhttps://www.klarna.com/link?t=0f3a9c21\n\n\u00a0\n\n\nYour 6-digit code\n\n\u00a0\n\nHi, your 6-digit code is:\n\n\u00a0\n\n093761\n\n\u00a0\n\nUse this code to complete the verification process in the app or website.\n\n\u00a0\n\nDo not share this code. Klarna representatives wi...",
+ "body": "093761 is your 6-digit code\nYour 6-digit code\nHi, your 6-digit code is:\n093761\n Use this code to complete the verification process in the app or website.\nDo not share this code. Klarna representatives will never reach out to you to verify this code over the phone or SMS.\nThe code is valid for 10 minutes.\n Fraudsters may pretend to be Klarna. Never share login details or codes.\nDidn't request a verification code?\n If you suspect someone else requested this code, lock your account immediately.\nHave a question?\nGet 24/7 support and find answers to your questions with our customer service assistant.\nChat with us \nKlarn",
+ "code": "093761"
+ },
+ {
+ "sender": "KI Palooza",
+ "subject": "Your Login Passcode for KI Palooza 2026",
+ "preview": " \u00a0 \u00a0Hey a a!\nWillkommen zur KI Palooza 2026\nDein Passcode\n551471\nKI Palooza 2026 Sep 29 2026 - Sep 30 2026\nHallo a a,\n\n\nWir schreiben dir weil wir eine Anfrage zur Anmeldung zu deinem Konto bekommen haben. Verwende den untenstehenden Passcode um dich ...",
+ "body": "Hey a a!\nWillkommen zur KI Palooza 2026\nDein Passcode\n551471\nKI Palooza 2026\nSep 29 2026 - Sep 30 2026\nHallo a a,\n\nWir schreiben dir weil wir eine Anfrage zur Anmeldung zu deinem Konto bekommen haben. Verwende den untenstehenden Passcode um dich in der App einzuloggen.\nDein Passcode ist\n551471\nDein QR Code\n\nPrüfe dein Profil und lege los!\nZu deinem Profil \nDownload KI Palooza 2026 Mobile App for\niOS and Android\nMake sure you download KI Palooza 2026 app. Easily connect with other attendees, view event schedules, speakers, get news updates, bookmark your favourites, and post on social feed.\nWillkommen zur KI Palooza 2026\nDein Passcode : 55147",
+ "code": "551471"
+ },
+ {
+ "sender": "X",
+ "subject": "Your X confirmation code is 5aem5f5z",
+ "preview": "X\n\nWe noticed an attempt to log in to your account @alexm that seems suspicious. Was this you?\n\n\n\nFalls du das warst\nJust to be safe, to log in to this account you’ll need to confirm this is really you by entering the following single-use code.\n\n5...",
+ "body": "We noticed an attempt to log in to your account @alexm that seems suspicious. Was this you?\nFalls du das warst\n Just to be safe, to log in to this account you’ll need to confirm this is really you by entering the following single-use code.\n5aem5f5z\nFalls du das nicht warst\n Complete these steps now to protect your account.\nChange your password. You'll be logged out of all your active X sessions except the one you're using at this time.\nReview the apps that have access to your account and revoke access to any unfamiliar apps. Learn more .\nHilfe | Nicht mein Account \nDiese PIN ist 10 Minuten gültig und läuft um 19:13 Uhr ab.\n Bitte beachten Sie, dass der Link nur auf dem Gerät funktioniert, dass Sie zum Login benutzt haben. Lesen Sie diese E-Mail auf einem anderen Gerät, z. B. Ihrem Smartphone? Geben Sie die PIN bitte von Hand in das Formularfeld ein, anstatt auf den Link zu klicken.\nGeben Sie diese PIN niemals weiter!\n Mitarbeiter von fonial fragen niemals nach dieser PIN. Teilen Sie diese daher nie mit fonial oder Dritten – es könnte sich um einen Versuch handeln unberechtigt in Ihr Kundenkont",
+ "code": "615233"
+ }
+]
diff --git a/src/lib/__tests__/verification-code.test.ts b/src/lib/__tests__/verification-code.test.ts
new file mode 100644
index 00000000..3ee25333
--- /dev/null
+++ b/src/lib/__tests__/verification-code.test.ts
@@ -0,0 +1,225 @@
+import { describe, it, expect } from 'vitest';
+import {
+ findVerificationCode,
+ htmlMayNameACode,
+ listVerificationCode,
+ verificationCodeBodyText,
+ VERIFICATION_CODE_MAX_AGE_MS,
+} from '../verification-code';
+// Real sign-in and confirmation mails as Stalwart 0.16.23 serves them: the
+// list's subject and preview, and the body text the reader derives from the
+// HTML part. Names, addresses and link tokens are replaced.
+import mails from './fixtures/verification-code-mails.json';
+
+// Mail whose code is neither in the subject nor in the 256-character
+// preview: its body opens with CSS, raw HTML or padding, or the preview
+// ends before (or in the middle of) the code.
+const NOT_IN_PREVIEW = new Set([
+ 'Lieferando', 'Planauskunft', 'Tuya', 'Telekom Geschäftskunden', 'Telekom Login', 'Steam', 'Autodesk',
+ 'Amazon Visa',
+]);
+
+describe('findVerificationCode on real mail', () => {
+ it.each(mails.map((m) => [m.sender, m] as const))('finds the code of %s in the reader', (_, mail) => {
+ expect(findVerificationCode(mail.subject, mail.body)).toBe(mail.code);
+ });
+
+ it.each(mails.map((m) => [m.sender, m] as const))('finds the code of %s in the list, or nothing', (sender, mail) => {
+ expect(findVerificationCode(mail.subject, mail.preview)).toBe(NOT_IN_PREVIEW.has(sender) ? null : mail.code);
+ });
+});
+
+describe('findVerificationCode', () => {
+ it('copies grouped digits without the gaps', () => {
+ expect(findVerificationCode('557 260 is your Instagram recovery code', '')).toBe('557260');
+ expect(findVerificationCode('', 'Bitte gebe folgenden Bestätigungs-Code ein: 3 0 4 6 2 7 Gebe diesen')).toBe('304627');
+ expect(findVerificationCode('', 'Your code: 123-456')).toBe('123456');
+ });
+
+ it('keeps the hyphen of a lettered code', () => {
+ expect(findVerificationCode('Slack confirmation code: 6ZA-BRE', '')).toBe('6ZA-BRE');
+ });
+
+ it('does not offer a code the preview cut in half', () => {
+ expect(findVerificationCode('', 'Bitte verwenden Sie den folgenden Steam-Guard-Code:\n\nAnmeldecode\nY9DG...')).toBeNull();
+ expect(findVerificationCode('', 'Your code is 1234...')).toBeNull();
+ });
+
+ it('finds digits run into the words around them', () => {
+ expect(findVerificationCode('', 'Gib diesen Code ein:86771674Teile diesen Code mit niemandem.')).toBe('86771674');
+ expect(findVerificationCode('', 'Sign in to Claude.ai177945Copy and paste the temporary verification code')).toBe('177945');
+ });
+
+ it('does not take a group of digits out of an id', () => {
+ expect(findVerificationCode('', 'Your verification code was sent. Request ffacd0b43b97d-4887a30a5a2si2098f4f')).toBeNull();
+ });
+
+ it('does not read a status code as the keyword of a one-time code', () => {
+ expect(findVerificationCode('', 'Rejected with code 550 (5.1.1) after 48291733 ms')).toBeNull();
+ expect(findVerificationCode('', 'Antwort mit Code 421: Server ausgelastet, Sitzung 48291733 beendet')).toBeNull();
+ });
+
+ it('prefers the code in the subject', () => {
+ expect(findVerificationCode('Your code is 482913', 'Your verification code for account 5512345 is below')).toBe('482913');
+ });
+
+ it('takes the code the keyword introduces over other numbers near it', () => {
+ expect(findVerificationCode('', 'Your verification code for account 12345678 is 482913.')).toBe('482913');
+ expect(findVerificationCode('', 'Dein Passcode\n551471\nKI Palooza 2026 Sep 29 2026 - Sep 30 2026')).toBe('551471');
+ });
+
+ it('accepts a year-shaped code only when it is presented as the code', () => {
+ expect(findVerificationCode('', 'Your Login Passcode for KI Palooza 2026')).toBeNull();
+ expect(findVerificationCode('', 'Your code is 2013')).toBe('2013');
+ });
+
+ it('reads keywords in other languages', () => {
+ expect(findVerificationCode('', 'Tu código de verificación es 482913')).toBe('482913');
+ expect(findVerificationCode('', 'Twój kod weryfikacyjny: 482913')).toBe('482913');
+ expect(findVerificationCode('', 'Ваш код подтверждения: 482913')).toBe('482913');
+ expect(findVerificationCode('', '您的验证码是 482913')).toBe('482913');
+ expect(findVerificationCode('', 'Din engangskode er 482913')).toBe('482913');
+ });
+
+ it.each([
+ ['an order confirmation', 'Deine Bestellung Nr. 302-4829175-1937264',
+ 'Vielen Dank für deine Bestellung vom 26.09.2026. Bestellnummer: 302-4829175-1937264 Summe: 49,99 € Deine Kundennummer: 5512345.'],
+ ['a shipping notice with a tracking code', 'Ihr Paket ist unterwegs',
+ 'Sendungsnummer 00340434161234567890. Mit dem Tracking-Code JJD0003900012 können Sie Ihre Sendung verfolgen. Zustellung am 28.09.2026 zwischen 10:00 und 14:00 Uhr.'],
+ ['a promotion', 'Nur heute: 25 % auf alles',
+ 'Mit dem Gutscheincode HERBST25 sparst du 25 %. Or use code THANKS10 for 10% off. Use promo code FALL2026 at checkout. © 2026 Shop GmbH, 10115 Berlin'],
+ ['a code review notification', 'Re: [bulwarkmail/webmail] Show verification codes (PR #1043)',
+ 'The code at line 1042 should use the shared helper, see commit 5f3e2a1 and issue #1039. Claude Code 2.1.14 fixed it.'],
+ ['an invoice', 'Ihre Rechnung RE-2026-10432',
+ 'Rechnungsbetrag 119,00 EUR. Bitte überweisen Sie bis 10.10.2026 auf IBAN DE89 3704 0044 0532 0130 00, BIC COBADEFFXXX.'],
+ ['a sign-in alert without a code', 'Neue Anmeldung bei deinem Konto',
+ 'Neue Anmeldung von Windows 11 um 14:32 Uhr in Berlin. Du musst keinen Code eingeben. Rufen Sie uns an unter +49 800 3301000 oder 0800 330 1000.'],
+ ['a code of conduct update', 'Updates to our Code of Conduct',
+ 'We updated our Code of Conduct effective 1 October 2026. Contact us at 1 Market St, San Francisco, CA 94105.'],
+ ['a card notice', 'Ihre Kreditkarte',
+ 'Geben Sie niemals Ihren Sicherheitscode oder Ihre PIN weiter. Ihre Karte endet auf 4821. Meeting-ID: 845 1234 5678'],
+ ['a QR code', 'Deine Mitgliedskarte', 'Scanne den QR-Code in der App. Deine Mitgliedsnummer 20394857.'],
+ ['a kernel log with an oops dump', 'Kernel warnings on host',
+ 'kern :warn : [Tue Oct 13 15:37:13 2026] 2026-10-13T15:37:13,834096-04:00 Code: 48 8b 45 00 0f 0b\nkern :warn : [Tue Oct 13 15:37:13 2026] 2026-10-13T15:37:13,834096-04:00 Tainted: [P]=PROPRIETARY_MODULE, [W]=WARN, [O]=OOT_MODULE'],
+ ['a code expiry timestamp', 'Your access code', 'Your code expires 2026-10-13T15:37:13Z.'],
+ ['a delivery report from Gmail', 'Successfully delivered message',
+ "Your message has been successfully delivered to the following recipients:\n\n (delivered to 'gmail-smtp-in.l.google.com' with code 250 (2.1.5) 'OK ffacd0b43b97d-4887a30a5a2si20984394f4f.30 - gsmtp')"],
+ ['a delivery report from Outlook', 'Successfully delivered message',
+ " (delivered to 'example-com.mail.protection.outlook.com' with code 250 (2.6.0) '2.6.0 [InternalId=21045339521540, Hostname=PAXPR03MB8065.eurprd03.prod.outlook.com] 12825 bytes in 0.108, 115.431 KB/sec Queued mail for delivery')"],
+ ])('finds nothing in %s', (_, subject, text) => {
+ expect(findVerificationCode(subject, text)).toBeNull();
+ });
+});
+
+describe('listVerificationCode', () => {
+ const now = Date.parse('2026-09-27T12:00:00Z');
+ const row = (receivedAt: string) => ({ subject: 'Your code is 482913', preview: '', receivedAt });
+
+ it('shows the code of a fresh mail', () => {
+ expect(listVerificationCode(row('2026-09-27T11:58:00Z'), now)).toBe('482913');
+ });
+
+ it('skips mail older than a day', () => {
+ expect(listVerificationCode(row(new Date(now - VERIFICATION_CODE_MAX_AGE_MS - 1000).toISOString()), now)).toBeNull();
+ });
+
+ it('allows for a server clock a little ahead', () => {
+ expect(listVerificationCode(row('2026-09-27T12:02:00Z'), now)).toBe('482913');
+ expect(listVerificationCode(row('2026-09-28T12:00:00Z'), now)).toBeNull();
+ });
+});
+
+describe('verificationCodeBodyText', () => {
+ const part = (partId: string, type: string) => ({ partId, blobId: `blob-${partId}`, size: 1, type });
+ const value = (v: string) => ({ value: v, isEncodingProblem: false, isTruncated: false });
+
+ it('reads the HTML part as the reader shows it, without its stylesheet', () => {
+ const text = verificationCodeBodyText({
+ htmlBody: [part('2', 'text/html')],
+ textBody: [part('1', 'text/plain')],
+ bodyValues: {
+ 1: value('This email is only available as HTML.'),
+ 2: value(''),
+ },
+ });
+ expect(text).not.toContain('600px');
+ expect(findVerificationCode('Verification Code', text)).toBe('261765');
+ });
+
+ // Opening a big HTML mail spent most of its script time turning the HTML
+ // into text to look for a code. Without any word that names a code there is
+ // nothing to find, so that step is skipped; it must never skip a mail that
+ // has one, however the word is written.
+ const html = (body: string) => verificationCodeBodyText({
+ htmlBody: [part('1', 'text/html')],
+ textBody: [],
+ bodyValues: { 1: value(`${body}`) },
+ });
+
+ it('skips reading HTML that names no code', () => {
+ const newsletter = 'Vacation policy update #998Lorem ipsum 482910 commodo ';
+ expect(htmlMayNameACode(newsletter)).toBe(false);
+ expect(html(newsletter)).toBe('');
+ });
+
+ it('still reads HTML whose code word is marked up, escaped or padded', () => {
+ expect(findVerificationCode('', html('Your verification code is 482910'))).toBe('482910');
+ expect(findVerificationCode('', html('Tu código de verificación es 482910'))).toBe('482910');
+ expect(findVerificationCode('', html('Ваш код: 482910'))).toBe('482910');
+ expect(findVerificationCode('', html('Your verification code is 482910'))).toBe('482910');
+ expect(findVerificationCode('', html('Ihre mTAN lautet 482910'))).toBe('482910');
+ });
+
+ it('reads plain-text mail', () => {
+ const text = verificationCodeBodyText({
+ htmlBody: [part('1', 'text/plain')],
+ textBody: [part('1', 'text/plain')],
+ bodyValues: { 1: value('Your HA Remote verification code is 811083.') },
+ });
+ expect(findVerificationCode('', text)).toBe('811083');
+ });
+});
+
+// A sender's bytes drive these regexes on the UI thread, for every opened
+// mail and every list row. Each of these inputs took seconds to minutes
+// before the patterns were anchored; all must stay linear.
+describe('crafted mail cannot stall the code search', () => {
+ const BUDGET_MS = 250;
+ const part = (partId: string, type: string) => ({ partId, blobId: `blob-${partId}`, size: 1, type });
+ const value = (v: string) => ({ value: v, isEncodingProblem: false, isTruncated: false });
+ function timed(fn: () => unknown): number {
+ const started = performance.now();
+ fn();
+ return performance.now() - started;
+ }
+ const htmlMail = (body: string) => ({
+ htmlBody: [part('1', 'text/html')],
+ textBody: [],
+ bodyValues: { 1: value(body) },
+ });
+
+ it('a megabyte of unclosed |