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>
This commit is contained in:
authored and GitHub committed 2026-11-23 11:33:48 -07:00
1 parent 19ae43b02b
commit 522c5af1a7
9 files changed
+983 -53

No files matched your search

@@ -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> | void;
addEventListener: (type: string, fn: () => Promise<void> | 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<string, unknown>;
fetchResult?: object | Error;
lastAttempted?: string;
lastHeaderTry?: { t: string; at: number };
href?: string;
}) => {
const script = renderLoginBootstrapHtml({ name: 'app' }).match(
/<script>([\s\S]*?)<\/script>/,
)![1];
const elements = {
status: { textContent: '' },
loginButton: button(),
retryButton: button(),
};
const replaced: string[] = [];
const location = {
href: opts.href ?? LAUNCH_URL,
reloads: 0,
replace: (url: string) => replaced.push(url),
reload() {
this.reloads++;
},
};
const session = new Map<string, string>();
if (opts.lastAttempted) {
session.set(
'puter.privateAppBootstrap.lastAttemptedToken',
opts.lastAttempted,
);
}
if (opts.lastHeaderTry) {
session.set(
'puter.privateAppBootstrap.lastHeaderTry',
JSON.stringify(opts.lastHeaderTry),
);
}
const fetches: Array<[string, RequestInit]> = [];
const fetchStub = async (url: string, init: RequestInit) => {
fetches.push([url, init]);
if (opts.fetchResult instanceof Error) throw opts.fetchResult;
return opts.fetchResult ?? OK;
};
new Function(
'document',
'location',
'fetch',
'sessionStorage',
'localStorage',
'globalThis',
'console',
script,
)(
{ getElementById: (id: keyof typeof elements) => elements[id] },
location,
fetchStub,
{
getItem: (key: string) => session.get(key) ?? null,
setItem: (key: string, value: string) => session.set(key, value),
},
{ getItem: () => null },
{ puter: opts.puter },
{ error: () => {} },
);
return { elements, location, replaced, fetches };
};
/** A puter.js whose desktop handoff settles when `handOver` is called. */
const desktopTab = () => {
let handOver!: (token: string) => void;
const kept: unknown[] = [];
const puter: Record<string, unknown> = { authToken: null };
const settled = new Promise<void>((resolve) => {
handOver = (token) => {
puter.authToken = token;
resolve();
};
});
puter.keepTabLaunchForNextPage_ = (token?: string) => {
kept.push(token);
return settled;
};
return { puter, handOver, kept };
};
const urlToken = (url: string) =>
new URL(url).searchParams.get('puter.auth.token');
it('signs in with the token the desktop hands over, keeping it out of the URL', async () => {
const { puter, handOver, kept } = desktopTab();
const page = openPage({ puter });
// puter.js clears the launch params from the address bar after load.
page.location.href = STRIPPED_URL;
handOver('T');
await flush();
expect(page.fetches).toHaveLength(1);
const [url, init] = page.fetches[0];
expect(url).toBe(LAUNCH_URL);
expect(init).toMatchObject({
headers: { 'X-Puter-Auth-Token': 'T' },
credentials: 'same-origin',
redirect: 'manual',
});
expect(page.replaced).toEqual([LAUNCH_URL]);
// The opened item is kept only for a sign-in with the handed token.
expect(kept).toContain('T');
});
it('reloads when the app URL differs from the page only in its hash', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({ puter });
handOver('T');
await flush();
expect(page.fetches).toHaveLength(1);
expect(page.replaced).toEqual([]);
expect(page.location.reloads).toBe(1);
});
it('goes to the app without the token for any answer other than a redirect', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({ puter, fetchResult: { type: 'basic', ok: false, status: 404 } });
page.location.href = STRIPPED_URL;
handOver('T');
await flush();
expect(page.replaced).toEqual([LAUNCH_URL]);
});
it('falls back to the token in the URL when the host redirects instead', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({ puter, fetchResult: REDIRECT });
handOver('T');
await flush();
const target = new URL(page.replaced[0]);
expect(target.searchParams.get('puter.auth.token')).toBe('T');
expect(target.searchParams.get('puter.app_instance_id')).toBe('i');
expect(target.hash).toBe('#/doc');
});
it('falls back to the token in the URL when the request fails', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({ puter, fetchResult: new Error('offline') });
handOver('T');
await flush();
expect(urlToken(page.replaced[0])).toBe('T');
});
it('waits for a click, then goes the URL way, when a header sign-in with the token just now did not load the app', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({ puter, lastHeaderTry: { t: 'T', at: Date.now() } });
handOver('T');
await flush();
expect(page.fetches).toEqual([]);
expect(page.replaced).toEqual([]);
await page.elements.loginButton.click!();
await flush();
expect(page.fetches).toEqual([]);
expect(urlToken(page.replaced[0])).toBe('T');
});
it('uses the token the desktop hands over when clicked before it arrives', async () => {
const { puter, handOver } = desktopTab();
puter.authToken = 'STORED';
// The stored token already failed, so nothing starts without a click.
const page = openPage({ puter, lastAttempted: 'STORED' });
const clicked = page.elements.loginButton.click!();
handOver('FRESH');
await clicked;
await flush();
expect(page.fetches).toHaveLength(1);
expect(page.fetches[0][1]).toMatchObject({
headers: { 'X-Puter-Auth-Token': 'FRESH' },
});
});
it('uses the header again when the earlier header sign-in was a while ago', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({
puter,
lastHeaderTry: { t: 'T', at: Date.now() - 2 * 60 * 1000 },
});
page.location.href = STRIPPED_URL;
handOver('T');
await flush();
expect(page.fetches).toHaveLength(1);
expect(page.replaced).toEqual([LAUNCH_URL]);
});
it('prefers the token the desktop hands over to a stored one', async () => {
const { puter, handOver } = desktopTab();
puter.authToken = 'STORED';
const page = openPage({ puter });
handOver('FRESH');
await flush();
expect(page.fetches[0][1]).toMatchObject({
headers: { 'X-Puter-Auth-Token': 'FRESH' },
});
});
it('waits for a click when no token was handed over', async () => {
const page = openPage({
puter: {
authToken: null,
keepTabLaunchForNextPage_: () => Promise.resolve(),
},
});
await flush();
expect(page.fetches).toEqual([]);
expect(page.replaced).toEqual([]);
expect(page.elements.loginButton.disabled).toBe(false);
});
it('does not retry a token that already failed', async () => {
const { puter, handOver } = desktopTab();
const page = openPage({ puter, lastAttempted: 'T' });
handOver('T');
await flush();
expect(page.fetches).toEqual([]);
expect(page.replaced).toEqual([]);
});
it('signs in through puter.js on a click, returning to the URL the tab opened at', async () => {
const kept: unknown[] = [];
const puter = {
authToken: null,
keepTabLaunchForNextPage_: (token?: string) => {
kept.push(token);
return Promise.resolve();
},
auth: { signIn: async () => ({ token: 'S' }) },
};
const page = openPage({ puter });
await flush();
page.location.href = STRIPPED_URL;
await page.elements.loginButton.click!();
await flush();
expect(page.fetches[0][1]).toMatchObject({
headers: { 'X-Puter-Auth-Token': 'S' },
});
expect(page.replaced).toEqual([LAUNCH_URL]);
expect(kept.filter(Boolean)).toEqual(['S']);
});
it('replaces a rejected token in the URL with the new one, as the host reads that first', async () => {
const puter = {
authToken: null,
keepTabLaunchForNextPage_: () => Promise.resolve(),
auth: { signIn: async () => ({ token: 'S' }) },
};
const page = openPage({
puter,
href: `${LAUNCH_URL.split('#')[0]}&puter.auth.token=STALE`,
});
await flush();
expect(page.replaced).toEqual([]);
await page.elements.loginButton.click!();
await flush();
expect(page.fetches).toEqual([]);
expect(urlToken(page.replaced[0])).toBe('S');
});
it('still signs in with a stored token on an older puter.js', async () => {
const page = openPage({ puter: { authToken: 'OLD' } });
page.location.href = STRIPPED_URL;
await flush();
expect(page.fetches[0][1]).toMatchObject({
headers: { 'X-Puter-Auth-Token': 'OLD' },
});
expect(page.replaced).toEqual([LAUNCH_URL]);
});
it('retries at the URL the tab opened at', async () => {
const page = openPage({ puter: { authToken: null } });
page.location.href = STRIPPED_URL;
page.elements.retryButton.click!();
expect(page.replaced).toEqual([LAUNCH_URL]);
});
it('retries with a reload when the URL has not changed', async () => {
const page = openPage({ puter: { authToken: null } });
page.elements.retryButton.click!();
expect(page.replaced).toEqual([]);
expect(page.location.reloads).toBe(1);
});
});
// ── Server-backed helpers (AuthService + DB) ─────────────────────────
//
// `resolveOwnedAppForHostedSite` queries the apps table directly;
@@ -758,10 +758,10 @@ export function buildAppCenterFallback(
// -- Login bootstrap HTML --------------------------------------------
/**
* Minimal HTML page that prompts the visitor to sign in with Puter. Uses
* puter.js's `auth.signIn` to get a token, then redirects back to the same URL
* with `?puter.auth.token=…` so the middleware can resolve identity on the next
* request.
* Minimal HTML page that prompts the visitor to sign in with Puter. Takes the
* token a desktop-opened tab is handed, a stored one, or one from puter.js's
* `auth.signIn`, sends it to the same URL in a header so the middleware sets
* its cookie, then loads the URL the tab was opened at.
*
* Kept inline (no template engine dependency). Ported from v1's
* `respondPrivateLoginBootstrap` with non-essential bells removed.
@@ -814,41 +814,94 @@ const status = document.getElementById('status');
const loginBtn = document.getElementById('loginButton');
const retryBtn = document.getElementById('retryButton');
const storageKey = 'puter.privateAppBootstrap.lastAttemptedToken';
const headerKey = 'puter.privateAppBootstrap.lastHeaderTry';
// Read before puter.js clears a tab launch's params from the address bar.
const launchUrl = location.href;
// In a tab the desktop opened, settles once the desktop has handed over its
// token. Signing in with that token keeps the opened item for the app's page.
const keepLaunch = t => Promise.resolve(globalThis.puter?.keepTabLaunchForNextPage_?.(t)).catch(() => {});
// A URL that differs only in its hash would just scroll, so reload instead.
const openLaunchUrl = () => {
if (location.href.split('#')[0] === launchUrl.split('#')[0]) location.reload();
else location.replace(launchUrl);
};
let continuing = false;
const setStatus = m => { status.textContent = m; };
const getStored = () => globalThis.puter?.authToken || localStorage.getItem('auth_token') || localStorage.getItem('puter.auth.token');
const redirectWithToken = t => {
if (typeof t !== 'string' || !t) throw new Error('missing_auth_token');
sessionStorage.setItem(storageKey, t);
const u = new URL(location.href);
const u = new URL(launchUrl);
u.searchParams.set('puter.auth.token', t);
location.replace(u.toString());
};
const tryStored = () => {
const u = new URL(location.href);
// The token goes in a header, keeping it out of the address bar and history.
// The response sets this host's cookie, then the app loads. The token goes in
// the URL instead when the host redirects (no access) or the request fails, so
// the browser follows it; on a click after a header try with it just now
// didn't get the app to load; and when the URL already has a token, which the
// host reads first.
const launchUrlHasToken = ['puter.auth.token', 'auth_token'].some(k => new URL(launchUrl).searchParams.has(k));
const viaUrl = t => {
sessionStorage.setItem(storageKey, t);
redirectWithToken(t);
};
const triedHeaderJustNow = t => {
try {
const last = JSON.parse(sessionStorage.getItem(headerKey) || 'null');
return last?.t === t && Date.now() - last.at < 60000;
} catch (e) {
return false;
}
};
const continueWith = async t => {
if (typeof t !== 'string' || !t) throw new Error('missing_auth_token');
continuing = true;
loginBtn.disabled = true;
await keepLaunch(t);
if (launchUrlHasToken || triedHeaderJustNow(t)) return viaUrl(t);
sessionStorage.setItem(headerKey, JSON.stringify({ t, at: Date.now() }));
let res = null;
try {
res = await fetch(launchUrl, { headers: { 'X-Puter-Auth-Token': t }, credentials: 'same-origin', redirect: 'manual', cache: 'no-store' });
} catch (e) {
console.error(e);
}
if (res && res.type !== 'opaqueredirect') openLaunchUrl();
else viaUrl(t);
};
const tryStored = auto => {
if (continuing) return true;
const u = new URL(launchUrl);
if (u.searchParams.get('puter.auth.token')) return false;
const t = getStored();
if (!t) return false;
const last = sessionStorage.getItem(storageKey);
if (last === t) return false;
// Without a click, never fall back to putting the token in the URL.
if (auto && triedHeaderJustNow(t)) return false;
setStatus('Using saved Puter session...');
redirectWithToken(t);
continueWith(t).catch(e => console.error(e));
return true;
};
loginBtn.addEventListener('click', async () => {
if (continuing) return;
loginBtn.disabled = true;
setStatus('Authenticating with Puter...');
try {
if (tryStored()) return;
// The desktop's token, if it's on its way, rather than an older stored one.
await keepLaunch();
if (tryStored(false)) return;
const r = await globalThis.puter.auth.signIn();
redirectWithToken(r?.token || getStored());
await continueWith(r?.token || getStored());
} catch (e) {
console.error(e);
loginBtn.disabled = false;
setStatus('Sign in was not completed. Click to try again.');
}
});
retryBtn.addEventListener('click', () => location.reload());
if (tryStored()) return;
retryBtn.addEventListener('click', openLaunchUrl);
// A tab the desktop opened is handed a token a moment after load, newer than
// a stored one.
keepLaunch().then(() => tryStored(true));
})();
</script>
</body>
@@ -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<void>((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
+6
View File
@@ -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.
+229
View File
@@ -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', () => {
+80 -10
View File
@@ -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<void>}
*/
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(
+102 -7
View File
@@ -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<string, string>} 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<string, string> | 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
+124 -17
View File
@@ -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'));
});
});
+7 -5
View File
@@ -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;
}