Skip to content

Ask for a verification code when Apple stops accepting the session, instead of failing forever in silence - #134

Merged
wanderdev0 merged 9 commits into
mainfrom
fix/session-that-wants-2fa-again
Aug 22, 2026
Merged

wanderdev0 merged 9 commits into
mainfrom
fix/session-that-wants-2fa-again

Conversation

@wanderdev0

Copy link
Copy Markdown
Owner

A session Apple stops accepting used to fail every fetch, forever, in silence. This asks for a
verification code instead — and picks up three more bugs found by running it against a real
account.

The reported failure

An account restores as logged in, works, and at some later point Apple moves it to
REQUIRE_2FA. From then on every fetch raises before a request leaves the phone:

findmy.errors.InvalidStateError: Invalid login state!
Currently: LoginState.REQUIRE_2FA but should be one of: (LoginState.LOGGED_IN,)

MapsActivity logged it and waited to retry, under a comment reading "this error just happens
every now and then. It's no big deal, we will retry automatically eventually"
. True of most
fetch errors and completely wrong about this one, because the state does not heal itself. Pins
stopped updating, nothing on screen said why, and no amount of waiting helped. It is the issue
people kept reporting and nobody could reproduce from the description.

What happens now

REQUIRE_2FA is recoverable — six digits, using the account object already in memory rather than
the Apple password. So the app asks.

The overlay is not dismissible into the map, deliberately. With the session in this state
nothing can be located at all: not account tags, not imported ones, because both need an
authenticated session. There is no working screen behind it to return to, so offering a way back
would recreate the bug with an extra tap in front of it. Two exits: enter the code, or sign out.

Three wrong codes and the app stops pretending — the login data goes and the user signs in
properly. There was no limit anywhere before this: the login screen counts failures but only to
reword a hint after three, and lets you type forever. Fine there, where nobody has a session to
lose. Not fine here, where giving up deletes the login, so the number matches that existing
threshold rather than inventing a second one. Only a code Apple actually rejected counts, so a
flaky connection cannot spend somebody's session.

Issue #43 is folded in, because it is the same state through a different door

That fix discarded any restore that was not LOGGED_IN, reasoning that the app only stores an
account after a completed sign-in, so this could only mean the session went bad afterwards. That
is an argument about how the state arose. It says nothing about whether it can be fixed.

Before this PR, one account state produced opposite behaviour depending on the door: wipe the
session and demand the Apple password
at restore, and fail every fetch forever in silence mid
session. Now both ask for a code, and both fall back to signing in properly if that cannot work.

Strictly better when recoverable, no worse when not.

Three bugs found by running it, not by reading it

The first version of this fix did nothing at all, against a real stale account. It detected
the state, logged that it was asking for a second factor, and then returned — because the API
used an empty list to mean both "this session is fine" and "this session needs a code and
there is no way to send one"
. The caller could not tell them apart. That silently recreated the
original bug with more code in front of it.

The second state is real, and is the one the account was in:

UnauthorizedError: Unexpected login state after reauth: LoginState.REQUIRE_2FA. Please log in again.

get_2fa_methods had nothing to offer. Three answers now, not two, and that case signs out.

The hook was in the wrong place. Fetching is one accessory at a time and each failure is
caught by a per-accessory handler that logs and steps over it — right for one tag that would not
answer, wrong when the reason is the same for all of them. The outer subscriber barely fires. It
now asks where the failure actually surfaces, with a latch so six tags failing for one reason do
not request six codes or sign out six times.

The login screen it sends people to had a dead button. With the email prefilled, typing only
the password never enabled Sign in — the button is driven by flags kept by text watchers, and
the watchers are attached after onCreate prefills the address, so nothing ever recorded that
the email was valid. A filled-in address beside a button that could not be pressed, with no way
forward except deleting an address that was already correct. The recovery path ended there.

And one crash, which this PR made more likely

Opening a day of history threw IllegalStateException: Duplicate key. Two reports of the same
sighting — same tag, same instant, same coordinates — differing only in a claimed accuracy of 97
metres versus 92. The de-duplicating key ignores horizontalAccuracy and confidence on
purpose, so they are meant to collapse; Collectors.toMap throws on a repeated key instead, so
the function whose whole job is de-duplication fell over on a duplicate.

The third Collectors.toMap landmine here. Its defaults are wrong for both things this codebase
uses it for.

Latent rather than new — two same-instant reports would always have collided — but keeping every
report a fetch finds made the list larger and this materially more likely, so it is not purely
pre-existing either. The tighter accuracy wins rather than whichever arrived last, because
ordering is Apple's and arbitrary: last-wins would show 97 metres on one refresh and 92 on the
next with nothing having changed.

Tests

162 JVM · 210 Python · full instrumented suite, plus five new instrumented tests driving the
overlay and two on the login button.

They assert the rescue, not the dialog — whether the session is usable afterwards, and
whether the login data is really gone when the app gives up. A test that only checked which views
appeared would pass against an overlay that did nothing, which is exactly the version that
shipped into this branch and had to be fixed.

Everything new was checked by breaking it on purpose:

Broken deliberately What went red
empty list collapsed back to "fine" the no-way-to-send-a-code test, exactly as the app behaved
the field seeding removed both login-button tests
the merge function removed two report-merging tests, with the reported exception

One trap is now written on Apple2FACodeInputManager.init() itself, where somebody would hit
it: after a rejected code the overlay must call clear(), not init(). init() empties the boxes but leaves the manager's cursor at six, so it
never decides a code is "fully filled" again and the second attempt is never submitted at all.
Silent, and only on the second try. Caught by asserting how many codes reached Apple.

What is not proven

The code-entry path has only run against a double. Every test drives
apple_test_double; the real account that surfaced this cannot exercise it, because it offers no
methods to send a code to. So "enter six digits and the map comes back" is untested against
Apple, and I am not claiming otherwise — see rule 2. The sign-out paths have been seen on a
real session.

Separately, #133 came out of this
work: every discarded AppleAccount leaks its aiohttp session and sockets. Pre-existing, more
visible now because rescuing sessions means signing out more often. Not fixed here.


🤖 Written by Claude Code

wanderdev0 and others added 8 commits August 22, 2026 13:17
A user hit this today: the account restores as LOGGED_IN, works, and then at
some later point Apple moves it to REQUIRE_2FA. From that moment every fetch
raises InvalidStateError before a request is even made.

Nothing recovered. The per-accessory handler counted each failure and carried
on, the call reported an error, and MapsActivity logged it under a comment
saying "this error just happens every now and then... we will retry
automatically eventually". For this failure that is exactly wrong: the state
does not heal itself, so every refresh fails identically, forever, with stale
pins and no explanation anywhere. That is the shape of a bug people report
repeatedly and cannot describe.

`getSecondFactorMethodsIfNeeded` is the first half of the fix - the question
"what would actually help here", answered honestly:

- LOGGED_IN returns None without asking the account anything, because the
  common path must cost nothing
- REQUIRE_2FA returns the methods, in the same shape the login path already
  produces, so Java reads it with the code it has
- anything else returns None, because no code fixes being logged out and a box
  that cannot work teaches people to type codes at whatever asks
- a failure to determine it returns None too - an unreadable state is not
  evidence that a second factor would help

Four tests, including that a healthy account is never interrogated and that a
real FindMy.py method object survives the conversion. The fake is a genuine
subclass rather than a duck: `_convertToJavaDictWrapper` dispatches on
isinstance, so a stand-in would fall through to the unmapped branch and the
test would pass proving nothing.

The UI that uses this comes next.

Co-Authored-By: Claude Opus 5 <[email protected]>
Folds issue #43 into the same fix, because it is the same state arriving
through a different door and it was getting the opposite treatment.

The #43 fix discarded any restore that was not LOGGED_IN, reasoning that the
app only stores an account after a completed sign-in, so this could only mean
the session went bad afterwards. That is an argument about how the state arose.
It says nothing about whether it can be fixed, and REQUIRE_2FA is precisely the
state six digits resolve - using this account object, not the user's password.

So a restore in REQUIRE_2FA now comes back rather than being thrown away, and
the caller asks what it needs. LOGGED_OUT still fails the restore, because no
code fixes that. Try the cheap recovery, fall back to the expensive one:
strictly better when recoverable, no worse when not.

Both doors now reach the same place. Before this, an identical account state
meant "wipe the session and demand the Apple password" at restore and "fail
every fetch forever in silence" mid-session.

Two tests, and the pre-existing LOGGED_OUT one is deliberately left asserting
exactly what it did.

Co-Authored-By: Claude Opus 5 <[email protected]>
Groundwork for asking a stale session for a verification code. Nothing shows
the overlay yet - that is the next commit.

**The six code boxes were inline in activity_apple_login**, so the overlay
would have meant a second copy. They are now `two_factor_code_row`, included by
both. The ids are load-bearing - `Apple2FACodeInputManager` finds the slots by
id and gets silent nulls if one is renamed - so two copies would have drifted
into a screen where typing does nothing. `AppleLoginFlowTest`'s eleven tests
still pass, which is the check that mattered for that refactor.

**`Apple2FACodeInputManager` now resolves from a root view** rather than an
activity, because the overlay is not one and `activity.findViewById` would have
found nothing. The activity constructor is kept and delegates to the content
view, so the login screen is unchanged.

**The overlay is not dismissible into the map**, and that is the design rather
than an omission. Once Apple moves a session to REQUIRE_2FA the app cannot
locate anything at all - not account tags and not imported ones, because both
need an authenticated session. Dismissing into the map would leave somebody
looking at a screen that has quietly stopped working, which is the bug being
fixed here. Two exits: enter the code, or sign out.

**`TwoFactorAttempts` puts a number on giving up, which had none.** The login
screen counts failures but only to reword its hint, and lets you type codes
forever - fine there, because nobody on the login screen has a session to lose.
Here giving up deletes the login data, so it is three, matching the threshold
the login screen already uses rather than inventing a second one. Only a code
Apple actually rejected counts, so a flaky connection cannot cost somebody
their session.

Five tests on the counting, including that it never goes negative or
un-exhausts: sign-out is asynchronous, so a code can land after the third
rejection, and an implementation that reset there would hand back three fresh
attempts on a session already being discarded.

Co-Authored-By: Claude Opus 5 <[email protected]>
The user-facing half. A session Apple has moved to REQUIRE_2FA now gets an
overlay asking for a verification code, from both doors onto that state: a
restore that lands in it, and a working session Apple moves there later.

Before this the second one was permanent and silent - every fetch failed its
state check before a request left the phone, and MapsActivity logged it under
a comment saying such errors "just happen every now and then". True of most
fetch errors, wrong about this one, because the state does not heal itself.

Three wrong codes and the app stops pretending: the login data goes and the
user signs in properly. Only a code Apple actually rejected counts, so a flaky
connection cannot spend somebody's session.

**The test found a bug that would have shipped.** After a rejection the overlay
re-bound the boxes with `init()`, which empties them but leaves the manager's
cursor at six - so it never decides a code is "fully filled" again and the
*second* attempt is never submitted at all. The user types and nothing happens,
with no error. `clear()` is the one that resets the cursor, which is why the
login screen calls it. Caught by asserting how many codes reached Apple rather
than what the screen looked like.

The double models the real thing rather than a shortcut: `_FakeTrustedDevice`
subclasses `SyncTrustedDeviceSecondFactor` - the concrete sync class a sync
account actually returns - because `_convertToJavaDictWrapper` dispatches on
isinstance and a duck would arrive in Java typed UNKNOWN. Fetches raise the
same InvalidStateError the real ones do, so the app's own error handling is
what runs.

Four instrumented tests, asserting the rescue rather than the dialog: the
session is usable again after a right code, the stored login survives a wrong
one, and it is really gone after three or after signing out.

`toAuthMethods` is extracted from `pythonLogin` rather than copied - two
readers of one Python format is how one of them stops handling a new method
type.

Co-Authored-By: Claude Opus 5 <[email protected]>
Found by running the previous commit against a real stale account: it detected
the state, logged that it was asking for a second factor, and then did nothing
at all. Same silent dead map, with more code in front of it.

**The cause was my own API.** `secondFactorMethodsIfNeeded` returned a plain
list and used empty for two different answers - "this session is fine" and
"this session needs a code and there is no way to send one". The caller could
not tell them apart, so it treated the second as the first and returned.

A real session does reach that state. FindMy.py reports it exactly:

    UnauthorizedError: Unexpected login state after reauth:
    LoginState.REQUIRE_2FA. Please log in again.

`get_2fa_methods` has nothing to offer, so there is genuinely nothing to type
and the honest move is the expensive one - sign out and sign in properly. Three
answers now, not two: absent means fine, a non-empty list means ask for a code,
and an empty list means a code is needed and cannot be asked for.

**Also fixes where the hook lives.** The outer subscriber was the wrong place:
fetching is one accessory at a time and each failure is caught by a
per-accessory handler that logs and steps over it, so a stale session fails
every tag in turn and the stream completes as though it merely found nothing.
That handler is where this actually surfaces, so that is where it asks now -
with a latch, because six tags failing for one reason must not ask Apple for
six codes or sign out six times. The latch clears when a code rescues the
session, so a later staleness is still caught.

Verified the new test reproduces what was seen on the real account: with the
empty case collapsed back to "fine", it fails exactly as the app did.

Co-Authored-By: Claude Opus 5 <[email protected]>
Reported: with the email prefilled, typing only the password never enables the
Sign in button.

The button is driven by two flags kept by text watchers, and the watchers are
attached when the account page is shown - which happens *after* `onCreate`
prefills the address. So nothing ever told the screen the email was valid.
Typing the password set its own flag and the other stayed false, leaving a
filled-in address beside a dead button, with nothing to explain it and no way
forward except deleting an address that was already correct.

This is the screen a failed session sends people to, so the recovery path
ended at a button that could not be pressed - and the 2FA work in this branch
sends people here more often, not less.

Fixed by reading the fields rather than waiting to be told they changed. That
covers every way text arrives without an edit event - prefill, restored
instance state, an autofill service - instead of special-casing the one that
was reported.

Also stops the watchers being attached more than once. The method runs again
every time the page is shown - back from 2FA, back from the terms step - and
addTextChangedListener appends, so each keystroke was firing a growing pile of
identical watchers.

Two tests, and the second exists to rule out the lazy fix: emptying the
prefilled address must disable the button again, which "assume the email is
fine whenever one was passed in" would get wrong. Both verified against the
bug - with the seeding removed they fail exactly as the app did.

Co-Authored-By: Claude Opus 5 <[email protected]>
Reported from a real account: opening a day of history threw
`IllegalStateException: Duplicate key` and the screen reported the day as a
failed fetch.

The two reports were the same sighting - same tag, same instant, same
coordinates - differing only in a stated accuracy of 97 metres versus 92. The
de-duplicating key ignores `horizontalAccuracy` and `confidence` on purpose,
because those are the fields Apple is least consistent about, so those two are
*meant* to collapse into one. `Collectors.toMap` throws on a repeated key
rather than merging, so the function whose entire job is de-duplication fell
over on a duplicate.

The third `Collectors.toMap` landmine in this codebase, after the null-value
one in the startup fetch. Its defaults are wrong for both of the things this
app does with it.

**The tighter accuracy wins, not whichever arrived last.** Ordering here is
Apple's and is arbitrary, so a last-wins merge would show 97 metres on one
refresh and 92 on the next with nothing having changed. Smaller is both the
better answer and a stable one.

Honest about ownership: this is a latent bug - two same-instant reports would
always have collided - but widening the fetch to keep everything it found made
the remote list larger and this materially more likely. I would not call it
purely pre-existing.

Six JVM tests, including that the stored copy still overrides the fetched one,
which the fix must not quietly change. Verified by removing the merge function
again and watching two of them fail with the reported exception.

Co-Authored-By: Claude Opus 5 <[email protected]>
After a rejected code the overlay must call clear(); init() empties the boxes
but leaves the cursor at six, so the next code is never submitted at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
CI aborted this branch's suite at 335 of 564 tests. The logcat artefact added
in #130 caught what nothing had caught before - a native crash, with a stack:

    AnisetteStatus.of -> LocalAnisette.ensureReady -> LocalAnisette.load
      -> AdiLibrary.initialise -> NativeAdi.callWithPath
      -> libstoreservicescore.so
    signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), tid RxCachedThreadS

MapsActivity asks for Anisette on the way to restoring a session, and the real
source dlopens Apple's library and initialises it. Correct in the app. In a
suite it happens once per test, in one process, on whichever Rx thread got
there first - and sometimes it segfaults. A native crash takes the whole
instrumentation with it, so the run does not fail, it *stops*, and every
remaining test is reported as never having run.

That is almost certainly the intermittent whole-suite abort this repo has been
living with. It has been showing up as two arbitrary test names and
`Process crashed`, which is why it never got diagnosed: the names are whatever
was in flight, and the cause was in a logcat nobody kept.

The login-flow tests have always replaced Anisette with a fake. The map fixture
never did, so every test built on it was loading the real thing - and nothing
built on it is testing Anisette. Now it does the same.

Found because a new test in this branch tripped it reliably enough to fail CI
rather than intermittently. Fixing the fixture rather than the test, because
the test was not doing anything unusual.

Co-Authored-By: Claude Opus 5 <[email protected]>
@wanderdev0
wanderdev0 merged commit 700759e into main Aug 22, 2026
3 checks passed
saamdotexe pushed a commit to saamdotexe/OpenTagViewer that referenced this pull request Oct 22, 2026
…wants-2fa-again

Ask for a verification code when Apple stops accepting the session, instead of failing forever in silence

This branch was previously deployed

1 inactive deployment
Android Build — 136e11fc Deployed Aug 22, 2026 by wanderdev0 via Instrumented tests (emulator) #144
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant