mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +00:00
fix(native): SSO in the Android app survives Android ending the app while the browser is open
A Samsung phone may end the app while the sign-in runs in the browser. The browser's return then started the app anew without the call that waited for it, the first page load failed while the network was still held back, and the user came back to 'server not reachable' and then to the sign-in page, in a loop. The return is now kept natively and redeemed by the sign-in page with the verifier kept until then, and a page that failed on the network is loaded once more before the app gives up.
This commit is contained in:
@@ -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)}`;
|
||||
|
||||
|
||||
@@ -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<boolean> {
|
||||
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<void> {
|
||||
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 });
|
||||
|
||||
@@ -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. */
|
||||
|
||||
Reference in New Issue
Block a user