From 522c5af1a737dcbf6d5a18c8c425af657ee44a18 Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Mon, 23 Nov 2026 11:33:48 -0700 Subject: [PATCH] fix(puter-js): clear launch params from app tabs; private app sign-in keeps the tab's launch (#4743) * fix(puter-js): clear launch params from an app tab's address bar An app the desktop opens in its own browser tab removes the puter.* params it was launched with from its URL after load. The app's own params, utm_* and the hash stay; framed apps are unchanged. The SDK reads launch items from the query it booted with, so onLaunchedWithItems() and wasLaunchedWithItems() still see the opened item after the URL changes. * fix(puter-js): keep a tab's app id across a reload after the launch params are cleared A godmode token doesn't name the app, so once the desktop answers a tab's launch, the app id from the launch URL is stored the way a token's own app id is. * fix(hosting): a private app's sign-in page continues with the desktop's token and keeps the opened item In a tab the desktop opened, the sign-in page waits for the desktop's handoff, sends the handed token to its own URL in X-Puter-Auth-Token so the host sets its cookie, then loads the URL the tab was opened at. The token goes in the URL only after a redirect, a failed request, or on a click after a header try didn't load the app. Before leaving, the page keeps the opened item in sessionStorage, bound to the launch and a fingerprint of the handed token, for 5 minutes. The app's page takes it when it boots on that token in the same tab. Reading sessionStorage for it can't stop the SDK from booting where storage is blocked. --------- Co-authored-by: Salazareo <25314977+Salazareo@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../http/middleware/privateAppGate.test.ts | 321 ++++++++++++++++++ .../core/http/middleware/privateAppGate.ts | 81 ++++- .../core/http/middleware/puterSite.test.ts | 47 +++ src/docs/src/changelog.md | 6 + src/puter-js/src/index.environments.test.js | 229 +++++++++++++ src/puter-js/src/index.js | 90 ++++- src/puter-js/src/lib/launchToken.js | 109 +++++- src/puter-js/src/lib/launchToken.test.js | 141 +++++++- src/puter-js/src/modules/UI.js | 12 +- 9 files changed, 983 insertions(+), 53 deletions(-) diff --git a/src/backend/core/http/middleware/privateAppGate.test.ts b/src/backend/core/http/middleware/privateAppGate.test.ts index 996c355f5..01c3bf87f 100644 --- a/src/backend/core/http/middleware/privateAppGate.test.ts +++ b/src/backend/core/http/middleware/privateAppGate.test.ts @@ -552,6 +552,327 @@ describe('renderLoginBootstrapHtml', () => { }); }); +describe('the login bootstrap page script', () => { + const LAUNCH_URL = + 'https://priv.app.test/?puter.app_instance_id=i&puter.item.uid=f-1&page=2#/doc'; + const STRIPPED_URL = 'https://priv.app.test/?page=2#/doc'; + + type Button = { + disabled: boolean; + click?: () => Promise | void; + addEventListener: (type: string, fn: () => Promise | void) => void; + }; + const button = (): Button => ({ + disabled: false, + addEventListener(_type, fn) { + this.click = fn; + }, + }); + const flush = () => new Promise((resolve) => setImmediate(resolve)); + const OK = { type: 'basic', ok: true, status: 200 }; + const REDIRECT = { type: 'opaqueredirect', ok: false, status: 0 }; + + /** Runs the page's inline script against stand-ins for the browser. */ + const openPage = (opts: { + puter?: Record; + fetchResult?: object | Error; + lastAttempted?: string; + lastHeaderTry?: { t: string; at: number }; + href?: string; + }) => { + const script = renderLoginBootstrapHtml({ name: 'app' }).match( + / diff --git a/src/backend/core/http/middleware/puterSite.test.ts b/src/backend/core/http/middleware/puterSite.test.ts index 97da40d04..a58bbc05f 100644 --- a/src/backend/core/http/middleware/puterSite.test.ts +++ b/src/backend/core/http/middleware/puterSite.test.ts @@ -2187,6 +2187,53 @@ describe('createPuterSiteMiddleware — private app sign-in token', () => { }); }); + /** A same-origin fetch from the sign-in page, token in a header. */ + const fetchWithHeaderToken = async (headerToken: string) => { + const mw = buildMiddleware(); + const { res, out } = makeRes(); + await mw( + makeReq({ + hostname: host, + path: '/', + originalUrl: '/?puter.app_instance_id=i&a=1', + query: { 'puter.app_instance_id': 'i', a: '1' }, + headers: { + 'sec-fetch-dest': 'empty', + 'x-puter-auth-token': headerToken, + }, + }), + res, + vi.fn(), + ); + await new Promise((resolve) => setImmediate(resolve)); + return out; + }; + + it('sets the cookie for a fetch that sends the app token in a header, without redirecting', async () => { + const appToken = await server.services.auth.getUserAppToken( + actorFor(visitor), + appUid, + ); + const out = await fetchWithHeaderToken(appToken); + expect(out.redirected).toBeUndefined(); + expect(out.statusCode).toBe(200); + expect(out.cookies[cookieName()]).toBeTruthy(); + }); + + it('ignores a header token minted for another app', async () => { + const other = await server.stores.app.create( + { name: `${sub}-other`, title: 'other', index_url: 'http://other.test/' }, + { ownerUserId: owner.id }, + ); + const wrongToken = await server.services.auth.getUserAppToken( + actorFor(visitor), + other.uid, + ); + const out = await fetchWithHeaderToken(wrongToken); + expect(String(out.body)).toContain('Sign in required'); + expect(out.cookies[cookieName()]).toBeUndefined(); + }); + it('serves without redirecting when the cookie could not be minted', async () => { // Without the cookie, the clean URL would bounce back to sign-in. const spy = vi diff --git a/src/docs/src/changelog.md b/src/docs/src/changelog.md index a6a8aed3c..a4a83bd28 100644 --- a/src/docs/src/changelog.md +++ b/src/docs/src/changelog.md @@ -2,6 +2,12 @@ New features, changes, and fixes in Puter.js and the Puter APIs, grouped by day, newest first. +## November 23, 2026 + +- Changed Puter.js in an app that Puter opens in its own browser tab to remove the `puter.*` launch parameters from the address bar once the page has loaded, keeping the app's other query parameters and its URL hash. Code that reads them from `location.search` has to do so before or during the `load` event. +- Fixed [`puter.ui.onLaunchedWithItems()`](/UI/onLaunchedWithItems/) and [`puter.ui.wasLaunchedWithItems()`](/UI/wasLaunchedWithItems/) missing the opened item when the app changed its URL before calling them. +- Fixed a private app that Puter opens in its own browser tab missing the opened item from [`puter.ui.onLaunchedWithItems()`](/UI/onLaunchedWithItems/) when the user had to sign in to the app first. + ## November 22, 2026 - Fixed [`puter.fs.getReadURL()`](/FS/getReadURL/) refusing files that the app or user can read through access to a parent folder, such as a folder shared with the user. diff --git a/src/puter-js/src/index.environments.test.js b/src/puter-js/src/index.environments.test.js index 2c59e8dda..78faa903b 100644 --- a/src/puter-js/src/index.environments.test.js +++ b/src/puter-js/src/index.environments.test.js @@ -205,6 +205,19 @@ describe('app launch parameters', () => { expect(puter.appDataPath).toBe('~/AppData/app-stored'); }); + it('hands over the opened item after the app has changed its URL', async () => { + const readURL = encodeURIComponent('https://api.test/file?uid=f-1'); + const puter = await bootApp( + `${LAUNCH}&puter.item.name=a.txt&puter.item.uid=f-1&puter.item.path=%2Fu%2Fa.txt&puter.item.read_url=${readURL}`, + ); + history.replaceState(null, '', '/app/editor'); + + const launched = vi.fn(); + puter.ui.onLaunchedWithItems(launched); + expect(puter.ui.wasLaunchedWithItems()).toBe(true); + expect(launched.mock.calls[0][0][0].uid).toBe('f-1'); + }); + it('strips the launch token a task later when the page has already loaded', async () => { Object.defineProperty(document, 'readyState', { value: 'complete', configurable: true }); const puter = await bootApp(); @@ -521,6 +534,222 @@ describe('a tab the desktop opened for an app', () => { }); expect(puter.authToken).toBeFalsy(); }); + + it('clears the launch params from its address bar once the page loads', async () => { + const puter = await bootWeb( + `${LAUNCH}&page=2&puter.app.id=app-1&puter.args=%7B%22a%22%3A1%7D` + + '&puter.notification=n-1&utm_source=puter.com#/inbox', + ); + await flush(); + expect(new URLSearchParams(location.search).get('puter.app.id')).toBe('app-1'); + + window.dispatchEvent(new Event('load')); + await flush(); + + expect(location.pathname).toBe('/site/index.html'); + expect(location.search).toBe('?page=2&puter.notification=n-1&utm_source=puter.com'); + expect(location.hash).toBe('#/inbox'); + expect(puter.appInstanceID).toBe('i'); + expect(puter.appID).toBe('app-1'); + expect(puter.args).toEqual({ a: 1 }); + }); + + it('keeps a godmode app\'s id for a reload after the params are cleared', async () => { + const godmodeToken = jwt({ t: 's', v: '2', godmode_app_uid: 'app-1' }); + const opener = { + closed: false, + postMessage: (data, guiOrigin) => window.dispatchEvent(new MessageEvent('message', { + origin: guiOrigin, + source: opener, + data: { msg: 'puter.launch', appInstanceID: data.appInstanceID, token: godmodeToken }, + })), + }; + Object.defineProperty(globalThis, 'opener', { value: opener, configurable: true, writable: true }); + const puter = await bootWeb(`${LAUNCH}&puter.app.id=app-1`); + await puter.openerLaunch_; + window.dispatchEvent(new Event('load')); + await flush(); + expect(location.search).toBe(''); + + const reloaded = await bootWeb(); + expect(reloaded.authToken).toBe(godmodeToken); + expect(reloaded.appID).toBe('app-1'); + expect(reloaded.appDataPath).toBe('~/AppData/app-1'); + }); + + it('hands the opened item to the next page of the launch when one keeps it', async () => { + const item = { + 'puter.item.name': 'notes.txt', + 'puter.item.uid': 'f-1', + 'puter.item.path': '~/notes.txt', + 'puter.item.read_url': 'https://api.test/file?uid=f-1', + }; + const opener = { + closed: false, + postMessage: (data, guiOrigin) => window.dispatchEvent(new MessageEvent('message', { + origin: guiOrigin, + source: opener, + data: { msg: 'puter.launch', appInstanceID: data.appInstanceID, token: APP_TOKEN, item }, + })), + }; + Object.defineProperty(globalThis, 'opener', { value: opener, configurable: true, writable: true }); + const search = `${LAUNCH}&puter.item.uid=f-1`; + // The sign-in page: takes the launch, keeps its item, and moves on. + const signInPage = await bootWeb(search); + await signInPage.keepTabLaunchForNextPage_(APP_TOKEN); + + const app = await bootWeb(search); + expect(app.openerLaunch_).toBeNull(); + expect(app.ui.wasLaunchedWithItems()).toBe(true); + const launched = vi.fn(); + app.ui.onLaunchedWithItems(launched); + expect(launched.mock.calls[0][0][0].uid).toBe('f-1'); + + const reloaded = await bootWeb(search); + expect(reloaded.ui.wasLaunchedWithItems()).toBe(false); + }); + + it('keeps the opened item from a next page that runs on another token', async () => { + const opener = { + closed: false, + postMessage: (data, guiOrigin) => window.dispatchEvent(new MessageEvent('message', { + origin: guiOrigin, + source: opener, + data: { + msg: 'puter.launch', + appInstanceID: data.appInstanceID, + token: APP_TOKEN, + item: { + 'puter.item.name': 'notes.txt', + 'puter.item.uid': 'f-1', + 'puter.item.path': '~/notes.txt', + 'puter.item.read_url': 'https://api.test/file?uid=f-1', + }, + }, + })), + }; + Object.defineProperty(globalThis, 'opener', { value: opener, configurable: true, writable: true }); + const search = `${LAUNCH}&puter.item.uid=f-1`; + const signInPage = await bootWeb(search); + await signInPage.keepTabLaunchForNextPage_(APP_TOKEN); + // Another tab of the app signed in as someone else meanwhile. + const otherToken = jwt({ t: 'au', v: '2', au: Buffer.alloc(16, 2).toString('base64') }); + localStorage.setItem(STORAGE_KEY, otherToken); + + const app = await bootWeb(search); + expect(app.authToken).toBe(otherToken); + expect(app.ui.wasLaunchedWithItems()).toBe(false); + expect(sessionStorage.getItem('puter.launch.keptItem')).toBeNull(); + }); + + it('keeps nothing for the next page when the launch had no item', async () => { + const opener = { + closed: false, + postMessage: (data, guiOrigin) => window.dispatchEvent(new MessageEvent('message', { + origin: guiOrigin, + source: opener, + data: { msg: 'puter.launch', appInstanceID: data.appInstanceID, token: APP_TOKEN }, + })), + }; + Object.defineProperty(globalThis, 'opener', { value: opener, configurable: true, writable: true }); + const signInPage = await bootWeb(LAUNCH); + await signInPage.keepTabLaunchForNextPage_(APP_TOKEN); + + expect(sessionStorage.length).toBe(0); + }); + + it('keeps nothing for a sign-in with a token other than the one handed over', async () => { + const opener = { + closed: false, + postMessage: (data, guiOrigin) => window.dispatchEvent(new MessageEvent('message', { + origin: guiOrigin, + source: opener, + data: { + msg: 'puter.launch', + appInstanceID: data.appInstanceID, + token: APP_TOKEN, + item: { 'puter.item.uid': 'f-1', 'puter.item.name': 'a.txt' }, + }, + })), + }; + Object.defineProperty(globalThis, 'opener', { value: opener, configurable: true, writable: true }); + const signInPage = await bootWeb(LAUNCH); + await signInPage.keepTabLaunchForNextPage_(PLAIN_TOKEN); + await signInPage.keepTabLaunchForNextPage_(); + + expect(sessionStorage.getItem('puter.launch.keptItem')).toBeNull(); + }); + + it('boots a reloaded tab where storage is blocked', async () => { + const realSession = Object.getOwnPropertyDescriptor(window, 'sessionStorage'); + Object.defineProperty(window, 'sessionStorage', { + configurable: true, + get() { + throw new DOMException('denied', 'SecurityError'); + }, + }); + try { + const puter = await bootWeb(`${LAUNCH}&puter.item.uid=f-1`); + expect(puter.ui.wasLaunchedWithItems()).toBe(false); + } finally { + Object.defineProperty(window, 'sessionStorage', realSession); + } + }); + + it('leaves puter.* params the app put in its URL after launch', async () => { + await bootWeb(`${LAUNCH}&puter.app.id=app-1`); + history.replaceState(null, '', '/site/index.html?puter.view=list&puter.app.id=app-1'); + window.dispatchEvent(new Event('load')); + await flush(); + expect(location.search).toBe('?puter.view=list'); + }); + + it('still delivers the opened item when it arrives after the params are cleared', async () => { + let answer; + const opener = { + closed: false, + postMessage: (data, guiOrigin) => { + answer = () => window.dispatchEvent(new MessageEvent('message', { + origin: guiOrigin, + source: opener, + data: { + msg: 'puter.launch', + appInstanceID: data.appInstanceID, + item: { + 'puter.item.name': 'notes.txt', + 'puter.item.uid': 'f-1', + 'puter.item.path': '~/notes.txt', + 'puter.item.read_url': 'https://api.test/file?uid=f-1', + }, + }, + })); + }, + }; + Object.defineProperty(globalThis, 'opener', { value: opener, configurable: true, writable: true }); + const puter = await bootWeb(`${LAUNCH}&puter.item.uid=f-1`); + window.dispatchEvent(new Event('load')); + await flush(); + expect(location.search).toBe(''); + + expect(puter.ui.wasLaunchedWithItems()).toBe(true); + const launched = vi.fn(); + puter.ui.onLaunchedWithItems(launched); + answer(); + await puter.openerLaunch_; + await flush(); + + expect(launched).toHaveBeenCalledOnce(); + expect(launched.mock.calls[0][0][0].uid).toBe('f-1'); + }); +}); + +describe('a web page the desktop did not launch', () => { + it('keeps its own puter.* query params', async () => { + await bootWeb('?puter.theme=dark&x=1'); + window.dispatchEvent(new Event('load')); + await flush(); + expect(location.search).toBe('?puter.theme=dark&x=1'); + }); }); describe('logger prefix', () => { diff --git a/src/puter-js/src/index.js b/src/puter-js/src/index.js index 53dca9864..7ba120e61 100644 --- a/src/puter-js/src/index.js +++ b/src/puter-js/src/index.js @@ -8,8 +8,11 @@ import { isFramedDocument } from './lib/appModeGate.js'; import { isGodmodeTokenPayload, isUserSessionTokenPayload, + keepLaunchItem, requestLaunchFromOpener, - urlWithoutQueryParam, + takeKeptLaunchItem, + tokenTag, + urlWithoutQueryParams, } from './lib/launchToken.js'; import path from 'path-browserify'; import localStorageMemory from './lib/polyfills/localStorage.js'; @@ -26,7 +29,7 @@ import FSItem from './modules/FSItem.js'; import { Hosting } from './modules/hosting/index.js'; import { KV } from './modules/kv/index.js'; import { netAPI } from './modules/networking/index.js'; -import { Notifications } from './modules/notifications/index.js'; +import { CLICK_PARAM, Notifications } from './modules/notifications/index.js'; import { OS } from './modules/os/index.js'; import { Perms } from './modules/perms/index.js'; import PuterDialog from './modules/PuterDialog.js'; @@ -334,6 +337,14 @@ export class Puter { */ openerLaunchItem_ = null; + /** + * Fingerprint of the token this tab's launch came with, if any. + * + * @internal + * @type {string | null} + */ + openerLaunchTokenTag_ = null; + /** * Whether this is a tab the GUI opened for an app and handed a session * token, which it then keeps in sessionStorage the way a framed app does. @@ -747,7 +758,9 @@ export class Puter { URLParams.get(urlTokenParam), ); if (bootstrapAuthToken) { - this.stripLaunchTokenFromUrl_(urlTokenParam); + this.stripParamsFromUrlAfterLoad_( + (name) => name === urlTokenParam, + ); } try { let selectedAuthToken = bootstrapAuthToken; @@ -871,6 +884,32 @@ export class Puter { appInstanceID: this.appInstanceID, }) : null; + // The launch params only describe the launch, so they're cleared + // from the tab's address bar. A framed app keeps them: its URL + // isn't shown, and reloading the frame needs them. + if (this.appInstanceID) { + const launchParams = new Set( + [...URLParams.keys()].filter( + (name) => + name.startsWith('puter.') && name !== CLICK_PARAM, + ), + ); + this.stripParamsFromUrlAfterLoad_((name) => + launchParams.has(name), + ); + } + if (this.appInstanceID && !openerLaunch) { + // A page this tab loaded earlier for the same launch, such as + // a private app's sign-in page, may have kept its item. + const keptItem = takeKeptLaunchItem({ + appInstanceID: this.appInstanceID, + token: this.authToken, + }); + if (keptItem) { + this.openerLaunchItem_ = new URLSearchParams(keptItem); + this.openerLaunchTokenTag_ = tokenTag(this.authToken); + } + } if (openerLaunch) { this.openerLaunch_ = openerLaunch.then((launch) => { this.openerLaunch_ = null; @@ -880,10 +919,14 @@ export class Puter { ); } if (launch?.token) { + this.openerLaunchTokenTag_ = tokenTag(launch.token); this.appTabSession_ = this.isUserSessionToken_( launch.token, ); this.setAuthToken(launch.token); + // A godmode token doesn't name the app, and a reload + // won't have the app id in the URL any more. + if (this.appID) this.setAppID(this.appID); } }); } @@ -1623,18 +1666,19 @@ export class Puter { /** * @internal - * Remove the launch token from the address bar after the page loads, so it - * stops going out in Referer headers and in anything that records the page - * URL. Waiting for `load` keeps it readable to the app's own boot code. + * Remove launch params from the page URL after the page loads, so they + * stop showing in the address bar, going out in Referer headers, and + * landing in anything that records the page URL. Waiting for `load` keeps + * them readable to the app's own boot code. * - * @param {string} param + * @param {(name: string) => boolean} shouldRemove */ - stripLaunchTokenFromUrl_ = function (param) { + stripParamsFromUrlAfterLoad_ = function (shouldRemove) { const strip = () => { try { - const cleaned = urlWithoutQueryParam( + const cleaned = urlWithoutQueryParams( globalThis.location.href, - param, + shouldRemove, ); if (cleaned) { globalThis.history.replaceState( @@ -1656,6 +1700,32 @@ export class Puter { } }; + /** + * @internal + * For a page that sends this tab on to another page of the same launch + * (a private app's sign-in page): waits for the launch the GUI hands the + * tab, then keeps its opened item for the next page when that page signs + * in with `token` and it's the token the launch came with. + * + * @param {string} [token] + * @returns {Promise} + */ + keepTabLaunchForNextPage_ = async function (token) { + await this.openerLaunch_; + if ( + token && + tokenTag(token) === this.openerLaunchTokenTag_ && + this.appInstanceID && + this.openerLaunchItem_ + ) { + keepLaunchItem({ + appInstanceID: this.appInstanceID, + item: Object.fromEntries(this.openerLaunchItem_), + token, + }); + } + }; + exit = function (statusCode = 0) { if (statusCode && typeof statusCode !== 'number') { console.warn( diff --git a/src/puter-js/src/lib/launchToken.js b/src/puter-js/src/lib/launchToken.js index 322d89a42..23aa1e9ec 100644 --- a/src/puter-js/src/lib/launchToken.js +++ b/src/puter-js/src/lib/launchToken.js @@ -1,13 +1,13 @@ /** - * `href` with every `name` query parameter removed, or null when it has none. - * Works on the raw query string so the parameters that stay keep their exact - * encoding. + * `href` without the query parameters whose decoded name `shouldRemove` + * matches, or null when it has none. Works on the raw query string so the + * parameters that stay keep their exact encoding. * * @param {string} href - * @param {string} name + * @param {(name: string) => boolean} shouldRemove * @returns {string | null} */ -export const urlWithoutQueryParam = (href, name) => { +export const urlWithoutQueryParams = (href, shouldRemove) => { let url; try { url = new URL(href); @@ -17,9 +17,9 @@ export const urlWithoutQueryParam = (href, name) => { const isTarget = (part) => { const rawKey = part.split('=', 1)[0].replace(/\+/g, ' '); try { - return decodeURIComponent(rawKey) === name; + return shouldRemove(decodeURIComponent(rawKey)); } catch { - return rawKey === name; + return shouldRemove(rawKey); } }; const parts = url.search.slice(1).split('&'); @@ -80,6 +80,101 @@ const launchItemParams = (item) => { return Object.keys(params).length ? params : null; }; +/** + * A short fingerprint of a token (cyrb53), to tell tokens apart without + * keeping one. + * + * @param {string} token + * @returns {string} + */ +export const tokenTag = (token) => { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < token.length; i++) { + const c = token.charCodeAt(i); + h1 = Math.imul(h1 ^ c, 2654435761); + h2 = Math.imul(h2 ^ c, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507); + h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507); + h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36); +}; + +const KEPT_LAUNCH_ITEM_KEY = 'puter.launch.keptItem'; +// Covers a sign-in redirect and the app's load, not a later visit. +const KEPT_LAUNCH_ITEM_TTL_MS = 5 * 60 * 1000; + +/** + * Keeps the item a tab launch opened for the next page this tab loads for the + * same launch, which can't ask the GUI for it again, when that page runs on + * `token`. sessionStorage keeps it to this tab and origin. + * + * @param {object} options + * @param {string} options.appInstanceID + * @param {Record} options.item - `puter.item.*` params + * @param {string} options.token + * @param {typeof globalThis} [options.scope] - Global to use; injectable for tests. + * @param {number} [options.now] + */ +export const keepLaunchItem = ({ + appInstanceID, + item, + token, + scope = globalThis, + now = Date.now(), +}) => { + try { + // Reading `sessionStorage` itself throws where storage is blocked. + scope.sessionStorage.setItem( + KEPT_LAUNCH_ITEM_KEY, + JSON.stringify({ + appInstanceID, + item, + tokenTag: tokenTag(token), + at: now, + }), + ); + } catch { + // No sessionStorage: the next page opens without the item. + } +}; + +/** + * Removes the kept launch item and returns it when it was kept for + * `appInstanceID` and `token` within the last few minutes, or null. + * + * @param {object} options + * @param {string} options.appInstanceID + * @param {string | null | undefined} options.token - the token this page runs on + * @param {typeof globalThis} [options.scope] - Global to use; injectable for tests. + * @param {number} [options.now] + * @returns {Record | null} + */ +export const takeKeptLaunchItem = ({ + appInstanceID, + token, + scope = globalThis, + now = Date.now(), +}) => { + let kept; + try { + const storage = scope.sessionStorage; + const raw = storage.getItem(KEPT_LAUNCH_ITEM_KEY); + if (raw === null) return null; + storage.removeItem(KEPT_LAUNCH_ITEM_KEY); + kept = JSON.parse(raw); + } catch { + return null; + } + if (kept?.appInstanceID !== appInstanceID) return null; + if (!token || kept.tokenTag !== tokenTag(token)) return null; + const age = now - kept.at; + if (!(age >= 0 && age <= KEPT_LAUNCH_ITEM_TTL_MS)) return null; + return launchItemParams(kept.item); +}; + /** * Asks the Puter GUI tab that opened this one for the launch it opened the * tab for (the app's token and opened item), so neither has to travel in the diff --git a/src/puter-js/src/lib/launchToken.test.js b/src/puter-js/src/lib/launchToken.test.js index 9c87afe20..907b4f165 100644 --- a/src/puter-js/src/lib/launchToken.test.js +++ b/src/puter-js/src/lib/launchToken.test.js @@ -2,29 +2,44 @@ import { describe, expect, it, vi } from 'vitest'; import { isGodmodeTokenPayload, isUserSessionTokenPayload, + keepLaunchItem, requestLaunchFromOpener, - urlWithoutQueryParam, + takeKeptLaunchItem, + tokenTag, + urlWithoutQueryParams, } from './launchToken.js'; -describe('urlWithoutQueryParam', () => { - it('removes the parameter and keeps the rest of the URL', () => { +describe('urlWithoutQueryParams', () => { + const named = (target) => (name) => name === target; + + it('removes the matching parameter and keeps the rest of the URL', () => { expect( - urlWithoutQueryParam( + urlWithoutQueryParams( 'https://app.example/p?puter.app_instance_id=i' + '&puter.auth.token=T&x=1#h', - 'puter.auth.token', + named('puter.auth.token'), ), ).toBe('https://app.example/p?puter.app_instance_id=i&x=1#h'); }); + it('removes every parameter the predicate matches', () => { + expect( + urlWithoutQueryParams( + 'https://app.example/p?puter.app_instance_id=i&page=2' + + '&puter.args=%7B%7D&utm_source=puter.com#h', + (name) => name.startsWith('puter.'), + ), + ).toBe('https://app.example/p?page=2&utm_source=puter.com#h'); + }); + it('keeps the encoding of the parameters that stay', () => { // Re-serializing through URLSearchParams would turn %20 into `+`, // which changes the value for apps that parse the query by hand. expect( - urlWithoutQueryParam( + urlWithoutQueryParams( 'https://app.example/?puter.item.name=My%20File%2B1.txt' + '&puter.auth.token=T&puter.args=%7B%22a%22%3A1%7D', - 'puter.auth.token', + named('puter.auth.token'), ), ).toBe( 'https://app.example/?puter.item.name=My%20File%2B1.txt&puter.args=%7B%22a%22%3A1%7D', @@ -33,42 +48,134 @@ describe('urlWithoutQueryParam', () => { it('drops the query entirely when nothing else is left', () => { expect( - urlWithoutQueryParam( + urlWithoutQueryParams( 'https://app.example/index.html?puter.auth.token=T', - 'puter.auth.token', + named('puter.auth.token'), ), ).toBe('https://app.example/index.html'); }); it('removes every occurrence, including a percent-encoded key', () => { expect( - urlWithoutQueryParam( + urlWithoutQueryParams( 'https://app.example/?auth_token=a&k=v&auth%5Ftoken=b', - 'auth_token', + named('auth_token'), ), ).toBe('https://app.example/?k=v'); }); it('leaves parameters that only share a prefix', () => { expect( - urlWithoutQueryParam( + urlWithoutQueryParams( 'https://app.example/?puter.auth.token=T&puter.auth.username=u', - 'puter.auth.token', + named('puter.auth.token'), ), ).toBe('https://app.example/?puter.auth.username=u'); }); it('returns null when there is nothing to remove', () => { expect( - urlWithoutQueryParam( + urlWithoutQueryParams( 'https://app.example/?puter.auth.username=u', - 'puter.auth.token', + named('puter.auth.token'), ), ).toBeNull(); expect( - urlWithoutQueryParam('https://app.example/', 'puter.auth.token'), + urlWithoutQueryParams( + 'https://app.example/', + named('puter.auth.token'), + ), ).toBeNull(); - expect(urlWithoutQueryParam('not a url', 'puter.auth.token')).toBeNull(); + expect( + urlWithoutQueryParams('not a url', named('puter.auth.token')), + ).toBeNull(); + }); +}); + +describe('kept launch items', () => { + const memoryScope = () => { + const map = new Map(); + return { + sessionStorage: { + getItem: (key) => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => map.set(key, String(value)), + removeItem: (key) => map.delete(key), + }, + map, + }; + }; + const item = { 'puter.item.uid': 'f-1', 'puter.item.name': 'a.txt' }; + const keep = (scope, now, extra = {}) => + keepLaunchItem({ appInstanceID: 'i-1', item, token: 'T', scope, now, ...extra }); + const take = (scope, now, extra = {}) => + takeKeptLaunchItem({ appInstanceID: 'i-1', token: 'T', scope, now, ...extra }); + + it('hands the item to the next page of the same launch, once', () => { + const scope = memoryScope(); + keep(scope, 1000); + + expect(take(scope, 2000)).toEqual(item); + expect(take(scope, 2000)).toBeNull(); + }); + + it('keeps a fingerprint of the token, not the token', () => { + const scope = memoryScope(); + keep(scope, 1000, { token: 'header.payload.signature' }); + + expect([...scope.map.values()].join()).not.toContain('signature'); + }); + + it('drops an item kept for another launch or another token', () => { + const scope = memoryScope(); + keep(scope, 1000); + expect(take(scope, 2000, { appInstanceID: 'i-2' })).toBeNull(); + expect(scope.map.size).toBe(0); + + keep(scope, 1000); + expect(take(scope, 2000, { token: 'OTHER' })).toBeNull(); + keep(scope, 1000); + expect(take(scope, 2000, { token: null })).toBeNull(); + }); + + it('drops an item kept too long ago, or with a time in the future', () => { + const scope = memoryScope(); + keep(scope, 0); + expect(take(scope, 5 * 60 * 1000 + 1)).toBeNull(); + + keep(scope, 10_000); + expect(take(scope, 0)).toBeNull(); + }); + + it('keeps only puter.item.* string params', () => { + const scope = memoryScope(); + keep(scope, 1000, { + item: { ...item, 'puter.auth.token': 'T', 'puter.item.size': 3 }, + }); + + expect(take(scope, 1000)).toEqual(item); + }); + + it('returns null for a malformed entry', () => { + const scope = memoryScope(); + scope.sessionStorage.setItem('puter.launch.keptItem', '{not json'); + expect(take(scope)).toBeNull(); + }); + + it('does nothing where storage is blocked', () => { + const blocked = { + get sessionStorage() { + throw new DOMException('denied', 'SecurityError'); + }, + }; + expect(() => keep(blocked)).not.toThrow(); + expect(take(blocked)).toBeNull(); + }); +}); + +describe('tokenTag', () => { + it('is stable for a token and differs between tokens', () => { + expect(tokenTag('a.b.c')).toBe(tokenTag('a.b.c')); + expect(tokenTag('a.b.c')).not.toBe(tokenTag('a.b.d')); }); }); diff --git a/src/puter-js/src/modules/UI.js b/src/puter-js/src/modules/UI.js index 8815559b9..41d51da17 100644 --- a/src/puter-js/src/modules/UI.js +++ b/src/puter-js/src/modules/UI.js @@ -556,9 +556,11 @@ export class UIModule extends EventListener { // we start from 1 because 0 is falsy and we want to avoid that for the message id #messageID = 1; - // Read once at load: an app's router may rewrite the URL afterwards. - #guiFeatures = new URLSearchParams(globalThis.location?.search ?? '') - .get('puter.gui_features')?.split(',') ?? []; + // Read once at load: an app's router may rewrite the URL afterwards, and + // an app tab's launch params are cleared from its address bar. + #launchParams = new URLSearchParams(globalThis.location?.search ?? ''); + + #guiFeatures = this.#launchParams.get('puter.gui_features')?.split(',') ?? []; // Set while the framed feedback dialog is open on a first-party page. #feedbackEmbedOpen = false; @@ -1274,7 +1276,7 @@ export class UIModule extends EventListener { * @returns {FSItem|null} */ #launchItem () { - let URLParams = new URLSearchParams(globalThis.location.search); + let URLParams = this.#launchParams; if ( !hasLaunchItemParams(URLParams) && puter.openerLaunchItem_ ) { URLParams = puter.openerLaunchItem_; } @@ -1344,7 +1346,7 @@ export class UIModule extends EventListener { * @returns {boolean} */ wasLaunchedWithItems () { - const URLParams = new URLSearchParams(globalThis.location.search); + const URLParams = this.#launchParams; if ( hasLaunchItemParams(URLParams) || puter.openerLaunchItem_ ) { return true; }