diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java index e7b4708f7..04d2b65bf 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java @@ -2,6 +2,7 @@ package com.liketrek.trek; import android.Manifest; import android.content.ActivityNotFoundException; +import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; @@ -433,7 +434,11 @@ public class TrekShellPlugin extends Plugin { } Uri data = intent.getData(); PluginCall call = pendingAuthCall(); - if (call == null || data == null || !authScheme.equals(data.getScheme())) return; + if (call == null) { + keepOrphanAuthReturn(intent); + return; + } + if (data == null || !authScheme.equals(data.getScheme())) return; JSObject result = new JSObject(); result.put("url", data.toString()); call.resolve(result); @@ -459,6 +464,48 @@ public class TrekShellPlugin extends Plugin { }, CANCEL_GRACE_MS); } + private static final String AUTH_PREFS = "trek_auth_return"; + /** As long as the server keeps the code it carries (NATIVE_HANDOFF_CODE_TTL_MS), with room to spare. */ + private static final long ORPHAN_AUTH_TTL_MS = 2 * 60 * 1000; + + /** + * A return to the sign-in scheme with no call waiting for it: Android ended + * the app while the browser was in front, and the browser's return started + * it anew (the launch intent comes through here as well). Kept on disk, as + * the process may be new too, until the sign-in page takes it. The return + * is then taken off the activity's intent: Capacitor hands the launch intent + * in again whenever the activity is created, and Android does as well when + * it rebuilds the task from the recent apps. + */ + private void keepOrphanAuthReturn(Intent intent) { + Uri data = intent.getData(); + if (data == null || !"auth".equals(data.getHost())) return; + if (!getContext().getString(R.string.custom_url_scheme).equals(data.getScheme())) return; + if (getActivity() != null && getActivity().getIntent() != null && getActivity().getIntent().getData() != null + && data.equals(getActivity().getIntent().getData())) { + getActivity().setIntent(new Intent(getActivity().getIntent()).setData(null)); + } + if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return; + getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE) + .edit() + .putString("url", data.toString()) + .putLong("at", System.currentTimeMillis()) + .commit(); + } + + /** The kept return of a sign-in (keepOrphanAuthReturn), once and while fresh; null otherwise. */ + @PluginMethod + public void takeAuthCallback(PluginCall call) { + android.content.SharedPreferences prefs = getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE); + String url = prefs.getString("url", null); + long at = prefs.getLong("at", 0); + prefs.edit().clear().commit(); + boolean fresh = url != null && System.currentTimeMillis() - at <= ORPHAN_AUTH_TTL_MS; + JSObject result = new JSObject(); + result.put("url", fresh ? url : JSONObject.NULL); + call.resolve(result); + } + private PluginCall pendingAuthCall() { return authCallId == null ? null : getBridge().getSavedCall(authCallId); } diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java index af482c0d5..bad0dc398 100644 --- a/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java @@ -1,11 +1,13 @@ package com.liketrek.trek; import android.net.Uri; +import android.util.Log; import android.webkit.ClientCertRequest; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; +import android.webkit.WebViewClient; import com.getcapacitor.Bridge; import com.getcapacitor.BridgeWebViewClient; import com.liketrek.trek.clientcert.TrekClientIdentity; @@ -34,6 +36,10 @@ class TrekWebViewClient extends BridgeWebViewClient { private final Set signInHosts; /** A page of the server has shown since launch; from then on no sign-in host is learned (SignInRedirect). */ private boolean serverShown; + /** The page itself failed on the network once already; the next failure goes to the address screen. */ + private boolean retriedMainFrame; + /** The page loaded again after a network error, until that load starts: its error page counts for nothing. */ + private String retryUrl; TrekWebViewClient( Bridge bridge, @@ -80,6 +86,7 @@ class TrekWebViewClient extends BridgeWebViewClient { @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { super.doUpdateVisitedHistory(view, url, isReload); + if (retryUrl != null) return; onSignInPage.accept(url != null && isSignInHost(Uri.parse(url))); // The 4xx answer arrives before this commit or after it; either way the // flag is read once here, so the next page clears the bar again. @@ -92,6 +99,9 @@ class TrekWebViewClient extends BridgeWebViewClient { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); + // The error page of a load that is about to be retried: not the server's + // first page, so no welcome page and no learning of sign-in hosts yet. + if (retryUrl != null) return; if (SignInRedirect.onServer(TrekServerStore.getUrl(view.getContext()), url)) serverShown = true; String welcome = TrekServerStore.takeWelcomeUrl(view.getContext()); if (welcome != null) view.loadUrl(welcome); @@ -137,9 +147,27 @@ class TrekWebViewClient extends BridgeWebViewClient { } } + /** + * A page that failed on the network is loaded once more before the app says + * the server is unreachable. Started from the background, as when the + * browser hands a sign-in back to an app Android had ended, a Samsung phone + * may hold its network back for a moment, and the first load fails with the + * server there all along. The error is logged, as a report has nothing else. + */ @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { if (request.isForMainFrame()) { + Log.w("TrekShell", "Page failed: " + error.getErrorCode() + " " + error.getDescription()); + if (!retriedMainFrame && isNetworkError(error.getErrorCode())) { + retriedMainFrame = true; + retryUrl = request.getUrl().toString(); + view.postDelayed(() -> { + String url = retryUrl; + retryUrl = null; + view.loadUrl(url); + }, 1500); + return; + } onUnreachable.run(); return; } @@ -168,6 +196,14 @@ class TrekWebViewClient extends BridgeWebViewClient { } } + private static boolean isNetworkError(int code) { + return code == WebViewClient.ERROR_HOST_LOOKUP + || code == WebViewClient.ERROR_CONNECT + || code == WebViewClient.ERROR_TIMEOUT + || code == WebViewClient.ERROR_IO + || code == WebViewClient.ERROR_UNKNOWN; + } + private static boolean wantedCertificate(Uri url) { TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest(); return asked != null && !asked.getServed() && TrekClientIdentity.matches(asked.getHost(), asked.getPort(), url.getHost(), url.getPort()); diff --git a/client/src/native/browserSignIn.test.ts b/client/src/native/browserSignIn.test.ts index 4e9dfaa5f..0161931d6 100644 --- a/client/src/native/browserSignIn.test.ts +++ b/client/src/native/browserSignIn.test.ts @@ -10,19 +10,25 @@ import { handoffUrl, rememberHandoffReturn, requestHandoffCode, + resumeBrowserSignIn, signInThroughBrowser, signInWithPasskey, takeHandoffReturn, } from './browserSignIn'; import { TrekShell } from './trekShell'; -vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } })); +vi.mock('./trekShell', () => ({ + APP_URL_SCHEME: 'com.liketrek.trek', + TrekShell: { authenticate: vi.fn(), takeAuthCallback: vi.fn() }, +})); vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() })); vi.mock('../api/client', () => ({ authApi: { passkey: { loginOptions: vi.fn(), loginVerify: vi.fn() } } })); vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } })); beforeEach(() => { vi.mocked(TrekShell.authenticate).mockReset(); + vi.mocked(TrekShell.takeAuthCallback).mockReset().mockResolvedValue({ url: null }); + localStorage.clear(); vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue(); }); @@ -89,6 +95,81 @@ describe('signInThroughBrowser', () => { }); }); +describe('resumeBrowserSignIn', () => { + // The app was ended while the browser was in front: the sign-in started, then + // the page that waited for it was gone. Only the stored verifier is left. + const startThenLoseThePage = async () => { + let finish: (value: { url: string }) => void = () => {}; + vi.mocked(TrekShell.authenticate).mockReturnValue(new Promise((resolve) => (finish = resolve))); + void signInThroughBrowser('oidc'); + await Promise.resolve(); + const url = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url); + return { challenge: url.searchParams.get('challenge') ?? '', finish }; + }; + + it('redeems a return that reached an app started anew, with the verifier of that sign-in, once', async () => { + const { challenge } = await startThenLoseThePage(); + vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-9' }); + await expect(resumeBrowserSignIn()).resolves.toBe(true); + const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0]; + expect(code).toBe('c-9'); + expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(challenge); + vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-9' }); + await expect(resumeBrowserSignIn()).resolves.toBe(false); + expect(nativeAuthApi.exchange).toHaveBeenCalledTimes(1); + }); + + it('does nothing without a kept return, and keeps the verifier for one that may still come', async () => { + await startThenLoseThePage(); + await expect(resumeBrowserSignIn()).resolves.toBe(false); + vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-2' }); + await expect(resumeBrowserSignIn()).resolves.toBe(true); + }); + + it('does nothing on a build without takeAuthCallback', async () => { + vi.mocked(TrekShell.takeAuthCallback).mockRejectedValueOnce({ code: 'UNIMPLEMENTED' }); + await expect(resumeBrowserSignIn()).resolves.toBe(false); + expect(nativeAuthApi.exchange).not.toHaveBeenCalled(); + }); + + it('drops a verifier older than the code it waits for', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + try { + await startThenLoseThePage(); + vi.setSystemTime(Date.now() + 3 * 60 * 1000); + vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-3' }); + await expect(resumeBrowserSignIn()).resolves.toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it('a sign-in that ends leaves the verifier of a newer one alone', async () => { + let rejectFirst: (err: unknown) => void = () => {}; + vi.mocked(TrekShell.authenticate) + .mockReturnValueOnce(new Promise((_, reject) => (rejectFirst = reject))) + .mockReturnValueOnce(new Promise(() => {})); + const first = signInThroughBrowser('oidc').catch((err: unknown) => err); + void signInThroughBrowser('oidc'); + await Promise.resolve(); + const second = new URL(vi.mocked(TrekShell.authenticate).mock.calls[1][0].url).searchParams.get('challenge'); + rejectFirst({ code: 'CANCELLED' }); + await expect(first).resolves.toBeInstanceOf(BrowserSignInCancelled); + vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-5' }); + await expect(resumeBrowserSignIn()).resolves.toBe(true); + const { verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0]; + expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(second); + }); + + it('leaves nothing behind once the running app redeemed the return itself', async () => { + const { finish } = await startThenLoseThePage(); + finish({ url: 'com.liketrek.trek://auth?code=c-4' }); + await vi.waitFor(() => expect(nativeAuthApi.exchange).toHaveBeenCalledTimes(1)); + vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-4' }); + await expect(resumeBrowserSignIn()).resolves.toBe(false); + }); +}); + describe('the remembered handoff return', () => { const path = `/native-handoff?challenge=${'a'.repeat(64)}`; diff --git a/client/src/native/browserSignIn.ts b/client/src/native/browserSignIn.ts index f3e2c5521..9895b0eec 100644 --- a/client/src/native/browserSignIn.ts +++ b/client/src/native/browserSignIn.ts @@ -12,9 +12,9 @@ import { APP_URL_SCHEME, TrekShell } from './trekShell'; * opens the server's /native-handoff page in the system browser, lets the user * sign in there, and carries the session back with a one-time code. * - * The verifier never leaves this function. Only its sha256 travels into the - * browser, and the code that comes back through the URL scheme is useless to - * anyone who does not also hold the verifier. The hash is computed in JS + * The verifier stays in the app. Only its sha256 travels into the browser, and + * the code that comes back through the URL scheme is useless to anyone who does + * not also hold the verifier. The hash is computed in JS * because crypto.subtle is missing on a plain-http server, which is how many * home networks reach theirs. */ @@ -99,9 +99,76 @@ export class BrowserSignInCancelled extends Error { } } +const PENDING_SIGN_IN_KEY = 'trek_native_pending_sign_in'; +// The server keeps the code a minute (NATIVE_HANDOFF_CODE_TTL_MS); two leave room for a slow start. +const PENDING_SIGN_IN_TTL_MS = 2 * 60 * 1000; + +/** + * Android may end the app while the system browser is in front, a Samsung + * phone short of memory readily so. The browser's return then starts a new + * app, and the call that waited for it is gone with the verifier it held, so + * the user came back to the sign-in page, signed in to the server but not to + * the app. The verifier is kept in this server's storage in the app until the + * return is redeemed, or for two minutes at most. + */ +function keepPendingSignIn(verifier: string): void { + try { + localStorage.setItem(PENDING_SIGN_IN_KEY, JSON.stringify({ verifier, at: Date.now() })); + } catch { + /* storage blocked: only the return to a running app can be redeemed */ + } +} + +/** Drops the kept verifier, if it is still this sign-in's: a newer one may have taken its place. */ +function dropPendingSignIn(verifier: string): void { + try { + const raw = localStorage.getItem(PENDING_SIGN_IN_KEY); + if (raw && (JSON.parse(raw) as { verifier?: unknown }).verifier === verifier) { + localStorage.removeItem(PENDING_SIGN_IN_KEY); + } + } catch { + /* storage blocked or the entry unreadable: nothing of ours to drop */ + } +} + +/** The verifier of a sign-in still open, once. */ +function takePendingSignIn(): string | null { + try { + const raw = localStorage.getItem(PENDING_SIGN_IN_KEY); + localStorage.removeItem(PENDING_SIGN_IN_KEY); + if (!raw) return null; + const { verifier, at } = JSON.parse(raw) as { verifier?: unknown; at?: unknown }; + if (typeof verifier !== 'string' || typeof at !== 'number') return null; + return Date.now() - at <= PENDING_SIGN_IN_TTL_MS ? verifier : null; + } catch { + return null; + } +} + +/** + * Redeems a sign-in whose return reached an app started anew (see + * keepPendingSignIn). True when the WebView now holds a session; false when + * there was nothing to redeem, or the app is a build that cannot tell. + */ +export async function resumeBrowserSignIn(): Promise { + let returned: string | null; + try { + ({ url: returned } = await TrekShell.takeAuthCallback()); + } catch { + return false; // a build without takeAuthCallback + } + if (!returned) return false; + const verifier = takePendingSignIn(); + const code = new URL(returned).searchParams.get('code'); + if (!verifier || !code) return false; + await nativeAuthApi.exchange({ code, verifier }); + return true; +} + /** Resolves once the WebView holds a session cookie of its own. */ export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: string): Promise { const { verifier, challenge } = createHandoffSecret(); + keepPendingSignIn(verifier); let returned: string; try { ({ url: returned } = await TrekShell.authenticate({ @@ -109,9 +176,11 @@ export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: callbackScheme: APP_URL_SCHEME, })); } catch (err) { + dropPendingSignIn(verifier); if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled(); throw err; } + dropPendingSignIn(verifier); const code = new URL(returned).searchParams.get('code'); if (!code) throw new Error('The browser returned without a sign-in code'); await nativeAuthApi.exchange({ code, verifier }); diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index 09d2cf64b..b7234d4a8 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -46,6 +46,12 @@ export interface TrekShellPlugin { * user closes the browser. */ authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>; + /** + * Android: a return to the sign-in scheme that found no authenticate() call + * waiting, because the app was started anew meanwhile. Handed out once, and + * only for two minutes, as long as the server keeps its code. Not in iOS builds, nor in Android builds before 5.1.4. + */ + takeAuthCallback(): Promise<{ url: string | null }>; /** iOS: stores the server's start page for a cold start without network. */ refreshOfflineCopy(): Promise<{ saved: boolean }>; /** iOS: loads that copy under the server's origin. False when there is none. */ diff --git a/client/src/pages/login/useLogin.native.test.tsx b/client/src/pages/login/useLogin.native.test.tsx index 2513ffad2..dc5fad5f0 100644 --- a/client/src/pages/login/useLogin.native.test.tsx +++ b/client/src/pages/login/useLogin.native.test.tsx @@ -1,4 +1,4 @@ -// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-006: useLogin inside the iOS/Android app +// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-008: useLogin inside the iOS/Android app import { startAuthentication } from '@simplewebauthn/browser'; import { http, HttpResponse } from 'msw'; import React from 'react'; @@ -9,7 +9,7 @@ import { server } from '../../../tests/helpers/msw/server'; import { act, renderHook, waitFor } from '../../../tests/helpers/render'; import { resetAllStores } from '../../../tests/helpers/store'; import { TranslationProvider } from '../../i18n/TranslationContext'; -import { BrowserSignInCancelled, signInThroughBrowser } from '../../native/browserSignIn'; +import { BrowserSignInCancelled, resumeBrowserSignIn, signInThroughBrowser } from '../../native/browserSignIn'; import { useAuthStore } from '../../store/authStore'; import { markSignedOut, wasSignedOut } from '../../utils/signedOut'; import { useLogin } from './useLogin'; @@ -24,7 +24,7 @@ vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() })); vi.mock('../../native/platform', () => ({ isNativeApp: () => true })); vi.mock('../../native/browserSignIn', async () => { const actual = await vi.importActual('../../native/browserSignIn'); - return { ...actual, signInThroughBrowser: vi.fn() }; + return { ...actual, signInThroughBrowser: vi.fn(), resumeBrowserSignIn: vi.fn() }; }); const realLocation = window.location; @@ -47,6 +47,7 @@ function clickEvent() { beforeEach(() => { resetAllStores(); vi.mocked(signInThroughBrowser).mockReset(); + vi.mocked(resumeBrowserSignIn).mockReset().mockResolvedValue(false); vi.mocked(startAuthentication).mockReset(); loadUser.mockClear(); useAuthStore.setState({ loadUser }); @@ -133,4 +134,21 @@ describe('useLogin in the native app', () => { expect(result.current.error).toBe('Signing in did not work. Please try again.'); expect(result.current.isLoading).toBe(false); }); + + it('FE-LOGIN-NATIVE-007: signs in with a browser return that reached an app Android started anew', async () => { + vi.mocked(resumeBrowserSignIn).mockResolvedValue(true); + const { result } = renderLogin(); + + await waitFor(() => expect(loadUser).toHaveBeenCalledWith({ silent: true })); + await waitFor(() => expect(result.current.showTakeoff).toBe(true)); + expect(signInThroughBrowser).not.toHaveBeenCalled(); + }); + + it('FE-LOGIN-NATIVE-008: explains a kept return that could not be redeemed, and stays on the page otherwise', async () => { + vi.mocked(resumeBrowserSignIn).mockRejectedValue(new Error('exchange failed')); + const { result } = renderLogin(); + + await waitFor(() => expect(result.current.error).toBe('Signing in did not work. Please try again.')); + expect(result.current.showTakeoff).toBe(false); + }); }); diff --git a/client/src/pages/login/useLogin.ts b/client/src/pages/login/useLogin.ts index 9a598ac68..bda520b5e 100644 --- a/client/src/pages/login/useLogin.ts +++ b/client/src/pages/login/useLogin.ts @@ -12,6 +12,7 @@ import { passwordErrorKey } from '../../utils/passwordError' import { isNativeApp } from '../../native/platform' import { BrowserSignInCancelled, + resumeBrowserSignIn, signInThroughBrowser, takeHandoffReturn, type BrowserSignInStart, @@ -303,6 +304,23 @@ export function useLogin() { } } + // In the app: a sign-in the system browser finished while Android started the + // app anew. Its return waited natively; redeemed here, it signs the app in. + useEffect(() => { + if (!nativeApp) return + resumeBrowserSignIn() + .then(async (signedIn) => { + if (!signedIn) return + await loadUser({ silent: true }) + setShowTakeoff(true) + void loadSettings() + setTimeout(() => { + void navigate(redirectTarget) + }, 2600) + }) + .catch(() => setError(t('native.login.failed'))) + }, [nativeApp, loadUser, loadSettings, navigate, redirectTarget, t]) + /** In the app: SSO and passkeys run in the system browser (native/browserSignIn.ts). */ const handleBrowserSignIn = async (start?: BrowserSignInStart): Promise => { setError('')