Send one request, not four, after the account pick in the sign-in popup (#4564)
Maintain Release Merge PR / update-release-pr (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
release-please / release-please (push) Canceled after 0s

* Send one request, not four, after the account pick in the sign-in popup

A sign-in popup exchanges for the opener's app token as soon as the user
picks an account. postAuthActions now hands over that result when the
opener origin and session token still match, and exchanges again otherwise.

The relationship check is skipped when an account was picked, since the
pick already decides both the second picker and consent. Signup in the
popup is not a pick and still runs it.

The /whoami read before the picker is reused only when the same user and
session token are still in place, the exchange just accepted that session,
no verification gate is pending, and the read is under a minute old.

* Test picking a different account in the sign-in popup

The popup has to read the picked account once and hand over a token for
it, not for the account it opened with. The second-account helper moves
to the shared e2e helpers so both specs that need one use the same copy.
This commit is contained in:
Nariman Jelveh authored and GitHub committed 2026-11-10 08:31:12 -07:00
1 parent 2084587885
commit 8a15f09f48
7 files changed
+406 -26

No files matched your search

+22
View File
@@ -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 {
@@ -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.
@@ -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']);
});
});