diff --git a/src/gui/src/initgui.gates.test.js b/src/gui/src/initgui.gates.test.js index a3dd05cf2..e27f5e66e 100644 --- a/src/gui/src/initgui.gates.test.js +++ b/src/gui/src/initgui.gates.test.js @@ -69,6 +69,51 @@ describe('the popup token hand-off in postAuthActions', () => { }); }); +describe('the requests a sign-in popup makes after an account is picked', () => { + const postAuthActions = src.slice( + src.indexOf('const postAuthActions = async'), + src.indexOf('window.initgui = async'), + ); + + it('matches the early exchange before every exchange in postAuthActions', () => { + const exchanges = postAuthActions.split('await window.getUserAppToken(origin)').length - 1; + const matched = postAuthActions.split( + 'reusableTokenExchange(early_token_exchange, origin, window.auth_token) ??', + ).length - 1; + expect(exchanges).toBe(2); + expect(matched).toBe(2); + expect(postAuthActions.split('getUserAppToken(').length - 1).toBe(2); + }); + + it('records every early exchange, so none is repeated unmatched', () => { + const boot = src.slice(src.indexOf('window.initgui = async')); + const sdkLogin = boot.slice( + boot.indexOf('// show signup window'), + boot.indexOf('window.popup_signin_consent = !!picked_a_user_for_sdk_login;'), + ); + expect(sdkLogin.split('await exchangeUserAppTokenEarly();').length - 1).toBe(3); + expect(sdkLogin).not.toContain('getUserAppToken('); + }); + + it('skips the relationship check only for a picked account', () => { + // Signup in the popup sets consent without a pick, and still needs + // the check to keep a second account picker away. + const check = src.indexOf('await window.checkUserSiteRelationship('); + const guard = src.lastIndexOf('if (', check); + expect(src.slice(guard, check)).toContain('if (!picked_a_user_for_sdk_login) {'); + expect(src.slice(guard, check)).not.toContain('popup_signin_consent'); + }); + + it('reuses the early whoami only through reusablePopupUser', () => { + const reuse = src.indexOf('whoami = popup_whoami.user;'); + expect(reuse).toBeGreaterThan(-1); + expect(src.split('popup_whoami.user').length - 1).toBe(1); + const guard = src.slice(src.lastIndexOf('if (', reuse), reuse); + expect(guard).toContain('picked_a_user_for_sdk_login &&'); + expect(guard).toContain('reusablePopupUser(popup_whoami, {'); + }); +}); + describe('the permission popup and browser push', () => { const postAuthActions = src.slice( src.indexOf('const postAuthActions = async'), diff --git a/src/gui/src/initgui.js b/src/gui/src/initgui.js index e28f78286..cba1aefa0 100644 --- a/src/gui/src/initgui.js +++ b/src/gui/src/initgui.js @@ -112,6 +112,8 @@ import { relationshipIsConsent, relaysTokenAtBoot, resolveOpenerOrigin, + reusablePopupUser, + reusableTokenExchange, runsUserAppTokenExchange, } from './util/popupAuth.js'; import { verifyOidcPopupReturn } from './util/popupOidcReturn.js'; @@ -161,6 +163,21 @@ const follow_share_recipient = async (action) => { })); }; +// A sign-in popup exchanges as soon as the user has chosen an account, and +// `postAuthActions` hands over that result instead of exchanging again. +let early_token_exchange = null; +const exchangeUserAppTokenEarly = async () => { + const authToken = window.auth_token; + const data = await window.getUserAppToken(window.openerOrigin); + let origin = null; + try { + origin = new URL(window.openerOrigin).origin; + } catch (e) { + // No origin to match on, so the result is not reused. + } + early_token_exchange = { origin, authToken, data }; +}; + const postAuthActions = async (action) => { if ( await follow_share_recipient(action) ) return; // Set when a popup's user-app token exchange fails. The exchange is what @@ -440,7 +457,10 @@ const postAuthActions = async (action) => { if (isolated) { try { - const data = await window.getUserAppToken(new URL(window.openerOrigin).origin); + const origin = new URL(window.openerOrigin).origin; + const data = + reusableTokenExchange(early_token_exchange, origin, window.auth_token) ?? + await window.getUserAppToken(origin); // Same two failure modes the postMessage path below guards // against: `getUserAppToken` reports a network failure by // returning null, and an HTTP failure (a blocked origin, an @@ -484,7 +504,10 @@ const postAuthActions = async (action) => { // Its failure carries `token: null`, which the SDK sets too. const deliver_token_to_opener = deliversTokenAtBoot(action); try { - let data = await window.getUserAppToken(new URL(window.openerOrigin).origin); + const origin = new URL(window.openerOrigin).origin; + let data = + reusableTokenExchange(early_token_exchange, origin, window.auth_token) ?? + await window.getUserAppToken(origin); // `getUserAppToken` reports a network failure by returning // null, and an HTTP failure (a blocked origin, a 5xx) by // returning the parsed *error* body — which is truthy but @@ -1514,6 +1537,8 @@ window.initgui = async function (options) { let picked_a_user_for_sdk_login = false; // Whether a popup put an account picker in front of the user. let showed_account_picker = false; + // The `/whoami` a sign-in popup read before its account picker. + let popup_whoami = null; // update SDK if auth_token is different from the one in the SDK if (window.auth_token && puter.authToken !== window.auth_token) { @@ -1868,7 +1893,7 @@ window.initgui = async function (options) { // Completing signup in a sign-in popup is the user asking to // be signed in to the opener. window.popup_signin_consent = true; - await window.getUserAppToken(window.openerOrigin); + await exchangeUserAppTokenEarly(); } } else if ( // An action-less popup is a sign-in popup — `postAuthActions` @@ -1892,6 +1917,11 @@ window.initgui = async function (options) { whoami_popup.token || window.auth_token, whoami_popup, ); + popup_whoami = { + user: whoami_popup, + authToken: window.auth_token, + fetchedAt: Date.now(), + }; } catch (e) { // session/auth errors will be handled further ahead; // let's log the error for now in case a change in state occurred. @@ -1917,7 +1947,7 @@ window.initgui = async function (options) { String(currentUserUuid); if (proofMatchesCurrentUser) { picked_a_user_for_sdk_login = true; - await window.getUserAppToken(window.openerOrigin); + await exchangeUserAppTokenEarly(); } else { // Show session list so user can pick which account to use showed_account_picker = true; @@ -1927,7 +1957,7 @@ window.initgui = async function (options) { }); if (picked_a_user_for_sdk_login) { - await window.getUserAppToken(window.openerOrigin); + await exchangeUserAppTokenEarly(); } } // Picking an account here *is* the consent to sign the opener in. @@ -2050,10 +2080,14 @@ window.initgui = async function (options) { // if not, we need to ask the user for confirmation before proceeding BUT only if the action is a file-picker action // ------------------------------------------------------------------------------------- if (window.embedded_in_popup && window.openerOrigin) { - let response = await window.checkUserSiteRelationship( - window.openerOrigin, - ); - window.userAppToken = response?.token; + // An account picked above already answers both questions below, the + // picker and the consent. Signup in the popup is not a pick. + if (!picked_a_user_for_sdk_login) { + let response = await window.checkUserSiteRelationship( + window.openerOrigin, + ); + window.userAppToken = response?.token; + } // A framed picker or upgrade already holds the framing page's user, // so it doesn't offer to switch. @@ -2410,6 +2444,22 @@ window.initgui = async function (options) { // Authed // ------------------------------------------------------------------------------------- if (window.is_auth()) { + // A sign-in popup whose user kept the account it opened with, and whose + // exchange just proved the session, already has this user's data. + if ( + !whoami && + picked_a_user_for_sdk_login && + reusablePopupUser(popup_whoami, { + userUuid: window.user?.uuid, + authToken: window.auth_token, + exchangedAuthToken: early_token_exchange?.data?.token + ? early_token_exchange.authToken + : null, + now: Date.now(), + }) + ) { + whoami = popup_whoami.user; + } // try to get user data using /whoami, only if that data is missing if (!whoami) { try { diff --git a/src/gui/src/util/popupAuth.js b/src/gui/src/util/popupAuth.js index 40ce023fb..9227e6fff 100644 --- a/src/gui/src/util/popupAuth.js +++ b/src/gui/src/util/popupAuth.js @@ -135,6 +135,65 @@ export const resolveOpenerOrigin = async ({ export const relationshipIsConsent = ({ hasRelationship, showedAccountPicker }) => hasRelationship && !showedAccountPicker; +/** + * The result of a popup's early user-app token exchange, when it stands in for + * a second one: it returned a token, for the same opener and the same session. + * + * @param {{ + * origin: string|null; + * authToken: string|null|undefined; + * data: { token?: string; app_uid?: string }|null; + * }|null} early - The early exchange, or null when none ran. + * @param {string} origin - The opener origin the token is needed for. + * @param {string|null|undefined} authToken - The session token in use. + * @returns {{ token: string; app_uid?: string }|null} null means exchange again. + */ +export const reusableTokenExchange = (early, origin, authToken) => { + if ( !early?.data?.token || !origin || !authToken ) return null; + if ( early.origin !== origin || early.authToken !== authToken ) return null; + return /** @type {{ token: string; app_uid?: string }} */ (early.data); +}; + +/** How long a sign-in popup's first `/whoami` stays usable. */ +export const POPUP_WHOAMI_MAX_AGE_MS = 60_000; + +const VERIFICATION_GATE_FLAGS = [ + 'requires_email_confirmation', + 'requires_phone_verification', + 'requires_card_verification', + 'requires_password_change', +]; + +/** + * Whether the `/whoami` a sign-in popup read before its account picker still + * describes the session, so boot can skip reading it again. + * + * A pending verification gate always gets a fresh read, and so does a session + * the token exchange has not just accepted. + * + * @param {{ + * user: Record; + * authToken: string|null|undefined; + * fetchedAt: number; + * }|null} early - The early read, or null when none succeeded. + * @param {{ + * userUuid: string|null|undefined; + * authToken: string|null|undefined; + * exchangedAuthToken: string|null|undefined; + * now: number; + * }} session - The signed-in user and token now, and the session token the + * early token exchange succeeded with (null when it returned no token). + * @returns {boolean} + */ +export const reusablePopupUser = (early, { userUuid, authToken, exchangedAuthToken, now }) => { + if ( !early?.user?.uuid || !authToken ) return false; + if ( early.user.uuid !== userUuid ) return false; + if ( early.authToken !== authToken || exchangedAuthToken !== authToken ) return false; + if ( VERIFICATION_GATE_FLAGS.some(flag => early.user[flag]) ) return false; + const age = now - early.fetchedAt; + return age >= 0 && age <= POPUP_WHOAMI_MAX_AGE_MS; +}; + /** * Whether a popup running `action` runs the user-app token exchange. * diff --git a/src/gui/src/util/popupAuth.test.js b/src/gui/src/util/popupAuth.test.js index 893dd6584..eff1022d7 100644 --- a/src/gui/src/util/popupAuth.test.js +++ b/src/gui/src/util/popupAuth.test.js @@ -26,7 +26,10 @@ import { offersFederatedSignInInPopup, relationshipIsConsent, relaysTokenAtBoot, + POPUP_WHOAMI_MAX_AGE_MS, resolveOpenerOrigin, + reusablePopupUser, + reusableTokenExchange, runsUserAppTokenExchange, } from './popupAuth.js'; @@ -315,3 +318,106 @@ describe('the retired opener_origin gate', () => { expect(popupAuth.trustsOpenerOriginParam).toBeUndefined(); }); }); + +describe('reusableTokenExchange', () => { + const origin = 'https://app.example'; + const early = { + origin, + authToken: 'session-a', + data: { token: 'app-token', app_uid: 'app-1' }, + }; + + it('returns the early result for the same opener and session', () => { + expect(reusableTokenExchange(early, origin, 'session-a')).toBe(early.data); + }); + + it('exchanges again when no early exchange ran', () => { + expect(reusableTokenExchange(null, origin, 'session-a')).toBeNull(); + }); + + it('exchanges again when the early one returned no token', () => { + // A network failure is null; an HTTP failure is the error body. + for ( const data of [null, { code: 'app_blocked', message: 'no' }, { token: '' }] ) { + expect(reusableTokenExchange({ ...early, data }, origin, 'session-a')).toBeNull(); + } + }); + + it('exchanges again after the user switched accounts', () => { + expect(reusableTokenExchange(early, origin, 'session-b')).toBeNull(); + }); + + it('exchanges again for another opener', () => { + expect(reusableTokenExchange(early, 'https://other.example', 'session-a')).toBeNull(); + expect(reusableTokenExchange({ ...early, origin: null }, origin, 'session-a')).toBeNull(); + }); + + it('exchanges again without a session token to match on', () => { + const unkeyed = { ...early, authToken: undefined }; + expect(reusableTokenExchange(unkeyed, origin, undefined)).toBeNull(); + expect(reusableTokenExchange({ ...early, authToken: null }, origin, null)).toBeNull(); + }); +}); + +describe('reusablePopupUser', () => { + const early = { + user: { uuid: 'user-a', username: 'a' }, + authToken: 'session-a', + fetchedAt: 1_000, + }; + const session = { + userUuid: 'user-a', + authToken: 'session-a', + exchangedAuthToken: 'session-a', + now: 2_000, + }; + + it('reuses the early read for the same user on a session the exchange accepted', () => { + expect(reusablePopupUser(early, session)).toBe(true); + }); + + it('reads again when the early read failed', () => { + expect(reusablePopupUser(null, session)).toBe(false); + expect(reusablePopupUser({ ...early, user: {} }, session)).toBe(false); + }); + + it('reads again after the user switched accounts', () => { + expect(reusablePopupUser(early, { ...session, userUuid: 'user-b' })).toBe(false); + expect(reusablePopupUser(early, { + ...session, + authToken: 'session-b', + exchangedAuthToken: 'session-b', + })).toBe(false); + }); + + it('reads again when the exchange did not accept this session', () => { + // A dead session has to reach the read that signs the user out. + expect(reusablePopupUser(early, { ...session, exchangedAuthToken: null })).toBe(false); + expect(reusablePopupUser(early, { ...session, exchangedAuthToken: 'session-b' })).toBe(false); + }); + + it('reads again when a verification gate is pending', () => { + for ( const flag of [ + 'requires_email_confirmation', + 'requires_phone_verification', + 'requires_card_verification', + 'requires_password_change', + ] ) { + const gated = { ...early, user: { ...early.user, [flag]: true } }; + expect(reusablePopupUser(gated, session)).toBe(false); + } + }); + + it('reads again once the early read is too old', () => { + const at = (now) => reusablePopupUser(early, { ...session, now }); + expect(at(early.fetchedAt + POPUP_WHOAMI_MAX_AGE_MS)).toBe(true); + expect(at(early.fetchedAt + POPUP_WHOAMI_MAX_AGE_MS + 1)).toBe(false); + expect(at(early.fetchedAt - 1)).toBe(false); + }); + + it('reads again without a session token', () => { + expect(reusablePopupUser( + { ...early, authToken: undefined }, + { ...session, authToken: undefined, exchangedAuthToken: undefined }, + )).toBe(false); + }); +}); diff --git a/src/puter-js/tests/e2e/helpers/testApp.js b/src/puter-js/tests/e2e/helpers/testApp.js index 9d4fbcedb..4c3d1564e 100644 --- a/src/puter-js/tests/e2e/helpers/testApp.js +++ b/src/puter-js/tests/e2e/helpers/testApp.js @@ -52,6 +52,28 @@ export async function waitForPuterReady (page) { await page.waitForFunction(() => !!window.puter?.apps?.create, null, { timeout: 10_000 }); } +/** + * Creates a second account, the one a first-time visitor is given, and + * returns its token and user. Sign-ups are rate limited, so create one per file. + * + * @param {import('@playwright/test').Browser} browser + * @returns {Promise<{ token: string, user: { uuid: string, username: string } }>} + */ +export async function createVisitorAccount (browser) { + const visitorContext = await browser.newContext({ + storageState: { cookies: [], origins: [] }, + }); + const visitorPage = await visitorContext.newPage(); + await visitorPage.goto('/'); + await waitForPuterReady(visitorPage); + const account = await visitorPage.evaluate(() => ({ + token: localStorage.getItem('auth_token_v2'), + user: JSON.parse(localStorage.getItem('user')), + })); + await visitorContext.close(); + return account; +} + async function assertFixtureReachable (fixtureURL) { let res; try { diff --git a/src/puter-js/tests/e2e/specs/accountSwitchAcrossTabs.spec.js b/src/puter-js/tests/e2e/specs/accountSwitchAcrossTabs.spec.js index f046373d8..61235ea60 100644 --- a/src/puter-js/tests/e2e/specs/accountSwitchAcrossTabs.spec.js +++ b/src/puter-js/tests/e2e/specs/accountSwitchAcrossTabs.spec.js @@ -1,20 +1,5 @@ import { test, expect } from '@playwright/test'; -import { waitForPuterReady } from '../helpers/testApp.js'; - -const createVisitorAccount = async (browser) => { - const visitorContext = await browser.newContext({ - storageState: { cookies: [], origins: [] }, - }); - const visitorPage = await visitorContext.newPage(); - await visitorPage.goto('/'); - await waitForPuterReady(visitorPage); - const account = await visitorPage.evaluate(() => ({ - token: localStorage.getItem('auth_token_v2'), - user: JSON.parse(localStorage.getItem('user')), - })); - await visitorContext.close(); - return account; -}; +import { createVisitorAccount, waitForPuterReady } from '../helpers/testApp.js'; // A second account: what a first-time visitor is given. Created once for the // whole file, because sign-ups are rate limited. diff --git a/src/puter-js/tests/e2e/specs/popupSignIn.spec.js b/src/puter-js/tests/e2e/specs/popupSignIn.spec.js index 324a19a70..6c7cc47a5 100644 --- a/src/puter-js/tests/e2e/specs/popupSignIn.spec.js +++ b/src/puter-js/tests/e2e/specs/popupSignIn.spec.js @@ -1,5 +1,5 @@ import { test, expect } from '@playwright/test'; -import { FIXTURE_URL } from '../helpers/testApp.js'; +import { FIXTURE_URL, createVisitorAccount, waitForPuterReady } from '../helpers/testApp.js'; const FIXTURE = FIXTURE_URL.replace( 'menubar-contextmenu.html', @@ -178,3 +178,116 @@ test.describe('popup sign-in cannot be driven from a link', () => { expect(await page.evaluate(() => window.__leaked)).toBe('waiting'); }); }); + +test.describe('popup sign-in after an account is picked', () => { + // The popup's own `/whoami` read carries `icon_size`. puter.js sends a + // bare one on every `setAuthToken()`, which the popup does not wait on. + const COUNTED = ['/auth/get-user-app-token', '/auth/check-app', '/whoami?icon_size=64']; + + /** + * Open a sign-in popup from the fixture, pick the signed-in account, and + * report the API requests the popup sent after the pick. With a `session` + * the page waits on `/login/wait` for it, as an isolated opener does. With + * an `other` account, that one is signed in on the browser too, and picked. + */ + const pickAccount = async (page, popupQuery, session = null, other = null) => { + await page.goto('/'); + await page.waitForFunction(() => !!window.puter?.authToken, null, { + timeout: 60_000, + }); + if ( other ) { + await waitForPuterReady(page); + await page.evaluate(({ token, user }) => { + const known = JSON.parse(localStorage.getItem('logged_in_users')); + known.push({ ...user, auth_token: token }); + localStorage.setItem('logged_in_users', JSON.stringify(known)); + }, other); + } + await page.goto(FIXTURE); + await page.locator('body.ready').waitFor({ timeout: 60_000 }); + + const [popup] = await Promise.all([ + page.waitForEvent('popup'), + page.evaluate(({ query, relaySession }) => { + if ( relaySession ) { + window.__relayed = fetch(`${puter.APIOrigin}/login/wait`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session: relaySession }), + }).then(async (response) => (await response.json())?.auth_token); + } + window.__delivered = null; + window.addEventListener('message', (event) => { + if ( event.data?.msg === 'puter.token' ) { + window.__delivered = event.data; + } + }); + window.open( + `${puter.defaultGUIOrigin}/action/sign-in?embedded_in_popup=true&${query}`, + 'signin-pick', + 'width=600,height=700', + ); + }, { query: popupQuery, relaySession: session }), + ]); + + const accounts = popup.locator('.auth-dialog [data-screen="accounts"] .auth-account'); + await expect(accounts).toHaveCount(other ? 2 : 1, { timeout: 60_000 }); + const account = other ? accounts.and(popup.locator(`[data-uuid="${other.user.uuid}"]`)) : accounts; + const requests = []; + popup.on('request', (request) => { + if ( request.method() === 'OPTIONS' ) return; + const { pathname, search } = new URL(request.url()); + if ( COUNTED.includes(pathname + search) ) requests.push(pathname + search); + }); + await Promise.all([popup.waitForEvent('close'), account.click()]); + return requests; + }; + + /** The username the API resolves `token` to, asked from the fixture page. */ + const usernameFor = (page, token) => + page.evaluate(async (bearer) => { + const response = await fetch(`${puter.APIOrigin}/whoami`, { + headers: { Authorization: `Bearer ${bearer}` }, + }); + return response.ok ? (await response.json()).username : null; + }, token); + + test('hands the opener a working token after one exchange', async ({ page }) => { + const requests = await pickAccount(page, 'msg_id=92'); + + await page.waitForFunction(() => !!window.__delivered); + const delivered = await page.evaluate(() => window.__delivered); + expect(delivered.success).toBe(true); + expect(delivered.msg_id).toBe('92'); + expect(delivered.app_uid).toMatch(/^app-/); + expect(await usernameFor(page, delivered.token)).toBe(delivered.username); + expect(requests).toEqual(['/auth/get-user-app-token']); + }); + + test('relays a working token to an isolated opener after one exchange', async ({ page }) => { + const session = '22222222-3333-4444-8555-aaaaaaaaaaaa'; + const requests = await pickAccount( + page, + `cross_origin_isolated=true&signin_session=${session}&msg_id=93`, + session, + ); + + const token = await page.evaluate(() => window.__relayed); + expect(await usernameFor(page, token)).toBeTruthy(); + expect(requests).toEqual(['/auth/get-user-app-token']); + }); + + test('hands over the picked account when it is not the one the popup opened with', async ({ browser, page }) => { + const other = await createVisitorAccount(browser); + + const requests = await pickAccount(page, 'msg_id=94', null, other); + + await page.waitForFunction(() => !!window.__delivered); + const delivered = await page.evaluate(() => window.__delivered); + expect(delivered.success).toBe(true); + expect(delivered.username).toBe(other.user.username); + expect(await usernameFor(page, delivered.token)).toBe(other.user.username); + // The popup has not read this account yet, so it reads it once. + expect(requests).toEqual(['/auth/get-user-app-token', '/whoami?icon_size=64']); + }); +});