mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6704fa64ed | ||
|
|
917daf12af | ||
|
|
f7c0fdda9f | ||
|
|
4efd966be9 | ||
|
|
11c519ed08 | ||
|
|
41f6edeab1 | ||
|
|
7ca1d97ef3 | ||
|
|
40eed41ce5 | ||
|
|
3ef18a2259 | ||
|
|
1621da6bf9 | ||
|
|
10e4606b9c | ||
|
|
6d06c23cc7 | ||
|
|
b30e1c9af5 | ||
|
|
6b06793750 | ||
|
|
e441880f13 | ||
|
|
9a86803418 | ||
|
|
09c6ce6f46 | ||
|
|
0fdf40b8da | ||
|
|
5b850113ff | ||
|
|
51bf8697a8 | ||
|
|
8c14e7de30 | ||
|
|
84faf5c40c | ||
|
|
aba2666f26 | ||
|
|
abe6882de9 | ||
|
|
770af49528 | ||
|
|
47b4cc1158 | ||
|
|
e253a7f862 | ||
|
|
af35783df4 |
No files matched your search
@@ -53,7 +53,7 @@ jobs:
|
||||
# step above fails; the tests skip themselves without the key.
|
||||
- name: Run live realtime conversation tests
|
||||
if: ${{ !cancelled() }}
|
||||
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/convoLive.test.ts
|
||||
run: npm run setupExtensions && (cd src/puter-js && npm run build) && npx vitest run --config src/puter-js/tests/api/vitest.config.ts src/puter-js/tests/api/realtime/realtimeLive.test.ts
|
||||
env:
|
||||
CI: 'true'
|
||||
PUTER_TEST_AI_OPENAI_API_KEY: ${{ secrets.PUTER_TEST_AI_OPENAI_API_KEY }}
|
||||
@@ -124,7 +124,7 @@ localization system.
|
||||
</script>
|
||||
```
|
||||
|
||||
## Implementation and checks
|
||||
## Implementation
|
||||
|
||||
`createAppBrowser` in `src/gui/src/UI/Dashboard/AppBrowser.js` owns the shared UI
|
||||
and data behavior; its `guestApps` option is the signed-out list. `TabApps.js`
|
||||
@@ -134,14 +134,172 @@ injects desktop actions. `appsEmbed.js` supplies new-tab launching through
|
||||
`launch_app`, and loads only the embed entry, its SDK, and shared styles. `embedHostUser` in
|
||||
`src/gui/src/helpers/embedHostUser.js` reads the host's user from the fragment, and
|
||||
`embedHostTheme.js` beside it applies the host's theme.
|
||||
The normal GUI webpack build emits `bundle.min.js` and `apps-embed.min.js`.
|
||||
The normal GUI webpack build emits `bundle.min.js`, `apps-embed.min.js`, and `feedback-embed.min.js`.
|
||||
The `/embed/apps` route puts the recommended list in the page's config as
|
||||
`guestApps`. No puter.js API or app-list endpoint changes are needed.
|
||||
|
||||
## Feedback dialog
|
||||
|
||||
`GET /embed/feedback` is the app feedback dialog (`puter.ui.showFeedbackDialog()`)
|
||||
for a first-party page, with the same framing rules, query redirect, and
|
||||
host-user binding as `/embed/apps`. It sends the feedback for the framing
|
||||
page's origin, which the server reads from the referrer and pins with
|
||||
`frame-ancestors`; opened top-level, it does nothing. Its page is transparent
|
||||
so the dialog's own scrim covers the host.
|
||||
|
||||
puter.js uses it on a page one label under the GUI origin, other than the
|
||||
subdomains the server refuses, when the page is signed in, framing it in a
|
||||
modal `<dialog>` that stays hidden until the embed is ready. A session check that takes longer than 200ms shows a loading scrim
|
||||
with a spinner in its place; Escape or a click on it cancels. The embed posts `{ msg: 'feedbackEmbed', state }` to its parent
|
||||
(`loading`, then `ready` or `unavailable`) and finally
|
||||
`{ msg: 'feedbackDialogClosed', sent }`. It reports `unavailable` without the
|
||||
named user's session, or while that user's email still needs confirming, and
|
||||
puter.js then uses the `/action/send-feedback` popup, which can sign in. So does
|
||||
a frame that never answers, such as one the host's CSP blocks. `feedbackEmbed.js`
|
||||
is the entry, sharing `embedSession` in `src/gui/src/helpers/embedSession.js`
|
||||
with the app browser; `showFeedbackEmbed` in `src/puter-js/src/lib/guiEmbed.js`
|
||||
is the host side.
|
||||
|
||||
## Sign-in and file pickers
|
||||
|
||||
`GET /embed/sign-in`, `/embed/show-open-file-picker`, `/embed/show-save-file-picker`
|
||||
and `/embed/show-directory-picker` serve the same GUI popups as `/action/<action>`
|
||||
for a first-party page, with the same framing rules, query redirect, and
|
||||
`no-store` as `/embed/apps`. Any other spelling of the path (another case, a
|
||||
trailing slash) redirects to it, since the shell boots the desktop for it. They render the normal GUI shell, which names the
|
||||
framing page (read from the referrer, pinned with `frame-ancestors`) as
|
||||
`gui_params.embed_host_origin`. The GUI then runs the popup boot unchanged, with
|
||||
the framing page as `window.opener`, and `window.close()` asks the page to
|
||||
remove the frame (`src/gui/src/helpers/popupFrame.js`). Without a framing page
|
||||
to answer (opened top-level, or framed by a refused page) it does nothing. The
|
||||
popup's parameters come from the fragment instead of the query: `msg_id`,
|
||||
`options` and `request_auth`, plus `user` for a picker.
|
||||
|
||||
The frame posts `{ msg: 'puterPopupFrame', state }` to its parent: `loading` as
|
||||
soon as the shell boots, `ready` once it shows a window or dialog, `unavailable`
|
||||
when the page has to use the popup, `provider` when the user picks a sign-in
|
||||
provider (below), and `closed` where a popup would close. Its
|
||||
answers (`puter.token`, `fileOpenPicked`, `directoryPicked`, `fileSaved`, the
|
||||
cancel messages, `sendMeFileData`) are the popup's.
|
||||
|
||||
puter.js uses them on a page one label under the GUI origin, other than the
|
||||
subdomains the server refuses, unless the page is cross-origin isolated or in a
|
||||
frame of another site (which `frame-ancestors` refuses too).
|
||||
`showPopupFrame` in `src/puter-js/src/lib/guiEmbed.js` shows the frame in a box
|
||||
the size of the popup window, over a scrim, hidden until `ready` and behind the
|
||||
loading spinner after 200ms. Escape closes it, on the page or in the frame. One shows per popup, as each
|
||||
popup has its own window name: a second picker request of the same kind
|
||||
replaces the one showing, and a `signIn()` call made while a framed sign-in is
|
||||
open settles with it. On
|
||||
screens up to 600px wide the box fills the screen. A frame that is refused,
|
||||
never answers, or reports `unavailable` falls back to the popup, opened through
|
||||
a consent dialog when the click that asked for it has expired. A reload or navigation the frame
|
||||
starts itself (logging out, a sign-out in another tab) names the frame as its
|
||||
referrer, so the server refuses it; the page then shows its spinner and opens
|
||||
the frame again, once per `ready`.
|
||||
|
||||
- **Sign-in** (`puter.auth.signIn()`) has no host-user binding: it is how the
|
||||
page gets a user. The box has a close button, which rejects with
|
||||
`auth_window_closed` as closing the popup does. Providers refuse to be
|
||||
framed, so choosing one posts `{ state: 'provider', url }` with the
|
||||
provider's start URL for this sign-in's `msg_id`, then `unavailable`. The
|
||||
page opens the popup straight at that URL, once it checks the URL is the
|
||||
GUI's `/auth/oidc/<provider>/start` for this `msg_id`, and the provider
|
||||
returns it as this sign-in's popup. `attempt_temp_user_creation` keeps the popup, since
|
||||
only the popup creates a temporary account.
|
||||
- **Pickers** frame only for a signed-in page. The GUI reports `unavailable`
|
||||
unless its session belongs to the user named in `user`, and the page then uses
|
||||
the popup, which can sign in and switch accounts. The token the GUI sends
|
||||
before a picker's answer isn't adopted, since it is for the page's own user.
|
||||
Dismissing the loading scrim settles the picker as cancelled.
|
||||
|
||||
## Upgrade
|
||||
|
||||
`GET /embed/upgrade` is the deployment's upgrade dialog for a first-party page,
|
||||
served like the popups above: the GUI shell with the same framing rules, query
|
||||
redirect, exact-path redirect and `no-store`, naming the framing page as
|
||||
`gui_params.embed_host_origin`. It runs only when framed by an allowed page.
|
||||
|
||||
puter.js frames it on a signed-in first-party page (the same pages as the
|
||||
pickers) for `puter.ui.requestUpgrade(details)`, and for the Upgrade button of
|
||||
the usage limit dialog a refused call shows there. Elsewhere both keep their
|
||||
behavior: inside an app `requestUpgrade()` asks the desktop, and on any other
|
||||
page the usage limit dialog opens the dashboard's upgrade page in a new tab.
|
||||
|
||||
The frame covers the page with no box or close button, and the GUI page is
|
||||
transparent (`html.popup-frame-transparent`) so the dialog's own scrim covers
|
||||
the host. The frame allows `payment` as well as `otp-credentials`. Escape on the
|
||||
page is left to the dialog, since one there shouldn't drop a payment in
|
||||
progress. Its fragment names `user` (the page's signed-in user) and, when the
|
||||
refusal gave them, `reason` (`funds`, `subscription` or `storage`) and `method`.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user`, the account
|
||||
has no verification or password change waiting (which the frame couldn't be
|
||||
closed from), and the deployment defines `window.UIUpgradeAccount` with
|
||||
`UIUpgradeAccount.embeddable === true`. Otherwise it runs:
|
||||
|
||||
```js
|
||||
new UIUpgradeAccount({ attribution: { appUid, reason, method }, onClose }).open_as_window();
|
||||
```
|
||||
|
||||
`appUid` is the app the framing page's origin resolves to, never one the
|
||||
fragment names. `open_as_window()` resolves once the dialog shows, and the GUI
|
||||
then posts `ready`. While the page still hides the frame, which Chromium and
|
||||
WebKit lay out at 0x0, the GUI posts `ready` first and opens the dialog once
|
||||
the frame has a viewport, so a window it opens doesn't center on 0x0.
|
||||
`onClose({ upgraded })` must run exactly once, when the
|
||||
dialog closes or when it declines to open for the account; the GUI then posts
|
||||
`{ msg: 'puterPopupFrame', state: 'closed', upgraded }` and the page removes
|
||||
the frame. If `open_as_window()` rejects, the GUI posts `unavailable` instead. `requestUpgrade()` resolves `{ upgraded }`. A call made while the
|
||||
frame shows settles with it rather than replacing it, and a call refused while
|
||||
it shows still rejects but opens no usage limit dialog over it.
|
||||
|
||||
When the frame can't show the upgrade (refused, never ready, `unavailable`, or
|
||||
no user to name), puter.js opens the dashboard's upgrade page in a new tab with
|
||||
what was refused, through a consent dialog when the click has expired or the
|
||||
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
|
||||
|
||||
## Email confirmation
|
||||
|
||||
`GET /embed/request-email-confirmation` walks a first-party page's user through
|
||||
confirming their email, served like the upgrade: the GUI shell with the same
|
||||
framing rules, redirects and `no-store`, run only when framed by an allowed
|
||||
page. puter.js frames it on a signed-in first-party page for
|
||||
`puter.ui.requestEmailConfirmation()`. Inside an app the desktop shows the same
|
||||
windows over the app instead.
|
||||
|
||||
Like the upgrade, the frame covers the page with no box or close button, over a
|
||||
transparent GUI page, and its fragment names `user`. Escape closes it, on the
|
||||
page or on the save-account or code window. On a window, Escape closes that
|
||||
window as its close button does, so a code already sent still answers. The GUI
|
||||
reports `unavailable` unless its session belongs to `user` and the account has
|
||||
no phone, card or password check waiting.
|
||||
An email check is fine: the boot skips its own email gate for this action, so
|
||||
the user gets one code window they can close.
|
||||
|
||||
The GUI then runs `ensureConfirmedEmail` (`src/gui/src/helpers/ensureConfirmedEmail.js`),
|
||||
which the desktop's handler uses too: a temporary account gets the save-account
|
||||
window first, then an unconfirmed email gets the code window, each at most
|
||||
once. When the page's whoami already reads the email as confirmed,
|
||||
`requestEmailConfirmation()` resolves `{ response: true }` without framing
|
||||
anything, and a confirmation in the frame marks that whoami confirmed for the
|
||||
calls after it. An email the GUI reads as confirmed shows nothing. Before
|
||||
opening a window the GUI waits for the frame to have a viewport, as the upgrade
|
||||
does. It then posts
|
||||
`{ msg: 'puterPopupFrame', state: 'closed', confirmed }`, and
|
||||
`requestEmailConfirmation()` resolves `{ response: confirmed }`, the field an
|
||||
app reads from the desktop's answer. A call made while the frame shows settles
|
||||
with it. A frame that is refused, never ready, or `unavailable` resolves
|
||||
`{ response: false }`, since there's no popup to fall back to.
|
||||
|
||||
## Checks
|
||||
|
||||
Run the GUI component/browser tests (with the SDK bundle built and Playwright
|
||||
Chromium installed), and the backend route tests:
|
||||
|
||||
```sh
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
|
||||
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
|
||||
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
|
||||
```
|
||||
@@ -420,7 +420,11 @@ export type EventMap = {
|
||||
old_username: string;
|
||||
new_username: string;
|
||||
};
|
||||
'user.email-changed': { user_id: number; new_email: string };
|
||||
'user.email-changed': {
|
||||
user_id: number;
|
||||
old_email: string | null;
|
||||
new_email: string;
|
||||
};
|
||||
/** An account was suspended, or its suspension lifted. Local events. */
|
||||
'user.suspended': { userId: number };
|
||||
'user.unsuspended': { userId: number };
|
||||
|
||||
@@ -7468,6 +7468,11 @@ describe('AuthController user-protected mutations (validation paths)', () => {
|
||||
{ expiresIn: '1h' },
|
||||
);
|
||||
|
||||
const heard: Array<Record<string, unknown>> = [];
|
||||
eventClient.on('user.email-changed', (_k, data) => {
|
||||
heard.push(data as Record<string, unknown>);
|
||||
});
|
||||
|
||||
const req = makeReq({});
|
||||
(req as unknown as { query: Record<string, string> }).query = {
|
||||
token: linkJwt,
|
||||
@@ -7475,6 +7480,11 @@ describe('AuthController user-protected mutations (validation paths)', () => {
|
||||
const res = makeRes();
|
||||
await controller.handleChangeEmailConfirm(req, res);
|
||||
expect(res.sent).toMatch(/Email changed successfully/);
|
||||
expect(heard).toContainEqual({
|
||||
user_id: user.id,
|
||||
old_email: user.email ?? null,
|
||||
new_email: newEmail,
|
||||
});
|
||||
|
||||
const after = await server.stores.user.getById(user.id, {
|
||||
force: true,
|
||||
|
||||
@@ -2647,6 +2647,7 @@ export class AuthController extends PuterController {
|
||||
'user.email-changed' as never,
|
||||
{
|
||||
user_id: user.id,
|
||||
old_email: user.email ?? null,
|
||||
new_email: newEmail,
|
||||
} as never,
|
||||
{},
|
||||
|
||||
@@ -15,7 +15,6 @@ export interface OidcLoginContinuation {
|
||||
embeddedInPopup: boolean;
|
||||
openerOrigin: string | null;
|
||||
messageId: string | null;
|
||||
switchedToLogin: boolean;
|
||||
}
|
||||
|
||||
interface OidcReturnDeps {
|
||||
@@ -56,7 +55,6 @@ export function completeOidcLoginReturn(
|
||||
data.userUuid !== user.uuid ||
|
||||
typeof data.redirectUri !== 'string' ||
|
||||
typeof data.embeddedInPopup !== 'boolean' ||
|
||||
typeof data.switchedToLogin !== 'boolean' ||
|
||||
(data.openerOrigin !== null && typeof data.openerOrigin !== 'string') ||
|
||||
(data.messageId !== null && typeof data.messageId !== 'string')
|
||||
) {
|
||||
@@ -91,6 +89,5 @@ export function completeOidcLoginReturn(
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.switchedToLogin) append('oidc_switched', 'login');
|
||||
return target;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ import type { Actor } from '../../core/actor.js';
|
||||
import { PuterRouter } from '../../core/http/PuterRouter.js';
|
||||
import { PuterServer } from '../../server.js';
|
||||
import { setupTestServer } from '../../testUtil.js';
|
||||
import { embedFrameAncestors } from './HomepageController.js';
|
||||
import { embedFrameAncestors, embedHostOrigin } from './HomepageController.js';
|
||||
|
||||
// ── Test harness ────────────────────────────────────────────────────
|
||||
//
|
||||
@@ -550,3 +550,26 @@ describe('embedFrameAncestors', () => {
|
||||
).toBe("'self'");
|
||||
});
|
||||
});
|
||||
|
||||
describe('embedHostOrigin', () => {
|
||||
const config = {
|
||||
origin: 'https://example.test',
|
||||
domain: 'example.test',
|
||||
api_base_url: 'https://backend.example.test',
|
||||
static_hosting_domain: 'site.example.test',
|
||||
};
|
||||
|
||||
it.each([
|
||||
['https://sheets.example.test/doc/1', 'https://sheets.example.test'],
|
||||
['https://backend.example.test/x', null],
|
||||
['https://api.example.test/', null],
|
||||
['https://someone.site.example.test/', null],
|
||||
['https://a.sheets.example.test/', null],
|
||||
['http://sheets.example.test/', null],
|
||||
['https://example.test/', null],
|
||||
['not a url', null],
|
||||
[undefined, null],
|
||||
])('%s frames as %s', (referer, expected) => {
|
||||
expect(embedHostOrigin(config, referer)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -31,8 +31,24 @@ import type {
|
||||
PuterHomepageService,
|
||||
PageMeta,
|
||||
LaunchOptions,
|
||||
PopupFrame,
|
||||
} from '../../services/homepage/PuterHomepageService';
|
||||
|
||||
/**
|
||||
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade dialog,
|
||||
* which it would otherwise open in a dashboard tab, and the email confirmation,
|
||||
* which it otherwise can't show.
|
||||
*/
|
||||
export const FRAMED_POPUP_ACTIONS = [
|
||||
'sign-in',
|
||||
'show-open-file-picker',
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'request-email-confirmation',
|
||||
] as const;
|
||||
|
||||
/** Longest description/og:description/twitter:description on `/app/<name>`. */
|
||||
export const APP_META_DESCRIPTION_MAX = 150;
|
||||
|
||||
@@ -61,32 +77,34 @@ export function appMetaDescription(text: string): string {
|
||||
return `${cut.replace(/[\s,;:.!?…—-]+$/, '')}…`;
|
||||
}
|
||||
|
||||
type EmbedFramingConfig = Pick<
|
||||
IConfig,
|
||||
| 'origin'
|
||||
| 'domain'
|
||||
| 'api_base_url'
|
||||
| 'static_hosting_domain'
|
||||
| 'static_hosting_domain_alt'
|
||||
| 'private_app_hosting_domain'
|
||||
| 'private_app_hosting_domain_alt'
|
||||
>;
|
||||
|
||||
/**
|
||||
* `frame-ancestors` for the app browser embed. A wildcard over `*.<domain>`
|
||||
* The origin of a first-party page that may frame an `/embed/*` page, named
|
||||
* exactly from the request's referrer, or null. A wildcard over `*.<domain>`
|
||||
* would also admit user-hosted sites whenever the hosting domains sit under it,
|
||||
* so the embedding page is named exactly, from the request's referrer. Only a
|
||||
* single label under `<domain>` qualifies, and not one this server answers
|
||||
* itself (the API, WebDAV, SDK and native-app hosts).
|
||||
* so only a single label under `<domain>` qualifies, and not one this server
|
||||
* answers itself (the API, WebDAV, SDK and native-app hosts).
|
||||
*/
|
||||
export function embedFrameAncestors(
|
||||
config: Pick<
|
||||
IConfig,
|
||||
| 'origin'
|
||||
| 'domain'
|
||||
| 'api_base_url'
|
||||
| 'static_hosting_domain'
|
||||
| 'static_hosting_domain_alt'
|
||||
| 'private_app_hosting_domain'
|
||||
| 'private_app_hosting_domain_alt'
|
||||
>,
|
||||
export function embedHostOrigin(
|
||||
config: EmbedFramingConfig,
|
||||
referer: string | undefined,
|
||||
): string {
|
||||
): string | null {
|
||||
const gui = new URL(config.origin ?? `https://${config.domain}`);
|
||||
let parent: URL;
|
||||
try {
|
||||
parent = new URL(referer ?? '');
|
||||
} catch {
|
||||
return "'self'";
|
||||
return null;
|
||||
}
|
||||
const host = parent.hostname.toLowerCase();
|
||||
const label = subdomainLabelOf(host, config.domain);
|
||||
@@ -105,7 +123,16 @@ export function embedFrameAncestors(
|
||||
!isReservedSubdomain(label) &&
|
||||
host !== new URL(config.api_base_url).hostname &&
|
||||
!hostingDomains.some((d) => host === d || host.endsWith(`.${d}`));
|
||||
return allowed ? `'self' ${parent.origin}` : "'self'";
|
||||
return allowed ? parent.origin : null;
|
||||
}
|
||||
|
||||
/** `frame-ancestors` for an `/embed/*` page: the GUI and {@link embedHostOrigin}. */
|
||||
export function embedFrameAncestors(
|
||||
config: EmbedFramingConfig,
|
||||
referer: string | undefined,
|
||||
): string {
|
||||
const host = embedHostOrigin(config, referer);
|
||||
return host ? `'self' ${host}` : "'self'";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -142,6 +169,7 @@ export class HomepageController extends PuterController {
|
||||
res: express.Response,
|
||||
metaOverrides: Partial<PageMeta> = {},
|
||||
launch: LaunchOptions = {},
|
||||
popupFrame?: PopupFrame,
|
||||
) => {
|
||||
const meta = { ...defaultMeta(req), ...metaOverrides };
|
||||
const actor =
|
||||
@@ -150,19 +178,27 @@ export class HomepageController extends PuterController {
|
||||
actor?: Parameters<typeof homepage.send>[0]['actor'];
|
||||
}
|
||||
).actor ?? null;
|
||||
await homepage.send({ req, res, actor }, meta, launch);
|
||||
await homepage.send({ req, res, actor }, meta, launch, popupFrame);
|
||||
};
|
||||
|
||||
// -- Root + path-aliased shell routes ------------------------
|
||||
|
||||
router.get('/', {}, (req, res) => sendShell(req, res));
|
||||
|
||||
router.get('/embed/apps', {}, async (req, res) => {
|
||||
// SDK bootstrap parameters must not change this page's account or API origin.
|
||||
// Checked on the raw URL; `req.query` drops pairs past the parser's limit.
|
||||
/**
|
||||
* Headers shared by the `/embed/*` pages; false when the request was
|
||||
* redirected instead. SDK bootstrap parameters must not change an
|
||||
* embed's account or API origin, so a query string is dropped. Checked
|
||||
* on the raw URL; `req.query` drops pairs past the parser's limit.
|
||||
*/
|
||||
const prepareEmbed = (
|
||||
req: express.Request,
|
||||
res: express.Response,
|
||||
path: string,
|
||||
): boolean => {
|
||||
if (req.originalUrl.includes('?')) {
|
||||
res.redirect('/embed/apps');
|
||||
return;
|
||||
res.redirect(path);
|
||||
return false;
|
||||
}
|
||||
res.removeHeader('X-Frame-Options');
|
||||
res.setHeader(
|
||||
@@ -170,6 +206,11 @@ export class HomepageController extends PuterController {
|
||||
`frame-ancestors ${embedFrameAncestors(this.config, req.get('referer'))}`,
|
||||
);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
return true;
|
||||
};
|
||||
|
||||
router.get('/embed/apps', {}, async (req, res) => {
|
||||
if (!prepareEmbed(req, res, '/embed/apps')) return;
|
||||
// Shown to visitors without a session; a signed-in embed fetches
|
||||
// its own list, so a failure here only costs signed-out visitors.
|
||||
const guestApps = await this.services.recommendedApps
|
||||
@@ -178,6 +219,48 @@ export class HomepageController extends PuterController {
|
||||
res.send(homepage.renderAppBrowserEmbed({ guestApps }));
|
||||
});
|
||||
|
||||
router.get('/embed/feedback', {}, (req, res) => {
|
||||
if (!prepareEmbed(req, res, '/embed/feedback')) return;
|
||||
// The feedback is recorded against this origin, which
|
||||
// frame-ancestors has just pinned to the actual framing page.
|
||||
res.send(
|
||||
homepage.renderFeedbackEmbed({
|
||||
hostOrigin: embedHostOrigin(
|
||||
this.config,
|
||||
req.get('referer'),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// The GUI runs the popup's own boot, answering the framing page
|
||||
// instead of an opener.
|
||||
for (const action of FRAMED_POPUP_ACTIONS) {
|
||||
const embedPath = `/embed/${action}`;
|
||||
router.get(embedPath, {}, async (req, res) => {
|
||||
// Routes match case-insensitively and with a trailing slash,
|
||||
// and the shell boots the desktop for any other spelling, so
|
||||
// only the exact one may be framed.
|
||||
if (req.originalUrl !== embedPath) {
|
||||
res.redirect(embedPath);
|
||||
return;
|
||||
}
|
||||
if (!prepareEmbed(req, res, embedPath)) return;
|
||||
await sendShell(
|
||||
req,
|
||||
res,
|
||||
{},
|
||||
{},
|
||||
{
|
||||
hostOrigin: embedHostOrigin(
|
||||
this.config,
|
||||
req.get('referer'),
|
||||
),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
router.get('/settings', {}, (req, res) => sendShell(req, res));
|
||||
router.get('/settings/*splat', {}, (req, res) => sendShell(req, res));
|
||||
|
||||
|
||||
@@ -1620,7 +1620,7 @@ describe('OIDCController signup callback', () => {
|
||||
expect(captured.redirectUrl).toContain('action=signup');
|
||||
});
|
||||
|
||||
it('creates a fresh user without oidc_switched on first signup', async () => {
|
||||
it('creates a fresh user on first signup', async () => {
|
||||
const state = oidc().signState({
|
||||
provider: 'custom',
|
||||
redirect_uri: TEST_ORIGIN + '/',
|
||||
@@ -1646,11 +1646,9 @@ describe('OIDCController signup callback', () => {
|
||||
);
|
||||
expect(captured.cookies).toHaveLength(1);
|
||||
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
|
||||
// Fresh creation — must NOT advertise "you've actually been signed in".
|
||||
expect(captured.redirectUrl).not.toContain('oidc_switched=login');
|
||||
});
|
||||
|
||||
it('adds oidc_switched=login when signup hits an already-linked account', async () => {
|
||||
it('signs in to an already-linked account on signup, returning as a login would', async () => {
|
||||
// Seed an account linked on (provider, sub) so the signup callback
|
||||
// resolves to `linked-sub` rather than creating a new user.
|
||||
const sub = `sub-${Math.random().toString(36).slice(2, 8)}`;
|
||||
@@ -1686,7 +1684,7 @@ describe('OIDCController signup callback', () => {
|
||||
res,
|
||||
);
|
||||
expect(captured.cookies).toHaveLength(1);
|
||||
expect(captured.redirectUrl).toContain('oidc_switched=login');
|
||||
expect(captured.redirectUrl).toBe(TEST_ORIGIN + '/');
|
||||
});
|
||||
|
||||
it('redirects to action=signup with auth_error when user resolution fails (unconfirmed email)', async () => {
|
||||
|
||||
@@ -688,14 +688,7 @@ export class OIDCController extends PuterController {
|
||||
);
|
||||
}
|
||||
|
||||
// If we landed on an existing account (either via the
|
||||
// provider_sub or via email match), signal the GUI so it can
|
||||
// render a "signed in" flow rather than "account created".
|
||||
const extra =
|
||||
resolved.origin === 'created'
|
||||
? undefined
|
||||
: { oidc_switched: 'login' };
|
||||
await this.#finishLogin(req, res, user, stateDecoded, extra);
|
||||
await this.#finishLogin(req, res, user, stateDecoded);
|
||||
};
|
||||
router.get('/auth/oidc/callback/signup', cbOpts, signupCb);
|
||||
router.post('/auth/oidc/callback/signup', cbOpts, signupCb);
|
||||
@@ -834,17 +827,14 @@ if (window.opener) {
|
||||
attempt = 0,
|
||||
): Promise<
|
||||
| { error: string; code?: string; requestCode?: string }
|
||||
| {
|
||||
user: import('../../stores/user/UserStore.js').UserRow;
|
||||
origin: 'linked-sub' | 'linked-email' | 'created';
|
||||
}
|
||||
| { user: import('../../stores/user/UserStore.js').UserRow }
|
||||
> {
|
||||
// 1. Existing provider/sub link.
|
||||
const linked = await this.services.oidc.findUserByProviderSub(
|
||||
provider,
|
||||
userinfo.sub,
|
||||
);
|
||||
if (linked) return { user: linked, origin: 'linked-sub' };
|
||||
if (linked) return { user: linked };
|
||||
|
||||
// 2/3. Email match branch.
|
||||
const claimedEmail =
|
||||
@@ -881,7 +871,7 @@ if (window.opener) {
|
||||
error: outcome.error ?? 'Failed to link provider.',
|
||||
};
|
||||
}
|
||||
return { user: byEmail, origin: 'linked-email' };
|
||||
return { user: byEmail };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -911,7 +901,7 @@ if (window.opener) {
|
||||
requestCode: outcome.requestCode,
|
||||
};
|
||||
}
|
||||
return { user: outcome.user, origin: 'created' };
|
||||
return { user: outcome.user };
|
||||
}
|
||||
|
||||
async #processCallback(
|
||||
@@ -1000,7 +990,6 @@ if (window.opener) {
|
||||
res: Response,
|
||||
user: UserRow,
|
||||
stateDecoded: Record<string, unknown>,
|
||||
extraQueryParams?: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const origin = (this.config.origin ?? '').replace(/\/$/, '');
|
||||
const continuation: OidcLoginContinuation = {
|
||||
@@ -1018,7 +1007,6 @@ if (window.opener) {
|
||||
stateDecoded.msg_id == null
|
||||
? null
|
||||
: String(stateDecoded.msg_id),
|
||||
switchedToLogin: extraQueryParams?.oidc_switched === 'login',
|
||||
};
|
||||
if (user.otp_enabled) {
|
||||
const challenge = this.services.token.sign(
|
||||
|
||||
@@ -139,7 +139,7 @@ describe('OIDC account second-factor login', () => {
|
||||
expect(await response.json()).toMatchObject({
|
||||
proceed: true,
|
||||
next_step: 'complete',
|
||||
redirectUrl: `${env.origin}/dashboard${flow === 'signup' ? '?oidc_switched=login' : ''}`,
|
||||
redirectUrl: `${env.origin}/dashboard`,
|
||||
});
|
||||
expect(
|
||||
response.headers
|
||||
|
||||
@@ -187,9 +187,9 @@ describe('createUserSubdomainNotFound', () => {
|
||||
});
|
||||
|
||||
it('passes through reserved subdomains (api, js, native apps, etc.)', () => {
|
||||
// `api`, `js`, `dav`, `docs`, `developer`, `editor`, `pdf`,
|
||||
// `api`, `js`, `dav`, `docs`, `developer`, `about`, `apps`,
|
||||
// `puter-app-icons`, etc. all pass through.
|
||||
for (const sub of ['api', 'js', 'docs', 'editor', 'puter-app-icons']) {
|
||||
for (const sub of ['api', 'js', 'docs', 'about', 'puter-app-icons']) {
|
||||
const { out, next } = run(
|
||||
createUserSubdomainNotFound(config),
|
||||
makeReq({
|
||||
@@ -865,13 +865,13 @@ describe('createNativeAppStatic', () => {
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(nodePath.join(tmpdir(), 'native-apps-'));
|
||||
mkdirSync(nodePath.join(root, 'editor', 'assets'), { recursive: true });
|
||||
mkdirSync(nodePath.join(root, 'about', 'assets'), { recursive: true });
|
||||
writeFileSync(
|
||||
nodePath.join(root, 'editor', 'index.html'),
|
||||
'<h1>editor</h1>',
|
||||
nodePath.join(root, 'about', 'index.html'),
|
||||
'<h1>about</h1>',
|
||||
);
|
||||
writeFileSync(
|
||||
nodePath.join(root, 'editor', 'assets', 'app.js'),
|
||||
nodePath.join(root, 'about', 'assets', 'app.js'),
|
||||
'console.log(1);',
|
||||
);
|
||||
mkdirSync(nodePath.join(root, 'docs', 'dist'), { recursive: true });
|
||||
@@ -893,7 +893,7 @@ describe('createNativeAppStatic', () => {
|
||||
|
||||
it('leaves a native app name alone on a host outside our domains', async () => {
|
||||
const req = staticReq({
|
||||
subdomains: ['com', 'example', 'editor'],
|
||||
subdomains: ['com', 'example', 'about'],
|
||||
path: '/index.html',
|
||||
});
|
||||
(req as Request & { is_custom_domain?: boolean }).is_custom_domain =
|
||||
@@ -907,7 +907,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
createNativeAppStatic(config),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
@@ -915,17 +915,24 @@ describe('createNativeAppStatic', () => {
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('passes through subdomains that are not native apps', async () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'api'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent).toBeUndefined();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
// `editor`, `markus` and `pdf` are web apps on standard host routing,
|
||||
// even with a folder of their own under the native apps root.
|
||||
it.each(['api', 'editor', 'markus', 'pdf'])(
|
||||
'passes %s through, as it is not a native app',
|
||||
async (sub) => {
|
||||
mkdirSync(nodePath.join(root, sub), { recursive: true });
|
||||
writeFileSync(nodePath.join(root, sub, 'index.html'), sub);
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', sub],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent).toBeUndefined();
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
it('passes through when there is no subdomain at all', async () => {
|
||||
const { next } = await runStatic(
|
||||
@@ -939,13 +946,13 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent).toEqual({
|
||||
path: '/index.html',
|
||||
root: nodePath.join(root, 'editor'),
|
||||
root: nodePath.join(root, 'about'),
|
||||
});
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -954,11 +961,11 @@ describe('createNativeAppStatic', () => {
|
||||
const { out } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'EDITOR'],
|
||||
subdomains: ['localhost', 'puter', 'ABOUT'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
);
|
||||
expect(out.sent?.root).toBe(nodePath.join(root, 'editor'));
|
||||
expect(out.sent?.root).toBe(nodePath.join(root, 'about'));
|
||||
});
|
||||
|
||||
it('serves docs out of its dist/ subdirectory, not the app root', async () => {
|
||||
@@ -979,7 +986,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/assets',
|
||||
originalUrl: '/assets?v=2',
|
||||
}),
|
||||
@@ -995,7 +1002,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/assets/',
|
||||
}),
|
||||
);
|
||||
@@ -1007,7 +1014,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { out, next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/nope.html',
|
||||
}),
|
||||
);
|
||||
@@ -1019,7 +1026,7 @@ describe('createNativeAppStatic', () => {
|
||||
const { next } = await runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/index.html',
|
||||
}),
|
||||
new Error('send failed'),
|
||||
@@ -1032,7 +1039,7 @@ describe('createNativeAppStatic', () => {
|
||||
runStatic(
|
||||
withRoot(),
|
||||
staticReq({
|
||||
subdomains: ['localhost', 'puter', 'editor'],
|
||||
subdomains: ['localhost', 'puter', 'about'],
|
||||
path: '/../../etc/passwd',
|
||||
}),
|
||||
),
|
||||
|
||||
+104
-1
@@ -368,12 +368,115 @@ describe('PuterServer host header validation', () => {
|
||||
expect(api.status).toBe(404);
|
||||
});
|
||||
|
||||
it('lets a deployment subdomain frame the feedback embed and names it', async () => {
|
||||
const parent = `http://spreadsheet.puter.localhost:${port}`;
|
||||
const res = await request('/embed/feedback', {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `${parent}/sheet/1`,
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['x-frame-options']).toBeUndefined();
|
||||
expect(res.headers['content-security-policy']).toBe(
|
||||
`frame-ancestors 'self' ${parent}`,
|
||||
);
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
expect(res.body).toContain('/dist/feedback-embed.min.js');
|
||||
expect(res.body).not.toContain('/dist/bundle.min.js');
|
||||
const config = JSON.parse(
|
||||
res.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
|
||||
);
|
||||
expect(config).toEqual({
|
||||
apiOrigin: `http://api.puter.localhost:${port}`,
|
||||
hostOrigin: parent,
|
||||
});
|
||||
|
||||
const hosted = await request('/embed/feedback', {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://someone.site.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
|
||||
expect(
|
||||
JSON.parse(
|
||||
hosted.body.match(/id="feedback-embed-config">(.*?)<\/script>/)[1],
|
||||
).hostOrigin,
|
||||
).toBeNull();
|
||||
|
||||
const redirected = await request('/embed/feedback?puter.api_origin=https://other.test', {
|
||||
host: `puter.localhost:${port}`,
|
||||
});
|
||||
expect(redirected.status).toBe(302);
|
||||
expect(redirected.headers.location).toBe('/embed/feedback');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'sign-in',
|
||||
'show-open-file-picker',
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'request-email-confirmation',
|
||||
])('lets a deployment subdomain frame the %s popup and names it to the GUI', async (action) => {
|
||||
const parent = `http://spreadsheet.puter.localhost:${port}`;
|
||||
const guiParams = (body: string) =>
|
||||
JSON.parse(body.match(/gui\((\{.*\})\);/)[1]);
|
||||
const res = await request(`/embed/${action}`, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `${parent}/sheet/1`,
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['x-frame-options']).toBeUndefined();
|
||||
expect(res.headers['content-security-policy']).toBe(
|
||||
`frame-ancestors 'self' ${parent}`,
|
||||
);
|
||||
expect(res.headers['cache-control']).toBe('no-store');
|
||||
expect(guiParams(res.body).embed_host_origin).toBe(parent);
|
||||
|
||||
const hosted = await request(`/embed/${action}`, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://someone.site.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(hosted.headers['content-security-policy']).toBe("frame-ancestors 'self'");
|
||||
expect(guiParams(hosted.body).embed_host_origin).toBeNull();
|
||||
|
||||
const redirected = await request(`/embed/${action}?auth_token=x&embedded_in_popup=true`, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `${parent}/sheet/1`,
|
||||
});
|
||||
expect(redirected.status).toBe(302);
|
||||
expect(redirected.headers.location).toBe(`/embed/${action}`);
|
||||
expect(redirected.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
});
|
||||
|
||||
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Request-Email-Confirmation'])(
|
||||
'lets a first-party page frame only the exact spelling of %s',
|
||||
async (spelling) => {
|
||||
const res = await request(spelling, {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://spreadsheet.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.location).toBe(spelling.toLowerCase().replace(/\/$/, ''));
|
||||
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
expect(res.headers['content-security-policy']).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it('names no framing page to the popups it serves in a window', async () => {
|
||||
const res = await request('/action/sign-in?embedded_in_popup=true', {
|
||||
host: `puter.localhost:${port}`,
|
||||
referer: `http://spreadsheet.puter.localhost:${port}/`,
|
||||
});
|
||||
expect(res.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
expect(res.headers['content-security-policy']).toBeUndefined();
|
||||
expect(res.body).not.toContain('embed_host_origin');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a user-hosted site', 'http://someone.site.puter.localhost:PORT/'],
|
||||
['a private app host', 'http://someone.app.puter.localhost:PORT/'],
|
||||
['the API host', 'http://api.puter.localhost:PORT/'],
|
||||
['the WebDAV host', 'http://dav.puter.localhost:PORT/'],
|
||||
['a native app host', 'http://editor.puter.localhost:PORT/'],
|
||||
['a native app host', 'http://about.puter.localhost:PORT/'],
|
||||
['a nested subdomain', 'http://a.spreadsheet.puter.localhost:PORT/'],
|
||||
['another site', 'http://evil.test:PORT/'],
|
||||
['another port', 'http://spreadsheet.puter.localhost:1/'],
|
||||
|
||||
@@ -107,6 +107,31 @@ describe('app browser embed shell', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('feedback embed shell', () => {
|
||||
it('carries the framing page and API origin, and loads only its own script', () => {
|
||||
const html = makeService({
|
||||
api_base_url: 'https://api.deployment.test',
|
||||
gui_bundle: '/static/bundle.min.js?v=42',
|
||||
}).renderFeedbackEmbed({ hostOrigin: 'https://notes.deployment.test' });
|
||||
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
|
||||
expect(JSON.parse(configJson)).toEqual({
|
||||
apiOrigin: 'https://api.deployment.test',
|
||||
hostOrigin: 'https://notes.deployment.test',
|
||||
});
|
||||
expect(html).toContain('<script defer src="/static/feedback-embed.min.js?v=42"></script>');
|
||||
expect(html).toContain('<link rel="stylesheet" href="/css/feedback-embed.css">');
|
||||
expect(html).toContain('<main id="feedback-embed"></main>');
|
||||
expect(html).not.toContain('bundle.min.js');
|
||||
expect(html).not.toContain('apps-embed');
|
||||
});
|
||||
|
||||
it('carries no framing page when none is allowed', () => {
|
||||
const html = makeService({}).renderFeedbackEmbed({ hostOrigin: null });
|
||||
const configJson = html.match(/id="feedback-embed-config">(.*?)<\/script>/)![1];
|
||||
expect(JSON.parse(configJson).hostOrigin).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/** Capture what the service sends, and return the rendered HTML. */
|
||||
const render = async (
|
||||
service: PuterHomepageService,
|
||||
|
||||
@@ -48,6 +48,15 @@ export interface LaunchOptions {
|
||||
on_initialized?: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A GUI popup a first-party page frames at `/embed/<action>`. `hostOrigin` is
|
||||
* that page, read from the referrer and pinned with frame-ancestors; null when
|
||||
* no allowed page frames it.
|
||||
*/
|
||||
export interface PopupFrame {
|
||||
hostOrigin: string | null;
|
||||
}
|
||||
|
||||
interface PuterGuiAddonsEvent {
|
||||
req: Request;
|
||||
path: string;
|
||||
@@ -171,15 +180,50 @@ export class PuterHomepageService extends PuterService {
|
||||
renderAppBrowserEmbed({
|
||||
guestApps = [],
|
||||
}: { guestApps?: Array<Record<string, unknown>> } = {}): string {
|
||||
const configJson = JSON.stringify({
|
||||
apiOrigin: this.config.api_base_url,
|
||||
sdkUrl:
|
||||
this.config.env === 'dev'
|
||||
? '/sdk/puter.dev.js'
|
||||
: (this.config.gui_puterjs_bundle ??
|
||||
'https://js.puter.com/v2/'),
|
||||
guestApps,
|
||||
}).replace(/</g, '\\u003c');
|
||||
return this.#renderEmbed({
|
||||
rootId: 'app-browser',
|
||||
rootClass: 'dashboard',
|
||||
stylesheet: 'apps-embed.css',
|
||||
script: 'apps-embed.min.js',
|
||||
config: {
|
||||
apiOrigin: this.config.api_base_url,
|
||||
sdkUrl:
|
||||
this.config.env === 'dev'
|
||||
? '/sdk/puter.dev.js'
|
||||
: (this.config.gui_puterjs_bundle ??
|
||||
'https://js.puter.com/v2/'),
|
||||
guestApps,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `hostOrigin` is the first-party page framing the dialog, which the
|
||||
* feedback is sent for; null when no allowed page frames it.
|
||||
*/
|
||||
renderFeedbackEmbed({ hostOrigin }: { hostOrigin: string | null }): string {
|
||||
return this.#renderEmbed({
|
||||
rootId: 'feedback-embed',
|
||||
stylesheet: 'feedback-embed.css',
|
||||
script: 'feedback-embed.min.js',
|
||||
config: { apiOrigin: this.config.api_base_url, hostOrigin },
|
||||
});
|
||||
}
|
||||
|
||||
#renderEmbed({
|
||||
rootId,
|
||||
rootClass,
|
||||
stylesheet,
|
||||
script,
|
||||
config,
|
||||
}: {
|
||||
rootId: string;
|
||||
rootClass?: string;
|
||||
stylesheet: string;
|
||||
script: string;
|
||||
config: Record<string, unknown>;
|
||||
}): string {
|
||||
const configJson = JSON.stringify(config).replace(/</g, '\\u003c');
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
@@ -190,27 +234,27 @@ export class PuterHomepageService extends PuterService {
|
||||
<title>${encode(String(this.config.gui_params?.title ?? 'Puter'))}</title>
|
||||
<link rel="stylesheet" href="/css/normalize.css">
|
||||
<link rel="stylesheet" href="/css/dashboard.css">
|
||||
<link rel="stylesheet" href="/css/apps-embed.css">
|
||||
<link rel="stylesheet" href="/css/${stylesheet}">
|
||||
</head>
|
||||
<body>
|
||||
<main id="app-browser" class="dashboard"></main>
|
||||
<script type="application/json" id="app-browser-config">${configJson}</script>
|
||||
<script defer src="${encode(this.#appBrowserEmbedScript())}"></script>
|
||||
<main id="${rootId}"${rootClass ? ` class="${rootClass}"` : ''}></main>
|
||||
<script type="application/json" id="${rootId}-config">${configJson}</script>
|
||||
<script defer src="${encode(this.#embedScript(script))}"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The embed's script is built beside the GUI bundle, so it is served from
|
||||
* Embed scripts are built beside the GUI bundle, so they are served from
|
||||
* wherever `gui_bundle` is (a CDN in production), with the same query.
|
||||
*/
|
||||
#appBrowserEmbedScript(): string {
|
||||
#embedScript(name: string): string {
|
||||
const base = 'http://relative.invalid';
|
||||
const bundle = new URL(
|
||||
this.config.gui_bundle ?? '/dist/bundle.min.js',
|
||||
base,
|
||||
);
|
||||
const script = new URL('apps-embed.min.js', bundle);
|
||||
const script = new URL(name, bundle);
|
||||
script.search = bundle.search;
|
||||
return script.origin === base
|
||||
? `${script.pathname}${script.search}`
|
||||
@@ -268,6 +312,7 @@ export class PuterHomepageService extends PuterService {
|
||||
ctx: { req: Request; res: Response; actor?: Actor | null },
|
||||
meta: PageMeta,
|
||||
launchOptions: LaunchOptions = {},
|
||||
popupFrame?: PopupFrame,
|
||||
): Promise<void> {
|
||||
const { req, res, actor } = ctx;
|
||||
|
||||
@@ -292,6 +337,7 @@ export class PuterHomepageService extends PuterService {
|
||||
{ req, actor: actor ?? null },
|
||||
meta,
|
||||
launchOptions,
|
||||
popupFrame,
|
||||
);
|
||||
res.send(html);
|
||||
}
|
||||
@@ -302,6 +348,7 @@ export class PuterHomepageService extends PuterService {
|
||||
ctx: { req: Request; actor: Actor | null },
|
||||
meta: PageMeta,
|
||||
launchOptions: LaunchOptions,
|
||||
popupFrame?: PopupFrame,
|
||||
): Promise<string> {
|
||||
const { req, actor } = ctx;
|
||||
const env = this.config.env ?? 'prod';
|
||||
@@ -347,6 +394,8 @@ export class PuterHomepageService extends PuterService {
|
||||
eventsNotifications: notificationsFoldInEnabled(this.config),
|
||||
...meta,
|
||||
launch_options: launchOptions,
|
||||
// After `meta`, so nothing page-specific can name the opener.
|
||||
...(popupFrame ? { embed_host_origin: popupFrame.hostOrigin } : {}),
|
||||
};
|
||||
|
||||
const event: PuterGuiAddonsEvent = {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# OpenAI Realtime relay
|
||||
|
||||
The relay serves `/puterai/openai/v1/realtime` on the API host. The SDK exposes
|
||||
it through [`puter.ai.convo()`](../../../docs/src/AI/convo.md).
|
||||
it through [`puter.ai.realtime()`](../../../docs/src/AI/realtime.md).
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime.md).
|
||||
Direct clients are documented in the [Realtime WebSocket API reference](../../../docs/src/AI/realtime-websocket.md).
|
||||
|
||||
## Transport
|
||||
|
||||
@@ -27,7 +27,7 @@ The socket opens before authentication completes. Authentication and model
|
||||
failures arrive as OpenAI-shaped error events followed by a close frame.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo({ output: ['text'] });
|
||||
const conversation = await puter.ai.realtime({ output: ['text'] });
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
conversation.on('text', ({ delta }) => console.log(delta));
|
||||
conversation.on('turn.done', () => conversation.close());
|
||||
|
||||
@@ -1102,8 +1102,9 @@ interface IConfigOptional {
|
||||
/** Force the bundled GUI even in dev. Default: false. */
|
||||
use_bundled_gui: boolean;
|
||||
/**
|
||||
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The app
|
||||
* browser embed loads `apps-embed.min.js` from the same directory.
|
||||
* Override the GUI bundle JS path. Default: `/dist/bundle.min.js`. The
|
||||
* `/embed/*` pages load `apps-embed.min.js` and `feedback-embed.min.js`
|
||||
* from the same directory.
|
||||
*/
|
||||
gui_bundle: string;
|
||||
/** Override the GUI CSS path when bundled. Default: `/dist/bundle.min.css`. */
|
||||
|
||||
+2
-2
@@ -200,8 +200,8 @@ These AI features are supported out of the box when using Puter.js:
|
||||
- **[`puter.ai.img2txt()`](/AI/img2txt/)** - Extract text from images (OCR)
|
||||
- **[`puter.ai.txt2vid()`](/AI/txt2vid/)** - Generate short video clips from text or a reference image with Wan, Seedance, Veo, Kling, MiniMax H3 and other models, or edit a video you supply with Gemini Omni, FLUX 3 or Kling Omni
|
||||
- **[`puter.ai.speech2speech()`](/AI/speech2speech/)** - Convert speech in one voice to another voice
|
||||
- **[`puter.ai.convo()`](/AI/convo/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
|
||||
- **[Realtime WebSocket API](/AI/realtime/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
|
||||
- **[`puter.ai.realtime()`](/AI/realtime/)** - Prepare a beta realtime conversation with optional text, microphone, playback, and interruption helpers
|
||||
- **[Realtime WebSocket API](/AI/realtime-websocket/)** - Connect directly without puter.js. This API is in beta and may change abruptly.
|
||||
- **[`puter.ai.listModels()`](/AI/listModels/)** - List available AI chat models (and providers) that Puter currently exposes.
|
||||
- **[`puter.ai.listModelProviders()`](/AI/listModelProviders/)** - List the AI providers that Puter currently exposes.
|
||||
- **[`puter.ai.txt2speech.listEngines()`](/AI/txt2speech.listEngines/)** - List available TTS engines/models
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
---
|
||||
title: puter.ai.convo()
|
||||
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
Prepares a realtime OpenAI conversation that your app can connect to when it's ready.
|
||||
|
||||
Preparing the conversation verifies Puter sign-in. Realtime conversations require a paid Puter plan, and usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
|
||||
|
||||
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime/).
|
||||
|
||||
## Syntax
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo(options = {});
|
||||
await conversation.connect();
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
#### `options` (Object) (Optional)
|
||||
|
||||
The options object accepts these fields.
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `model` | `String` | The realtime model. Defaults to `gpt-realtime-2.1-mini`. Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
|
||||
| `instructions` | `String` | Session instructions, up to 8192 characters. Defaults to the provider's default. |
|
||||
| `output` | `Array<String>` | Accepts `['text']`, `['audio']`, or both. Defaults to `['audio']`. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
|
||||
| `voice` | `String` | OpenAI voice identifier, up to 128 characters. Defaults to the provider's default. |
|
||||
| `turnDetection` | `Boolean` | Whether the provider detects the end of spoken turns automatically. Defaults to `true`. Set to `false` for manual audio commits. |
|
||||
|
||||
## Return value
|
||||
|
||||
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
|
||||
|
||||
The conversation exposes these properties and methods.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
|
||||
| `model` | Resolved model name. |
|
||||
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
|
||||
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
|
||||
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
|
||||
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
|
||||
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
|
||||
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
|
||||
| `send(event)` | Sends a native OpenAI JSON event. |
|
||||
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
|
||||
| `off(type, handler)` | Removes a listener. |
|
||||
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
|
||||
|
||||
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
|
||||
|
||||
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
|
||||
|
||||
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
|
||||
|
||||
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
|
||||
|
||||
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
|
||||
|
||||
## Errors and limits
|
||||
|
||||
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
|
||||
|
||||
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
|
||||
|
||||
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Convenience events
|
||||
|
||||
The conversation emits these events alongside native events.
|
||||
|
||||
| Event | Fields |
|
||||
| --- | --- |
|
||||
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
|
||||
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
|
||||
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
|
||||
| `text` | `delta`, `responseId` |
|
||||
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
|
||||
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
|
||||
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
|
||||
| `turn.done` | `responseId`, native provider `usage`, `status` |
|
||||
| `close` | `code`, `reason` |
|
||||
|
||||
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
|
||||
|
||||
## Browser media
|
||||
|
||||
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
|
||||
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
|
||||
| `microphone.unmute()` | Enables capture tracks and forwarding. |
|
||||
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
|
||||
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
|
||||
| `speaker.stop()` | Clears playback and releases its audio context. |
|
||||
|
||||
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
|
||||
|
||||
## Examples
|
||||
|
||||
### Have a text conversation
|
||||
|
||||
A text conversation uses convenience methods for input and streamed output.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo({
|
||||
output: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
});
|
||||
|
||||
conversation.on('text', ({ delta }) => console.log(delta));
|
||||
conversation.on('turn.done', () => conversation.close());
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
await conversation.connect();
|
||||
conversation.sendText('Say hello in three words.');
|
||||
```
|
||||
|
||||
### Have a voice conversation
|
||||
|
||||
A voice conversation enables the microphone and speaker after connection.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.convo();
|
||||
conversation.on('transcript', ({ role, text }) => console.log(role, text));
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
await conversation.connect();
|
||||
await conversation.speaker.start();
|
||||
await conversation.microphone.start();
|
||||
|
||||
// To interrupt a response and submit a replacement text turn:
|
||||
await conversation.interrupt();
|
||||
conversation.sendText('Actually, make it Wednesday.');
|
||||
|
||||
// When the user ends the conversation:
|
||||
conversation.close();
|
||||
```
|
||||
@@ -0,0 +1,126 @@
|
||||
---
|
||||
title: Realtime WebSocket API (Beta)
|
||||
description: Connect to OpenAI realtime conversations through Puter without puter.js.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter.
|
||||
|
||||
Puter authenticates the user and charges their account for usage.
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.realtime()`](/AI/realtime/).
|
||||
|
||||
## Connection and authentication
|
||||
|
||||
Connect to this URL on the Puter API host:
|
||||
|
||||
```text
|
||||
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
|
||||
```
|
||||
|
||||
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
|
||||
|
||||
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <PUTER_TOKEN>
|
||||
```
|
||||
|
||||
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
|
||||
|
||||
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
|
||||
|
||||
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Text example
|
||||
|
||||
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
|
||||
|
||||
```js
|
||||
import WebSocket from 'ws';
|
||||
|
||||
const socket = new WebSocket(
|
||||
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
|
||||
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
|
||||
);
|
||||
const send = (event) => socket.send(JSON.stringify(event));
|
||||
|
||||
socket.on('message', (data) => {
|
||||
const event = JSON.parse(data.toString());
|
||||
|
||||
if (event.type === 'session.created') {
|
||||
send({
|
||||
type: 'session.update',
|
||||
session: {
|
||||
type: 'realtime',
|
||||
output_modalities: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
},
|
||||
});
|
||||
}
|
||||
if (event.type === 'session.updated') {
|
||||
send({
|
||||
type: 'conversation.item.create',
|
||||
item: {
|
||||
type: 'message',
|
||||
role: 'user',
|
||||
content: [{ type: 'input_text', text: 'Hello!' }],
|
||||
},
|
||||
});
|
||||
send({ type: 'response.create' });
|
||||
}
|
||||
if (event.type === 'response.output_text.delta')
|
||||
process.stdout.write(event.delta);
|
||||
if (event.type === 'error')
|
||||
console.error(event.error);
|
||||
if (event.type === 'response.done')
|
||||
socket.close();
|
||||
});
|
||||
socket.on('error', console.error);
|
||||
socket.on('close', (code, reason) => console.log(code, reason.toString()));
|
||||
```
|
||||
|
||||
## Events, audio, and interruption
|
||||
|
||||
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
|
||||
|
||||
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
|
||||
|
||||
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
|
||||
|
||||
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
|
||||
|
||||
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
|
||||
|
||||
## Server restarts
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "puter.reconnect",
|
||||
"event_id": "event_puter_1767225600000",
|
||||
"reason": "server_restarting",
|
||||
"close_in_ms": 90000
|
||||
}
|
||||
```
|
||||
|
||||
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
|
||||
|
||||
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
|
||||
|
||||
## Errors, billing, and limits
|
||||
|
||||
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
|
||||
|
||||
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
|
||||
|
||||
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
|
||||
|
||||
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
|
||||
+128
-103
@@ -1,126 +1,151 @@
|
||||
---
|
||||
title: Realtime WebSocket API (Beta)
|
||||
description: Connect to OpenAI realtime conversations through Puter without puter.js.
|
||||
title: puter.ai.realtime()
|
||||
description: Prepare an OpenAI realtime conversation with optional audio and text helpers.
|
||||
platforms: [websites, apps, nodejs, workers]
|
||||
---
|
||||
|
||||
The Realtime WebSocket API lets your client send and receive native OpenAI realtime JSON events through Puter.
|
||||
Prepares a realtime OpenAI conversation that your app can connect to when it's ready.
|
||||
|
||||
Puter authenticates the user and charges their account for usage.
|
||||
Preparing the conversation verifies Puter sign-in. Realtime conversations require a paid Puter plan, and usage is billed to the signed-in user. Native OpenAI events and convenience methods use the same session. Microphone capture and speaker playback start when your app requests them.
|
||||
|
||||
In Node.js, the SDK requires a global `WebSocket`, available in Node.js 22 or later.
|
||||
|
||||
**Beta:** This API is incomplete. Its methods, options, events, and behavior may change abruptly, including breaking changes without notice.
|
||||
|
||||
For optional text, microphone, playback, and interruption helpers, use [`puter.ai.convo()`](/AI/convo/).
|
||||
To connect without puter.js, see the [Realtime WebSocket API](/AI/realtime-websocket/).
|
||||
|
||||
## Connection and authentication
|
||||
|
||||
Connect to this URL on the Puter API host:
|
||||
|
||||
```text
|
||||
wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini
|
||||
```
|
||||
|
||||
The `model` query parameter defaults to `gpt-realtime-2.1-mini`. The model is fixed for the connection. A session update that changes it is rejected. It also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`.
|
||||
|
||||
Authenticate with a Puter session, app, or full-access API token. Puter supplies the provider credential. Server clients pass this header:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <PUTER_TOKEN>
|
||||
```
|
||||
|
||||
Browser WebSocket clients pass `realtime` and `openai-insecure-api-key.<PUTER_TOKEN>` as subprotocols. The server echoes only `realtime`. The endpoint also accepts an `auth_token` query parameter. Prefer the authorization header where supported because URLs and subprotocols can appear in logs. Authentication takes precedence in this order, header, subprotocol, then query parameter.
|
||||
|
||||
The socket can open before authentication and provider setup finish. Listen for errors and closure immediately. Wait for `session.created`, send your session settings, then wait for `session.updated` before submitting a turn.
|
||||
|
||||
To open a replacement while another connection remains healthy, set the optional `purpose=handover` query parameter. These attempts share a smaller per-credential budget, checked before the general connection-attempt budget. Initial connections and dropped-connection recovery use the URL without this parameter. The limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Text example
|
||||
|
||||
Install the `ws` package and set `PUTER_TOKEN` to your Puter token. Run this example as a Node.js ES module:
|
||||
## Syntax
|
||||
|
||||
```js
|
||||
import WebSocket from 'ws';
|
||||
const conversation = await puter.ai.realtime(options = {});
|
||||
await conversation.connect();
|
||||
```
|
||||
|
||||
const socket = new WebSocket(
|
||||
'wss://api.puter.com/puterai/openai/v1/realtime?model=gpt-realtime-2.1-mini',
|
||||
{ headers: { Authorization: `Bearer ${process.env.PUTER_TOKEN}` } },
|
||||
);
|
||||
const send = (event) => socket.send(JSON.stringify(event));
|
||||
## Parameters
|
||||
|
||||
socket.on('message', (data) => {
|
||||
const event = JSON.parse(data.toString());
|
||||
#### `options` (Object) (Optional)
|
||||
|
||||
if (event.type === 'session.created') {
|
||||
send({
|
||||
type: 'session.update',
|
||||
session: {
|
||||
type: 'realtime',
|
||||
output_modalities: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
},
|
||||
});
|
||||
}
|
||||
if (event.type === 'session.updated') {
|
||||
send({
|
||||
type: 'conversation.item.create',
|
||||
item: {
|
||||
type: 'message',
|
||||
role: 'user',
|
||||
content: [{ type: 'input_text', text: 'Hello!' }],
|
||||
},
|
||||
});
|
||||
send({ type: 'response.create' });
|
||||
}
|
||||
if (event.type === 'response.output_text.delta')
|
||||
process.stdout.write(event.delta);
|
||||
if (event.type === 'error')
|
||||
console.error(event.error);
|
||||
if (event.type === 'response.done')
|
||||
socket.close();
|
||||
The options object accepts these fields.
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `model` | `String` | The realtime model. Defaults to `gpt-realtime-2.1-mini`. Also accepts `gpt-realtime-2.1`, `gpt-realtime-2`, `gpt-realtime-1.5`, `gpt-realtime`, and `gpt-realtime-mini`. |
|
||||
| `instructions` | `String` | Session instructions, up to 8192 characters. Defaults to the provider's default. |
|
||||
| `output` | `Array<String>` | Accepts `['text']`, `['audio']`, or both. Defaults to `['audio']`. Audio includes a transcript. Requesting both uses audio output and emits transcript deltas through the `text` event. |
|
||||
| `voice` | `String` | OpenAI voice identifier, up to 128 characters. Defaults to the provider's default. |
|
||||
| `turnDetection` | `Boolean` | Whether the provider detects the end of spoken turns automatically. Defaults to `true`. Set to `false` for manual audio commits. |
|
||||
|
||||
## Return value
|
||||
|
||||
A Promise resolves to a prepared conversation after options and sign-in are checked. In a browser, preparation opens the Puter sign-in prompt if needed. Preparation opens no realtime connection and requests no microphone access.
|
||||
|
||||
The conversation exposes these properties and methods.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `state` | `prepared`, `connecting`, `connected`, or `closed`. |
|
||||
| `model` | Resolved model name. |
|
||||
| `connect()` | Opens the connection and applies settings. Resolves after the provider acknowledges session configuration. Concurrent calls share one connection Promise, including bounded retries for transient setup failures. Calling it while connected opens no additional connection. During a reconnection, it resolves when the reconnection succeeds and rejects if the conversation closes instead. |
|
||||
| `configure(options)` | Updates the given session settings and resolves after the provider acknowledges this update. Settings it isn't given, including ones set through native events, are left alone. Accepts the factory options except `model`. One update can be pending at a time. Provider rules apply to changes such as switching a voice after audio has been generated. |
|
||||
| `sendText(text)` | Adds a user message and requests a response. Text must be nonempty and at most 8192 characters. |
|
||||
| `appendAudio(pcm)` | Appends an `Int16Array` containing PCM16, 24 kHz mono audio. A chunk contains at most 12000 samples. |
|
||||
| `commitAudio()` | Commits buffered audio and requests a response. Requires turn detection to be off, through `turnDetection: false` or a native session update. The provider requires at least 100 ms of buffered audio. |
|
||||
| `interrupt(position?)` | Stops built-in playback immediately and waits for cancellation and playback-history synchronization. A reply requested but not yet started is cancelled as soon as it starts. Custom players provide `{ itemId, contentIndex, playedMs }`. An idle call resolves immediately. Readiness failures reject the returned Promise with `session_not_ready` or `session_closed`. |
|
||||
| `send(event)` | Sends a native OpenAI JSON event. |
|
||||
| `on(type, handler)` | Registers a listener and returns an unsubscribe function. Use `'*'` to receive every native and convenience event. |
|
||||
| `off(type, handler)` | Removes a listener. |
|
||||
| `close()` | Closes the session, rejects pending operations, and releases SDK-owned capture and playback resources. Repeated calls have no additional effect. |
|
||||
|
||||
Attach listeners before connecting to receive initial session events. Closing during connection rejects the pending attempt.
|
||||
|
||||
If the connection drops because of network loss, a server restart or a provider error, the conversation reconnects on its own. Normal closes with code 1000 end the conversation. While it reconnects, `state` is `connecting`, a `reconnecting` event fires, and pending operations reject with `connection_lost`. The new session gets every setting the provider acknowledged, from the factory options, `configure()` and native `session.update` events. Then `ready` fires again with `reconnected: true`. Listeners, the microphone and the speaker carry over. Microphone audio captured while reconnecting is dropped.
|
||||
|
||||
The conversation also restores recent context. Before `ready` fires, it adds back up to 40 of the most recent conversation items, 48 KiB in total. Restored items are user text, user speech that has a transcript, assistant replies as text, and function calls with their outputs. User speech has a transcript only when input transcription is configured through native session settings. An assistant reply that was interrupted, or still playing when the connection dropped, is cut to what the user saw or heard. The cut is estimated from how much of the audio played, so it can be off by a few words. Images, speech without a transcript, deleted items, and replies still generating when the connection dropped are left out. Restored items get new item IDs, don't fire item events, and count as input tokens on the next response. Item IDs from before the reconnect don't work in later events. Restoration uses a contiguous suffix of restorable items. An oversized newest item leaves that suffix empty. Older items left out to fit the window fire a `context_trimmed` event with the count in `omittedItems`; this is routine and not an error. A provider refusal or a failure to send the restored items fires one `error` event with code `context_restore_failed` per restoration. In both cases the conversation stays connected. Items are preserved without truncating text, function arguments or function results.
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends a `puter.reconnect` event, which also reaches your listeners. Without that notice, a restart drops the connection and the conversation reconnects as above. Within a few seconds, the conversation opens a replacement session in the background while the current one keeps working. It switches once no reply is generating or playing, no user turn is being spoken or transcribed, no function call is waiting for its output, and nothing you sent is waiting on the provider. The switch goes through the same steps as a reconnect, and the `reconnecting` event has code 1012. If the replacement can't open yet, the conversation keeps the current session and tries again later. A refusal that retrying can't fix, such as `insufficient_funds`, stops the attempts. If the server closes the session first, the conversation switches to the replacement, or reconnects if none is open.
|
||||
|
||||
The conversation makes up to ten attempts over about a minute. In a browser that reports being offline, it first waits up to two minutes for the connection to come back. If every attempt fails, or the server refuses with an error such as `insufficient_funds`, the conversation closes. A closed conversation cannot reconnect. To start another session, prepare a new one.
|
||||
|
||||
Native event definitions are listed in the [OpenAI realtime reference](https://developers.openai.com/api/reference/resources/realtime/server-events). Native events retain their provider fields. Sending native events preserves direct control of the session. Puter refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. Sending one fires an `error` event with code `invalid_event`, and the conversation closes with code 1008. Audio helpers expect the session to use PCM16 at 24 kHz.
|
||||
|
||||
## Errors and limits
|
||||
|
||||
Failures use objects containing `code` and `message`. Preparation can reject with `invalid_argument`, `model_not_found`, `auth_required`, `auth_canceled`, or `auth_failed`. Connection can reject with `subscription_required` or `insufficient_funds`, which also show the Puter upgrade prompt. Connection and asynchronous operations can reject with provider errors, `session_closed`, `connection_lost`, `operation_timeout`, or `operation_in_progress`. Sending before readiness, or while reconnecting, throws `session_not_ready`.
|
||||
|
||||
Invalid input throws `invalid_argument`, `invalid_event`, or `input_too_large`. A full SDK send queue throws `queue_full`. Media helpers report `unsupported_environment`, `permission_denied`, `media_error`, `media_timeout`, or `queue_full`. Runtime media errors and `context_restore_failed` arrive through the `error` event. Provider errors also arrive as native `error` events with a nested `error` object.
|
||||
|
||||
Each native event is capped at 64 KiB. The SDK bounds JSON traversal, outgoing queues, acknowledgment waits, microphone work, and playback. All numeric limits are listed on [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
## Convenience events
|
||||
|
||||
The conversation emits these events alongside native events.
|
||||
|
||||
| Event | Fields |
|
||||
| --- | --- |
|
||||
| `ready` | `model`, `provider`, and `reconnected: true` after a reconnection |
|
||||
| `reconnecting` | `code`, `reason` of the dropped connection. After a `puter.reconnect` event, `code` is 1012. |
|
||||
| `context_trimmed` | `omittedItems`, the number of restorable items left out of the restored context after a reconnection. Fires before `ready`. |
|
||||
| `text` | `delta`, `responseId` |
|
||||
| `transcript` | `role`, `text`, `final`. Assistant deltas use `final: false`. Completed assistant and user transcripts use `final: true`. User transcripts require transcription to be configured through native session settings. |
|
||||
| `audio` | `pcm`, `sampleRate`, `responseId`, `itemId`, `contentIndex`. The PCM chunk is an `Int16Array`. |
|
||||
| `interrupted` | `source` (`manual` or `speech`), `responseId` |
|
||||
| `turn.done` | `responseId`, native provider `usage`, `status` |
|
||||
| `close` | `code`, `reason` |
|
||||
|
||||
Each event includes its `type`. When the provider event leaves out an ID, `responseId` and `itemId` are empty strings and `contentIndex` is `0`. The `interrupted` event signals local interruption immediately. Its corresponding operation resolves after the provider acknowledges cancellation and any requested truncation. Late audio from a canceled response remains visible as native events and is excluded from convenience audio and built-in playback.
|
||||
|
||||
## Browser media
|
||||
|
||||
The optional microphone and speaker helpers require a browser with Web Audio support. Microphone capture also requires media permissions and a secure context. Start audio from a user action so the browser can allow playback.
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `microphone.start()` | Requests microphone access and streams PCM16, resampled to 24 kHz, in 20 ms chunks through an AudioWorklet. If the page or network falls behind, chunks are dropped rather than stopping capture. |
|
||||
| `microphone.mute()` | Disables capture tracks and stops forwarding captured chunks. |
|
||||
| `microphone.unmute()` | Enables capture tracks and forwarding. |
|
||||
| `microphone.stop()` | Stops capture tracks and releases capture resources. A `start()` still waiting on the permission prompt rejects with `session_closed`. |
|
||||
| `speaker.start({ bargeIn: true })` | Starts playback. Barge-in defaults to `true`. With barge-in enabled, provider speech-start events interrupt playback and synchronize played audio with conversation history. Starting the speaker requests no microphone access. |
|
||||
| `speaker.stop()` | Clears playback and releases its audio context. |
|
||||
|
||||
Both start methods require a connected session. Capture and playback are independent, so custom audio input can use the built-in speaker, and built-in capture can use custom playback.
|
||||
|
||||
## Examples
|
||||
|
||||
### Have a text conversation
|
||||
|
||||
A text conversation uses convenience methods for input and streamed output.
|
||||
|
||||
```js
|
||||
const conversation = await puter.ai.realtime({
|
||||
output: ['text'],
|
||||
instructions: 'Keep replies short.',
|
||||
});
|
||||
socket.on('error', console.error);
|
||||
socket.on('close', (code, reason) => console.log(code, reason.toString()));
|
||||
|
||||
conversation.on('text', ({ delta }) => console.log(delta));
|
||||
conversation.on('turn.done', () => conversation.close());
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
await conversation.connect();
|
||||
conversation.sendText('Say hello in three words.');
|
||||
```
|
||||
|
||||
## Events, audio, and interruption
|
||||
### Have a voice conversation
|
||||
|
||||
Each message contains one JSON object with a nonempty string `type` of at most 128 characters. Binary messages are rejected. Native events retain their provider fields. The endpoint doesn't deliver `rate_limits.updated`, which describes Puter's provider account rather than yours, and it removes provider organization IDs from error messages. The endpoint exposes the WebSocket event protocol. Your client manages capture, playback, acknowledgments, and timeouts.
|
||||
A voice conversation enables the microphone and speaker after connection.
|
||||
|
||||
The endpoint refuses `conversation.item.retrieve` events and MCP tools (`"type": "mcp"`) in `session.update` and `response.create` events. A refused event isn't sent to the provider. The session gets an `invalid_event` error and closes with 1008.
|
||||
```js
|
||||
const conversation = await puter.ai.realtime();
|
||||
conversation.on('transcript', ({ role, text }) => console.log(role, text));
|
||||
conversation.on('error', (event) => console.error(event));
|
||||
|
||||
PCM16 audio configured at 24 kHz mono is sent as base64 chunks in `input_audio_buffer.append` events. Output arrives in `response.output_audio.delta` events. With manual turn detection, commit buffered input with `input_audio_buffer.commit`, then request a reply with `response.create`.
|
||||
await conversation.connect();
|
||||
await conversation.speaker.start();
|
||||
await conversation.microphone.start();
|
||||
|
||||
To interrupt, stop local playback immediately and send `response.cancel` with the active `response_id`. If some generated audio was not played, send `conversation.item.truncate` with its `item_id`, `content_index`, and `audio_end_ms` set to the amount actually played. Wait for `response.done` and any requested `conversation.item.truncated` acknowledgment before submitting a replacement turn.
|
||||
// To interrupt a response and submit a replacement text turn:
|
||||
await conversation.interrupt();
|
||||
conversation.sendText('Actually, make it Wednesday.');
|
||||
|
||||
Connection loss ends the session. Reconnecting creates a new conversation. Tool execution and automatic reconnection belong to your client.
|
||||
|
||||
## Server restarts
|
||||
|
||||
When Puter knows ahead of time that the server a session runs on will restart, it sends each open session this event, at most once a minute:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "puter.reconnect",
|
||||
"event_id": "event_puter_1767225600000",
|
||||
"reason": "server_restarting",
|
||||
"close_in_ms": 90000
|
||||
}
|
||||
// When the user ends the conversation:
|
||||
conversation.close();
|
||||
```
|
||||
|
||||
The `reason` field is `server_restarting`. The `close_in_ms` field, when present, is about how long until the server closes the session itself. The session keeps working until then. Open a new connection after a short, randomized delay, and once it gets `session.created` and your client is idle, with no response generating and no user turn in progress, move to it and close the old one. A connection that reaches a server that is also restarting gets a `server_restarting` error and closes with 1012. In that case keep the old session and try again after a short, randomized delay. If the server closes the old session first, the close code is 1012, and your client reconnects the same way. A restart can also drop the connection without any notice, so treat an unexpected close the same way.
|
||||
|
||||
A new connection starts an empty conversation. To keep context, add earlier items back with `conversation.item.create` before you request a response. Event types that start with `puter.` come from Puter, not the provider.
|
||||
|
||||
## Errors, billing, and limits
|
||||
|
||||
API errors arrive as `{ "type": "error", "error": { "code": "...", "message": "..." } }`. Handle socket errors and close frames too. Invalid, missing, or revoked credentials use `invalid_api_key`. If Puter can't check a credential or the account's plan, the error is `internal_error` and the session closes with 1011, so try again after a short, randomized delay. Other relay codes include `permission_denied`, `model_not_found`, `insufficient_funds`, `subscription_required`, `rate_limit_exceeded`, `invalid_event`, `connection_timeout`, `provider_unavailable`, `upstream_error`, and `server_restarting`.
|
||||
|
||||
Policy failures generally close with 1008, oversized client messages with 1009, upstream or setup failures with 1011, server restarts with 1012, and temporary server overload with 1013. Reconnect after 1011, 1012, or 1013. Authentication and model failures can arrive after the WebSocket handshake succeeds.
|
||||
|
||||
The endpoint requires a paid Puter plan. Usage is charged after completed responses and input transcriptions. While a response generates, part of your balance is held for it, so a session opens only if your balance covers one response. If the provider connection closes before a response reports its usage, the response is charged the full amount held for it. Each account can open 20 sessions at once by default. Each JSON message you send is limited to 64 KiB, including reassembled fragments. Messages from the provider can be up to 4 MiB. Stream audio in small chunks. All message rates, queue caps, timeouts, and other bounds are published in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Input transcription holds a small amount of your balance per transcribed item, priced at the transcription model you select. Two items are reserved ahead of your audio and replenished as the provider commits them, so a session holds only its spare items plus the items still awaiting a transcript. Changing the transcription model reprices the spare items. If your balance can't cover another item, audio waits while earlier items settle; once none are left to settle, the session closes with `insufficient_funds`. Failed transcriptions, items without final usage, and audio whose commit the provider never acknowledges before the connection closes are each charged that model's fixed per-item amount. Unacknowledged audio is charged one item per started 160 seconds. With server turn detection, only detected speech counts, so silence is never charged. The amounts, timeout and audio limits are listed in [rate limits and quotas](/rate-limits-and-quotas/).
|
||||
|
||||
Provider-reported realtime models must have a known price. A missing model uses the last known model. An explicitly unpriced model closes the connection with `upstream_error`.
|
||||
|
||||
After recording usage, the connection can continue while settled credit is positive, including a fractional balance. Each new billable operation still needs its full reservation after accounting for other outstanding holds.
|
||||
@@ -6,7 +6,7 @@ platforms: [websites]
|
||||
|
||||
Initiates the sign in process for the user.
|
||||
|
||||
This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in.
|
||||
This will open a popup window with the appropriate authentication method. Puter automatically handles the authentication process and will resolve the promise when the user has signed in. Puter's own apps on puter.com subdomains show the sign-in in a frame over the page instead, and open the popup when the user picks a sign-in provider such as Google.
|
||||
|
||||
It is important to note that all essential methods in Puter handle authentication automatically. This method is only necessary if you want to handle authentication manually, for example if you want to build your own custom authentication flow.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Opens a dialog where the user can send you, the app's developer, feedback about
|
||||
|
||||
The message is delivered by Puter: it is stored and emailed to the email address on your Puter account. The feedback never passes through your app's code, and the dialog tells the user what is shared with you: their username, plus their email address (as the email's reply-to, so you can respond) when their email is verified.
|
||||
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog (signing the user in first if needed).
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog (signing the user in first if needed). Puter's own apps on puter.com subdomains show it in a frame over the page instead, when the user is signed in to both.
|
||||
|
||||
**Feedback is opt-in.** Users can only send feedback if it's enabled for your app. Apps created in the Dev Center have feedback enabled at creation — you can turn it off with the "User Feedback" toggle in the app's settings. Apps created through `puter.apps.create` default to off; enable it by setting `feedbackEnabled`:
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ Gemini speech-to-text first counts the audio's tokens, which times out after 30
|
||||
|
||||
The OpenAI- and Anthropic-compatible endpoints (`/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages`) require a paid plan; a free account gets `402 subscription_required`. The same models are available to every account through `puter.ai.*` and `/drivers/call`, and the model catalogue endpoints are open to everyone.
|
||||
|
||||
Realtime sessions ([`puter.ai.convo()`](/AI/convo/), `/puterai/openai/v1/realtime`) require a paid plan, like the other OpenAI-compatible endpoints, and are capped at 20 open at once per account. An account without a plan gets an `error` event with code `subscription_required`. A session over the cap gets `rate_limit_exceeded`. Both close with 1008.
|
||||
Realtime sessions ([`puter.ai.realtime()`](/AI/realtime/), `/puterai/openai/v1/realtime`) require a paid plan, like the other OpenAI-compatible endpoints, and are capped at 20 open at once per account. An account without a plan gets an `error` event with code `subscription_required`. A session over the cap gets `rate_limit_exceeded`. Both close with 1008.
|
||||
|
||||
| Realtime transport limit | Value | Behavior at the limit |
|
||||
| --- | --- | --- |
|
||||
@@ -131,7 +131,7 @@ Realtime sessions ([`puter.ai.convo()`](/AI/convo/), `/puterai/openai/v1/realtim
|
||||
|
||||
Send audio as a stream of small chunks. The message cap applies to text, configuration, tool output, and audio alike.
|
||||
|
||||
The [`puter.ai.convo()`](/AI/convo/) SDK also applies these limits before sending or retaining data.
|
||||
The [`puter.ai.realtime()`](/AI/realtime/) SDK also applies these limits before sending or retaining data.
|
||||
|
||||
| Conversation SDK limit | Value | Behavior at the limit |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -124,17 +124,17 @@ let sidebar = [
|
||||
path: '/AI/speech2speech',
|
||||
},
|
||||
{
|
||||
title: '<code>convo()</code>',
|
||||
page_title: '<code>puter.ai.convo()</code>',
|
||||
title_tag: 'puter.ai.convo()',
|
||||
title: '<code>realtime()</code>',
|
||||
page_title: '<code>puter.ai.realtime()</code>',
|
||||
title_tag: 'puter.ai.realtime()',
|
||||
icon: '/assets/img/function.svg',
|
||||
source: '/AI/convo.md',
|
||||
path: '/AI/convo',
|
||||
source: '/AI/realtime.md',
|
||||
path: '/AI/realtime',
|
||||
},
|
||||
{
|
||||
title: 'Realtime WebSocket API (Beta)',
|
||||
source: '/AI/realtime.md',
|
||||
path: '/AI/realtime',
|
||||
source: '/AI/realtime-websocket.md',
|
||||
path: '/AI/realtime-websocket',
|
||||
},
|
||||
{
|
||||
title: '<code>listModels()</code>',
|
||||
|
||||
+4
-42
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import download from './helpers/download.js';
|
||||
import ensureConfirmedEmail from './helpers/ensureConfirmedEmail.js';
|
||||
import item_icon from './helpers/itemIcon.js';
|
||||
import socialLink from './helpers/socialLink.js';
|
||||
import update_mouse_position from './helpers/updateMousePosition.js';
|
||||
@@ -31,11 +32,9 @@ import UIWindow from './UI/UIWindow.js';
|
||||
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
|
||||
import UIWindowAttachCustomDomain from './UI/UIWindowAttachCustomDomain.js';
|
||||
import UIWindowColorPicker from './UI/UIWindowColorPicker.js';
|
||||
import UIWindowEmailConfirmationRequired from './UI/UIWindowEmailConfirmationRequired.js';
|
||||
import UIWindowFontPicker from './UI/UIWindowFontPicker.js';
|
||||
import UIPermissionDialog from './UI/UIPermissionDialog.js';
|
||||
import UIEnablePushDialog from './UI/UIEnablePushDialog.js';
|
||||
import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
|
||||
import UIAuthSignup from './UI/Auth/UIAuthSignup.js';
|
||||
import UINotification from './UI/UINotification.js';
|
||||
|
||||
@@ -235,49 +234,12 @@ const ipc_listener = async (event, handled) => {
|
||||
// requestEmailConfirmation
|
||||
//--------------------------------------------------------
|
||||
else if ( event.data.msg === 'requestEmailConfirmation' ) {
|
||||
// If the user has an email and it is confirmed, respond with success
|
||||
if ( window.user.email && window.user.email_confirmed ) {
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: true,
|
||||
}, '*');
|
||||
}
|
||||
|
||||
// If the user is a temporary user, show the save account window
|
||||
if ( window.user.is_temp &&
|
||||
!await UIWindowSaveAccount({
|
||||
send_confirmation_code: true,
|
||||
message: 'Please create an account to proceed.',
|
||||
window_options: {
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
},
|
||||
}) ) {
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: false,
|
||||
}, '*');
|
||||
return;
|
||||
}
|
||||
else if ( !window.user.email_confirmed && !await UIWindowEmailConfirmationRequired() ) {
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: false,
|
||||
}, '*');
|
||||
return;
|
||||
}
|
||||
|
||||
const email_confirm_resp = await UIWindowEmailConfirmationRequired({
|
||||
email: window.user.email,
|
||||
});
|
||||
|
||||
// Above the app's window, which stays on top in the dashboard.
|
||||
const confirmed = await ensureConfirmedEmail(i18n('save_account_to_proceed'), { stay_on_top: true });
|
||||
target_iframe.contentWindow.postMessage({
|
||||
original_msg_id: msg_id,
|
||||
msg: 'requestEmailConfirmationResponded',
|
||||
response: email_confirm_resp,
|
||||
response: confirmed,
|
||||
}, '*');
|
||||
}
|
||||
//--------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
globalThis.def = globalThis.def ?? ((cls) => cls);
|
||||
globalThis.use = globalThis.use ?? (() => ({}));
|
||||
globalThis.$ = globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = (key) => key;
|
||||
|
||||
const { stub, confirmEmail, saveAccount } = vi.hoisted(() => ({
|
||||
stub: () => ({ default: () => {} }),
|
||||
confirmEmail: vi.fn(),
|
||||
saveAccount: vi.fn(),
|
||||
}));
|
||||
vi.mock('./helpers/download.js', stub);
|
||||
vi.mock('./helpers/itemIcon.js', stub);
|
||||
vi.mock('./helpers/socialLink.js', stub);
|
||||
vi.mock('./helpers/updateMousePosition.js', stub);
|
||||
vi.mock('./UI/UIAlert.js', stub);
|
||||
vi.mock('./UI/UIContextMenu.js', stub);
|
||||
vi.mock('./UI/UIItem.js', stub);
|
||||
vi.mock('./UI/UIPopover.js', stub);
|
||||
vi.mock('./UI/UIPrompt.js', stub);
|
||||
vi.mock('./UI/UIWindow.js', stub);
|
||||
vi.mock('./UI/UIWindowAppFeedback.js', stub);
|
||||
vi.mock('./UI/UIWindowColorPicker.js', stub);
|
||||
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', () => ({ default: confirmEmail }));
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
vi.mock('./UI/UIEnablePushDialog.js', stub);
|
||||
vi.mock('./UI/UIWindowSaveAccount.js', () => ({ default: saveAccount }));
|
||||
vi.mock('./UI/Auth/UIAuthSignup.js', stub);
|
||||
vi.mock('./UI/UINotification.js', stub);
|
||||
vi.mock('./helpers/godmodeTokens.js', () => ({ renewGodmodeToken: vi.fn() }));
|
||||
vi.mock('./helpers/watchItems.js', () => ({ addItemWatcher: vi.fn() }));
|
||||
vi.mock('./helpers/verification_gates.js', () => ({
|
||||
openVerificationGateWindow: vi.fn(),
|
||||
}));
|
||||
|
||||
let iframe;
|
||||
let posted;
|
||||
|
||||
beforeAll(async () => {
|
||||
window.when_puter_happens = [];
|
||||
window.appCallbackFunctions = {};
|
||||
await import('./IPC.js');
|
||||
globalThis.puter = { services: undefined, util: { rpc: { send: vi.fn() } } };
|
||||
for (const fn of window.when_puter_happens) await fn();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
confirmEmail.mockReset();
|
||||
saveAccount.mockReset();
|
||||
document.body.innerHTML = '';
|
||||
const win = document.createElement('div');
|
||||
win.setAttribute('data-app_uuid', 'app-1');
|
||||
iframe = document.createElement('iframe');
|
||||
iframe.setAttribute('data-app', 'notes');
|
||||
win.append(iframe);
|
||||
document.body.append(win);
|
||||
posted = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
|
||||
window.app_instance_ids = new Set(['inst-1']);
|
||||
window.iframe_for_app_instance = (id) => (id === 'inst-1' ? iframe : null);
|
||||
window.window_for_app_instance = () => win;
|
||||
window.is_auth = () => true;
|
||||
window.ipc_handlers = {};
|
||||
globalThis.services = { get: () => ({ get_by_uuid: () => ({ name: 'caller', uuid: 'inst-1' }) }) };
|
||||
});
|
||||
|
||||
const request = () =>
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: { appInstanceID: 'inst-1', env: 'app', msg: 'requestEmailConfirmation', uuid: 'cb-1' },
|
||||
source: iframe.contentWindow,
|
||||
origin: 'https://app.example',
|
||||
}),
|
||||
);
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const replies = () => posted.mock.calls
|
||||
.map(([data]) => data)
|
||||
.filter((data) => data.msg === 'requestEmailConfirmationResponded');
|
||||
|
||||
describe('requestEmailConfirmation', () => {
|
||||
it('answers a confirmed email true once, without a dialog', async () => {
|
||||
window.user = { email: '[email protected]', email_confirmed: true };
|
||||
request();
|
||||
await settle();
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: true }]);
|
||||
expect(confirmEmail).not.toHaveBeenCalled();
|
||||
expect(saveAccount).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([true, false])('shows an unconfirmed email one dialog and answers its result, %s', async (answer) => {
|
||||
window.user = { email: '[email protected]', email_confirmed: false };
|
||||
confirmEmail.mockResolvedValueOnce(answer);
|
||||
request();
|
||||
await settle();
|
||||
expect(confirmEmail).toHaveBeenCalledTimes(1);
|
||||
// The app's window stays on top in the dashboard, so the dialog has to as well.
|
||||
expect(confirmEmail).toHaveBeenCalledWith({ window_options: { stay_on_top: true } });
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: answer }]);
|
||||
});
|
||||
|
||||
it('answers false once when a temporary account isn\'t saved', async () => {
|
||||
window.user = { is_temp: true };
|
||||
saveAccount.mockResolvedValueOnce(false);
|
||||
request();
|
||||
await settle();
|
||||
expect(saveAccount).toHaveBeenCalledTimes(1);
|
||||
expect(saveAccount.mock.calls[0][0].window_options).toMatchObject({ stay_on_top: true });
|
||||
expect(confirmEmail).not.toHaveBeenCalled();
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: false }]);
|
||||
});
|
||||
|
||||
it('asks a temporary account that confirmed while saving for nothing more', async () => {
|
||||
window.user = { is_temp: true };
|
||||
saveAccount.mockImplementationOnce(async () => {
|
||||
window.user = { is_temp: false, email: '[email protected]', email_confirmed: true };
|
||||
return true;
|
||||
});
|
||||
request();
|
||||
await settle();
|
||||
expect(confirmEmail).not.toHaveBeenCalled();
|
||||
expect(replies()).toEqual([{ original_msg_id: 'cb-1', msg: 'requestEmailConfirmationResponded', response: true }]);
|
||||
});
|
||||
});
|
||||
@@ -225,6 +225,29 @@ describe('OIDC buttons on the login and signup screens', () => {
|
||||
window.location = original;
|
||||
expect(assign.mock.calls[0][0]).toBe('https://puter.test/auth/oidc/google/start?flow=login&referrer=ref');
|
||||
});
|
||||
|
||||
it('hands a framed sign-in to the popup instead of leaving for the provider', async () => {
|
||||
asPopup('msg_id=1');
|
||||
window.embedded_in_frame = true;
|
||||
window.tell_popup_frame = vi.fn();
|
||||
try {
|
||||
void UIAuthLogin();
|
||||
await vi.waitFor(() => expect($('.oidc-google-btn')).toHaveLength(1));
|
||||
const href = window.location.href;
|
||||
$('.oidc-google-btn').trigger('click');
|
||||
expect(window.tell_popup_frame.mock.calls).toEqual([
|
||||
['provider', { url: expect.stringContaining('https://puter.test/auth/oidc/google/start?flow=login') }],
|
||||
['unavailable'],
|
||||
]);
|
||||
const start = new URL(window.tell_popup_frame.mock.calls[0][1].url);
|
||||
expect(start.searchParams.get('embedded_in_popup')).toBe('true');
|
||||
expect(start.searchParams.get('msg_id')).toBe('1');
|
||||
expect(window.location.href).toBe(href);
|
||||
} finally {
|
||||
delete window.embedded_in_frame;
|
||||
delete window.tell_popup_frame;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('second factor', () => {
|
||||
|
||||
@@ -111,8 +111,8 @@ const runVerificationGates = async (user, show_email, reload_on_success, page) =
|
||||
let email_verified = true;
|
||||
const emailGate = async () => {
|
||||
if ( ! show_email ) return;
|
||||
// Its ✕ would close it without an answer, leaving the caller
|
||||
// waiting on a card that is already gone.
|
||||
// No ✕: the signup card it replaced is already gone, so there's
|
||||
// nothing to go back to.
|
||||
email_verified = await UIWindowEmailConfirmationRequired({
|
||||
show_close_button: false,
|
||||
stay_on_top: true,
|
||||
|
||||
@@ -191,9 +191,15 @@ export default function openAuthFlow ({ page = false, dismissable = ! page, clos
|
||||
/** @type {Array<AuthScreen & { $el: jQuery, el_return?: Element | null }>} */
|
||||
const stack = [];
|
||||
|
||||
// A frame's focus() calls do nothing until the framing page focuses it,
|
||||
// so the screen takes focus then, unless something already has it.
|
||||
const onFrameFocus = () => {
|
||||
if ( ! document.activeElement || document.activeElement === document.body ) flow.focus();
|
||||
};
|
||||
const teardown = () => {
|
||||
if ( torn_down ) return;
|
||||
torn_down = true;
|
||||
window.removeEventListener('focus', onFrameFocus);
|
||||
if ( active_flow === flow ) active_flow = null;
|
||||
// Screens waiting on the user (the second factor) hear they won't get an answer.
|
||||
while ( stack.length ) stack.pop().onLeave?.();
|
||||
@@ -352,8 +358,14 @@ export default function openAuthFlow ({ page = false, dismissable = ! page, clos
|
||||
$overlay.on('keydown keyup keypress', function (e) {
|
||||
e.stopPropagation();
|
||||
if ( e.type !== 'keydown' || e.key !== 'Escape' ) return;
|
||||
// An Escape that cancels an IME conversion is the IME's; jQuery's
|
||||
// event doesn't carry isComposing, the browser's does.
|
||||
if ( e.originalEvent?.isComposing || e.keyCode === 229 ) return;
|
||||
e.preventDefault();
|
||||
if ( dismissable && ! busy ) $dialog.find('.dashboard-dialog-close').trigger('click');
|
||||
if ( busy ) return;
|
||||
if ( dismissable ) $dialog.find('.dashboard-dialog-close').trigger('click');
|
||||
// A framed sign-in's ✕ is the framing page's, which close() asks.
|
||||
else if ( window.embedded_in_frame ) window.close();
|
||||
});
|
||||
// A press on the backdrop (or a page's background) would move focus to
|
||||
// the page, and with it the keys; it stays where it was.
|
||||
@@ -361,6 +373,8 @@ export default function openAuthFlow ({ page = false, dismissable = ! page, clos
|
||||
if ( e.target === this ) e.preventDefault();
|
||||
});
|
||||
|
||||
if ( window.embedded_in_frame ) window.addEventListener('focus', onFrameFocus);
|
||||
|
||||
active_flow = flow;
|
||||
return flow;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,56 @@ describe('openAuthFlow', () => {
|
||||
expect(flow.isClosed()).toBe(false);
|
||||
});
|
||||
|
||||
it('lets Escape ask the framing page to close a framed sign-in, unless busy', async () => {
|
||||
window.embedded_in_frame = true;
|
||||
const close = vi.spyOn(window, 'close').mockImplementation(() => {});
|
||||
try {
|
||||
const flow = openAuthFlow({ page: true });
|
||||
flow.push({ name: 'a', html: '<input>' });
|
||||
await tick();
|
||||
flow.setBusy(true);
|
||||
key($('.auth-dialog input').get(0), 'Escape');
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
flow.setBusy(false);
|
||||
// Escape that cancels an IME conversion is the IME's.
|
||||
$('.auth-dialog input').get(0).dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', isComposing: true, bubbles: true }));
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
key($('.auth-dialog input').get(0), 'Escape');
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
flow.finish(false);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
delete window.embedded_in_frame;
|
||||
}
|
||||
});
|
||||
|
||||
it('focuses a framed screen once the framing page focuses the frame', async () => {
|
||||
window.embedded_in_frame = true;
|
||||
try {
|
||||
const flow = openAuthFlow({ page: true });
|
||||
flow.push({ name: 'a', html: '<input>' });
|
||||
// What a frame's focus() amounts to before the page focuses it.
|
||||
document.activeElement.blur();
|
||||
window.dispatchEvent(new FocusEvent('focus'));
|
||||
// jsdom lays nothing out, so the screen's fallback, the card, takes it.
|
||||
expect($('.auth-dialog').get(0).contains(document.activeElement)).toBe(true);
|
||||
|
||||
// Focus the user moved elsewhere stays there.
|
||||
const el_outside = $('<button class="outside">').appendTo('body').get(0);
|
||||
el_outside.focus();
|
||||
window.dispatchEvent(new FocusEvent('focus'));
|
||||
expect(document.activeElement).toBe(el_outside);
|
||||
el_outside.remove();
|
||||
|
||||
flow.finish(false);
|
||||
document.activeElement.blur();
|
||||
window.dispatchEvent(new FocusEvent('focus'));
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
} finally {
|
||||
delete window.embedded_in_frame;
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores the backdrop unless asked, so a stray click keeps typed credentials', async () => {
|
||||
const kept = openAuthFlow();
|
||||
kept.push({ name: 'a', html: '' });
|
||||
|
||||
@@ -134,7 +134,15 @@ export async function renderProviderButtons ($list, { kind, referrer, flow }) {
|
||||
}
|
||||
$list.html(h);
|
||||
$list.on('click', '.auth-provider-btn', function () {
|
||||
window.location.href = providerStartUrl($(this).attr('data-provider'), kind, referrer());
|
||||
const url = providerStartUrl($(this).attr('data-provider'), kind, referrer());
|
||||
// A provider won't load in a frame, so the framing page opens this
|
||||
// in a popup instead. `unavailable` covers an SDK that can't.
|
||||
if ( window.embedded_in_frame ) {
|
||||
window.tell_popup_frame('provider', { url });
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
}
|
||||
window.location.href = url;
|
||||
});
|
||||
return { providers: ordered, signupOidcOnly: data.signupOidcOnly === true };
|
||||
}
|
||||
@@ -383,7 +383,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
function trapModalTab ($overlay) {
|
||||
$overlay.on('keydown', function (e) {
|
||||
if ( e.key !== 'Tab' ) return;
|
||||
const focusables = $overlay.find('button, textarea').toArray()
|
||||
const focusables = $overlay.find('button, textarea, input:not([type="hidden"]), select, a[href]').toArray()
|
||||
.filter(el => ! el.disabled && el.offsetParent !== null);
|
||||
if ( focusables.length === 0 ) return;
|
||||
const first = focusables[0];
|
||||
@@ -456,6 +456,12 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// restores its position if it comes back.
|
||||
const deleteData = $overlay.find('.myapps-modal-delete-data').is(':checked');
|
||||
const removedIndex = self._apps.findIndex(a => a.name === appName);
|
||||
// Uninstalled from inside an open folder: where focus goes after.
|
||||
const fromGroupId = $el_window.find('.myapps-group-panel-grid .myapps-tile').toArray()
|
||||
.some(el => el.dataset.appName === appName) ? self._openGroupId : null;
|
||||
const groupMates = fromGroupId
|
||||
? (findGroupById(self._groups, fromGroupId)?.apps ?? []).filter(name => name !== appName)
|
||||
: [];
|
||||
const removedApp = removedIndex === -1 ? null : self._apps[removedIndex];
|
||||
// A running instance would be stranded: the tile is a headless
|
||||
// app's only switcher, so once it's gone a minimized window could
|
||||
@@ -463,6 +469,9 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// also consumes the app's URL entry if it owns one).
|
||||
$(`.window[data-app="${html_encode(appName)}"]`).close();
|
||||
self._invalidateInFlightLoads();
|
||||
// Until the revoke lands the server still lists the app as
|
||||
// installed, so loads started meanwhile leave it out themselves.
|
||||
self._pendingUninstalls.add(appName);
|
||||
self._setAppRemoved(appName, true);
|
||||
close({ restoreFocus: false });
|
||||
|
||||
@@ -494,9 +503,19 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
self.renderApps($el_window, { preservePage: true, instant: true });
|
||||
// The confirm button left with the modal; keep a keyboard user on
|
||||
// the grid, at the slot the app vacated.
|
||||
if ( slot !== -1 && (! document.activeElement || document.activeElement === document.body) ) {
|
||||
const tiles = $el_window.find('.myapps-page .myapps-tile').toArray();
|
||||
tiles[Math.min(slot, tiles.length - 1)]?.focus({ preventScroll: true });
|
||||
if ( ! document.activeElement || document.activeElement === document.body ) {
|
||||
if ( slot !== -1 ) {
|
||||
const tiles = $el_window.find('.myapps-page .myapps-tile').toArray();
|
||||
tiles[Math.min(slot, tiles.length - 1)]?.focus({ preventScroll: true });
|
||||
} else if ( fromGroupId ) {
|
||||
// The folder may still be open, closed, or dissolved
|
||||
// into the one app left in it.
|
||||
const target = $el_window.find('.myapps-group-panel-grid .myapps-tile')[0]
|
||||
?? $el_window.find(`.myapps-group-tile[data-group-id="${CSS.escape(fromGroupId)}"]`)[0]
|
||||
?? $el_window.find('.myapps-page .myapps-tile').toArray()
|
||||
.find(el => groupMates.includes(el.dataset.appName));
|
||||
target?.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
// FLIP the survivors from their old boxes into the new layout.
|
||||
const moved = [];
|
||||
@@ -546,6 +565,9 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
puter.perms.revokeApp(appUid, '*', { deleteData }).then(async (result) => {
|
||||
// revokeApp resolves (never rejects) with `error` set on failure.
|
||||
if ( result?.error ) throw result;
|
||||
// Loads started before now may have read the app as installed.
|
||||
self._invalidateInFlightLoads();
|
||||
self._pendingUninstalls.delete(appName);
|
||||
// Clearing the grants is only half of it. An app the user already
|
||||
// opened holds a token that authenticates against a session row,
|
||||
// and that row outlives the permission rows — so without this an
|
||||
@@ -567,6 +589,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
}
|
||||
}).catch(async err => {
|
||||
console.error('Failed to uninstall app:', err);
|
||||
self._pendingUninstalls.delete(appName);
|
||||
await removalSettled;
|
||||
self._invalidateInFlightLoads();
|
||||
// The uninstall didn't happen — take the name back off the
|
||||
@@ -693,6 +716,8 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
$overlay.on('click', '.myapps-add-back', () => showPane('options'));
|
||||
$(document).on('keydown.add-app-modal', function (e) {
|
||||
if ( e.key !== 'Escape' ) return;
|
||||
// Escape while composing (CJK input) cancels the composition only.
|
||||
if ( e.originalEvent?.isComposing || e.keyCode === 229 ) return;
|
||||
// Escape steps back out of the form before it closes the modal, so a
|
||||
// half-written request survives a mis-hit key.
|
||||
if ( currentPane() === 'request' ) showPane('options');
|
||||
@@ -917,6 +942,8 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// The last uninstalled-apps list a read returned, for loads whose read fails.
|
||||
_lastRemovedApps: null,
|
||||
_launchingApps: new Set(),
|
||||
// Apps whose uninstall was confirmed but hasn't landed on the server.
|
||||
_pendingUninstalls: new Set(),
|
||||
// A deep-link install mid-arrival ({ name, $el_window }) — its tile is
|
||||
// parked invisible until the intro's arrival beat (see
|
||||
// _spliceDeepLinkApp); and the session's landing-installed apps, kept
|
||||
@@ -1362,7 +1389,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// account dialog, the touch action sheet, or the phone drawer.
|
||||
if ( $('.dashboard-notifications-panel.open, .dashboard-dialog-overlay, .context-menu-modal-backdrop, .dashboard-sidebar.open').length ) return;
|
||||
|
||||
const $panelGrid = $el_window.find('.myapps-group-panel-grid');
|
||||
const $panelGrid = $el_window.find('.myapps-group-overlay:not([inert]) .myapps-group-panel-grid');
|
||||
const pageTiles = ($panelGrid.length
|
||||
? $panelGrid
|
||||
: $el_window.find('.myapps-page').eq(self._page)
|
||||
@@ -2237,6 +2264,8 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// removal below, so the tile a user reaches for the instant a folder
|
||||
// shuts would do nothing.
|
||||
$overlay.css('pointer-events', 'none');
|
||||
// Nor may its tiles take focus (Tab, the arrow keys) on the way out.
|
||||
$overlay.attr('inert', '');
|
||||
|
||||
// Back into the tile it grew out of; if that tile is gone (the folder
|
||||
// dissolved, the page flipped) the card simply recedes where it is.
|
||||
@@ -2334,14 +2363,32 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// boundary so their stale snapshot can't replay over it (see
|
||||
// _resolveGroups).
|
||||
this._groupsSavedAtSeq = this._loadSeq || 0;
|
||||
try {
|
||||
const p = puter.kv.set(APP_GROUPS_KV_KEY, JSON.stringify(groups));
|
||||
if ( p && typeof p.catch === 'function' ) {
|
||||
p.catch(err => console.error('Failed to save app folders:', err));
|
||||
this._persistLatest(APP_GROUPS_KV_KEY, JSON.stringify(groups), 'Failed to save app folders:');
|
||||
},
|
||||
|
||||
// Saves `value` under `key` one write at a time, sending only the
|
||||
// newest value once the write before it lands: two writes of a key in
|
||||
// flight together (an eject's save, then the drop's) can land in
|
||||
// either order, leaving the older layout stored.
|
||||
_persistLatest (key, value, failureMessage) {
|
||||
this._kvWrites ??= new Map();
|
||||
let slot = this._kvWrites.get(key);
|
||||
if ( ! slot ) this._kvWrites.set(key, slot = { pending: undefined, running: false });
|
||||
slot.pending = value;
|
||||
if ( slot.running ) return;
|
||||
slot.running = true;
|
||||
(async () => {
|
||||
while ( slot.pending !== undefined ) {
|
||||
const next = slot.pending;
|
||||
slot.pending = undefined;
|
||||
try {
|
||||
await puter.kv.set(key, next);
|
||||
} catch ( err ) {
|
||||
console.error(failureMessage, err);
|
||||
}
|
||||
}
|
||||
} catch ( err ) {
|
||||
console.error('Failed to save app folders:', err);
|
||||
}
|
||||
slot.running = false;
|
||||
})();
|
||||
},
|
||||
|
||||
// -- Drag-to-reorder --
|
||||
@@ -3269,14 +3316,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
// boundary so their stale snapshot can't replay over it (see
|
||||
// _resolveOrderNames).
|
||||
this._orderSavedAtSeq = this._loadSeq || 0;
|
||||
try {
|
||||
const p = puter.kv.set(APPS_ORDER_KV_KEY, JSON.stringify(names));
|
||||
if ( p && typeof p.catch === 'function' ) {
|
||||
p.catch(err => console.error('Failed to save app order:', err));
|
||||
}
|
||||
} catch ( err ) {
|
||||
console.error('Failed to save app order:', err);
|
||||
}
|
||||
this._persistLatest(APPS_ORDER_KV_KEY, JSON.stringify(names), 'Failed to save app order:');
|
||||
},
|
||||
|
||||
loadApps ($el_window) {
|
||||
@@ -3444,7 +3484,7 @@ export function createAppBrowser ({ editable = true, onLaunch, actions = {}, gue
|
||||
|
||||
// Append installed apps that aren't already in the list
|
||||
for ( const app of installedApps ) {
|
||||
if ( seen.has(app.name) ) continue;
|
||||
if ( seen.has(app.name) || this._pendingUninstalls.has(app.name) ) continue;
|
||||
seen.add(app.name);
|
||||
merged.push(app);
|
||||
}
|
||||
|
||||
@@ -68,6 +68,86 @@ async function mount (options = {}) {
|
||||
}
|
||||
|
||||
describe('shared app browser', () => {
|
||||
it('keeps an app off the grid while its uninstall is still on its way to the server', async () => {
|
||||
const actions = { showAlert: vi.fn(), revokeAppSessions: vi.fn(async () => {}) };
|
||||
await mount({ editable: true, actions });
|
||||
let finishRevoke;
|
||||
puter.perms = { revokeApp: vi.fn(() => new Promise(resolve => { finishRevoke = resolve; })) };
|
||||
// The app's windows are closed first; the test has none.
|
||||
$.fn.close ??= function () { return this; };
|
||||
window.matchMedia = () => ({ matches: true });
|
||||
browser._setReorderMode($root, true);
|
||||
$('.myapps-tile[data-app-name="editor"] .myapps-tile-remove').trigger('click');
|
||||
$('.myapps-modal-confirm').trigger('click');
|
||||
expect(puter.perms.revokeApp).toHaveBeenCalled();
|
||||
|
||||
// A refresh before the revoke lands still lists the app as installed.
|
||||
await browser.loadApps($root);
|
||||
expect(browser._apps.map(app => app.name)).not.toContain('editor');
|
||||
|
||||
installed = installed.filter(app => app.name !== 'editor');
|
||||
finishRevoke({});
|
||||
await vi.waitFor(() => expect(browser._pendingUninstalls.size).toBe(0));
|
||||
await browser.loadApps($root);
|
||||
expect(browser._apps.map(app => app.name)).not.toContain('editor');
|
||||
expect(actions.showAlert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('saves one layout at a time, sending only the newest once the last write lands', async () => {
|
||||
await mount({ editable: true });
|
||||
const writes = [];
|
||||
puter.kv.set = vi.fn((key, value) => new Promise(resolve => writes.push({ key, value, resolve })));
|
||||
const orderWrites = () => writes.filter(w => w.key === APPS_ORDER_KV_KEY);
|
||||
|
||||
browser._apps = [{ name: 'a' }, { name: 'b' }];
|
||||
browser.saveOrder();
|
||||
browser._apps = [{ name: 'b' }, { name: 'a' }];
|
||||
browser.saveOrder();
|
||||
browser._apps = [{ name: 'a' }, { name: 'b' }, { name: 'c' }];
|
||||
browser.saveOrder();
|
||||
expect(orderWrites()).toHaveLength(1);
|
||||
|
||||
orderWrites()[0].resolve();
|
||||
await vi.waitFor(() => expect(orderWrites()).toHaveLength(2));
|
||||
expect(orderWrites()[1].value).toBe(JSON.stringify(browser._savedOrderNames));
|
||||
expect(orderWrites()[1].value).not.toBe(orderWrites()[0].value);
|
||||
orderWrites()[1].resolve();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(orderWrites()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('leaves the app request form open on an Escape that ends an IME composition', async () => {
|
||||
await mount({ editable: true });
|
||||
$('.myapps-add-tile').trigger('click');
|
||||
$('.myapps-add-option[data-add-option="request"]').trigger('click');
|
||||
const pane = () => $('.myapps-add-pane:not([hidden])').attr('data-pane');
|
||||
expect(pane()).toBe('request');
|
||||
|
||||
$('.myapps-add-message')[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', isComposing: true, bubbles: true }));
|
||||
expect(pane()).toBe('request');
|
||||
$('.myapps-add-message')[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
expect(pane()).toBe('options');
|
||||
$(document).off('keydown.add-app-modal');
|
||||
});
|
||||
|
||||
it('lets Tab reach the delete-data option in the Uninstall dialog', async () => {
|
||||
// jsdom lays nothing out; the focus trap skips elements with no offsetParent.
|
||||
vi.spyOn(HTMLElement.prototype, 'offsetParent', 'get').mockReturnValue(document.body);
|
||||
await mount({ editable: true });
|
||||
browser._setReorderMode($root, true);
|
||||
$('.myapps-tile[data-app-name="editor"] .myapps-tile-remove').trigger('click');
|
||||
const $overlay = $('.myapps-modal-overlay');
|
||||
expect(document.activeElement.classList.contains('myapps-modal-cancel')).toBe(true);
|
||||
|
||||
// Tab from the last control wraps to the first, the checkbox.
|
||||
$overlay.find('.myapps-modal-confirm')[0].focus();
|
||||
$overlay.trigger($.Event('keydown', { key: 'Tab', shiftKey: false }));
|
||||
expect(document.activeElement.classList.contains('myapps-modal-delete-data')).toBe(true);
|
||||
// Shift+Tab from it wraps back to the last.
|
||||
$overlay.trigger($.Event('keydown', { key: 'Tab', shiftKey: true }));
|
||||
expect(document.activeElement.classList.contains('myapps-modal-confirm')).toBe(true);
|
||||
});
|
||||
|
||||
it('uses saved order, folders, and removed recommendations in read-only mode', async () => {
|
||||
await mount();
|
||||
expect(browser._apps.map(app => app.name)).toEqual(['notes', 'sheet', 'editor']);
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('TabApps.beginDeepLinkLaunch', () => {
|
||||
});
|
||||
|
||||
describe('TabApps cancelling a drag out of a folder', () => {
|
||||
it('puts the folder and the order back as they were', () => {
|
||||
it('puts the folder and the order back as they were', async () => {
|
||||
document.body.innerHTML = '<div class="window"><div class="dashboard-section-apps active"><div class="myapps-container"><div class="myapps-page"><div class="myapps-tile" data-app-name="a"></div></div></div></div></div>';
|
||||
window.puter = { kv: { set: vi.fn(async () => {}), get: vi.fn(async () => null) } };
|
||||
TabApps._groupsLoaded = true;
|
||||
@@ -91,7 +91,9 @@ describe('TabApps cancelling a drag out of a folder', () => {
|
||||
TabApps._endDrag(false);
|
||||
|
||||
expect(TabApps._groups).toEqual([{ id: 'g1', name: 'Work', apps: ['a', 'b'] }]);
|
||||
expect(JSON.parse(window.puter.kv.set.mock.calls.at(-2)[1])).toEqual([{ id: 'g1', name: 'Work', apps: ['a', 'b'] }]);
|
||||
// The restore is written once the eject's own write lands.
|
||||
const lastSaved = key => JSON.parse(window.puter.kv.set.mock.calls.filter(([k]) => k === key).at(-1)[1]);
|
||||
await vi.waitFor(() => expect(lastSaved('dashboard_app_groups')).toEqual([{ id: 'g1', name: 'Work', apps: ['a', 'b'] }]));
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,6 +37,7 @@ import UIItemPropertiesModal from './UIItemPropertiesModal.js';
|
||||
import UIShareModal from './UIShareModal.js';
|
||||
import { openPublishWebsiteDialog, openPublishWorkerDialog } from './UIPublishDialogs.js';
|
||||
import { dedupedName } from '../../helpers/dedupedName.js';
|
||||
import { runLimited } from '../../helpers/runLimited.js';
|
||||
import { compareEntries, compareNames } from './sortEntries.js';
|
||||
import { middleTruncate } from './middleTruncate.js';
|
||||
import { resolveTypedPath } from './typedPath.js';
|
||||
@@ -54,6 +55,14 @@ import { paintAvatars } from '../../helpers/profilePictures.js';
|
||||
|
||||
const { html_encode, SelectionArea } = window;
|
||||
|
||||
// Permanent deletes in flight at once: a browser's connections to one host.
|
||||
const DELETE_CONCURRENCY = 6;
|
||||
|
||||
// The "New" menu's stand-ins for window.create_file, one per create in
|
||||
// flight (newest last), and the function they stand in for.
|
||||
const createFileInterceptors = [];
|
||||
let realCreateFile = null;
|
||||
|
||||
/**
|
||||
* `p` with the folder `from` (itself, or anything under it) moved to `to`;
|
||||
* any other path, or a non-string, comes back as it was.
|
||||
@@ -1242,8 +1251,9 @@ const TabFiles = {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Arrow keys, Home/End and PageUp/PageDown - Navigate items
|
||||
if ( e.which >= 33 && e.which <= 40 ) {
|
||||
// Arrow keys, Home/End and PageUp/PageDown - Navigate items. Not
|
||||
// with Alt or Cmd: those are the browser's (Alt+Left is Back).
|
||||
if ( e.which >= 33 && e.which <= 40 && ! e.altKey && ! e.metaKey ) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
@@ -1907,9 +1917,9 @@ const TabFiles = {
|
||||
if ( confirmed !== 'delete' ) return;
|
||||
// The phone selection bar acts on rows that are going away.
|
||||
this.$el_window.find('.files-selection-actions').removeClass('visible');
|
||||
for ( const row of list ) {
|
||||
await window.delete_item(row);
|
||||
}
|
||||
// A few at a time rather than one after another: a few hundred items
|
||||
// took a round trip each. delete_item reports its own failures.
|
||||
await runLimited(list, DELETE_CONCURRENCY, row => window.delete_item(row));
|
||||
await window.refresh_trash_state();
|
||||
},
|
||||
|
||||
@@ -2383,11 +2393,19 @@ const TabFiles = {
|
||||
};
|
||||
|
||||
if ( isList ) {
|
||||
for ( const el of names ) {
|
||||
// 8px padding on each side; an auto-width column shows the
|
||||
// full name, clipped by CSS.
|
||||
write(el, nameWidth ? truncateFilenameToWidth(fullNameOf(el), nameWidth - 16, font) : fullNameOf(el));
|
||||
}
|
||||
// The name's padding (8px a side) takes room from a set width. An
|
||||
// auto-width column fills the row, so its room is read off the
|
||||
// name's wrapper, less the wrapper's padding: all reads before any
|
||||
// write, so the writes don't force a layout each.
|
||||
const paddingOf = s => (parseFloat(s.paddingLeft) || 0) + (parseFloat(s.paddingRight) || 0);
|
||||
const padding = paddingOf(style);
|
||||
const wrapperPadding = nameWidth ? 0 : paddingOf(getComputedStyle(names[0].parentElement));
|
||||
const rooms = nameWidth ? null : names.map(el => el.parentElement.clientWidth - wrapperPadding);
|
||||
names.forEach((el, i) => {
|
||||
const room = (nameWidth || rooms[i]) - padding;
|
||||
// A listing that isn't laid out yet (hidden tab) has no room to fit to.
|
||||
write(el, room > 0 ? truncateFilenameToWidth(fullNameOf(el), room, font) : fullNameOf(el));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3312,6 +3330,9 @@ const TabFiles = {
|
||||
// the directories sidebar is hidden — Home carries a row for each.
|
||||
this.renderPlaceRows();
|
||||
|
||||
// Something that ran while the listing loaded (a restore finishing,
|
||||
// a failed mkdir) may have found the pane empty and said so.
|
||||
$files.find('.files-empty-notice').remove();
|
||||
if ( directoryContents.length === 0 ) {
|
||||
this.renderEmptyPlaceholderIfNeeded();
|
||||
this.updateFooterStats();
|
||||
@@ -4433,11 +4454,14 @@ const TabFiles = {
|
||||
const metadata = metadataStr ? JSON.parse(metadataStr) : {};
|
||||
|
||||
// Only a direct child of Trash carries restore metadata.
|
||||
const name = $(el_item).attr('data-name') || '';
|
||||
if ( path.dirname($(el_item).attr('data-path') || '') !== window.trash_path ) {
|
||||
throw new Error('Cannot restore: only top-level Trash items can be restored');
|
||||
throw new Error(i18n('restore_only_trash_items', { name }, false));
|
||||
}
|
||||
// An item an app or the API moved into the Trash has no record of
|
||||
// where it came from.
|
||||
if ( ! metadata.original_path ) {
|
||||
throw new Error('Cannot restore: original path not found in metadata');
|
||||
throw new Error(i18n('restore_location_unknown', { name }, false));
|
||||
}
|
||||
|
||||
const destPath = path.dirname(metadata.original_path);
|
||||
@@ -5370,10 +5394,14 @@ const TabFiles = {
|
||||
return async () => {
|
||||
$('.context-menu').remove();
|
||||
|
||||
// Where the user was, so an upload that lands after
|
||||
// they've moved on neither pulls them back nor draws
|
||||
// its row into another folder's listing.
|
||||
const pathAtClick = _this.currentPath;
|
||||
|
||||
// Temporarily intercept create_file to capture the upload promise
|
||||
let uploadPromise = null;
|
||||
const origCreateFile = window.create_file;
|
||||
window.create_file = (options) => {
|
||||
const createFile = (options) => {
|
||||
// Counted from here, not from the click: Web Link
|
||||
// waits on a prompt first, and other items added
|
||||
// to the folder meanwhile must still show up.
|
||||
@@ -5384,6 +5412,12 @@ const TabFiles = {
|
||||
// a caller that awaits this.
|
||||
return uploadPromise.catch(() => undefined);
|
||||
};
|
||||
// Creates can overlap. Each one's interceptor stays
|
||||
// installed until it finishes, the newest on top, and
|
||||
// the real create_file comes back once none is left.
|
||||
if ( createFileInterceptors.length === 0 ) realCreateFile = window.create_file;
|
||||
createFileInterceptors.push(createFile);
|
||||
window.create_file = createFile;
|
||||
|
||||
try {
|
||||
await originalOnClick();
|
||||
@@ -5401,7 +5435,10 @@ const TabFiles = {
|
||||
operation: 'create_file',
|
||||
data: $('<div>').attr({ 'data-uid': result.uid, 'data-path': result.path }),
|
||||
});
|
||||
if ( targetPath === _this.currentPath ) {
|
||||
// Not mid-way to another folder (currentPath
|
||||
// only moves once its listing arrives).
|
||||
const settled = ! _this.loadingFolder;
|
||||
if ( settled && targetPath === _this.currentPath ) {
|
||||
// Remove empty-directory placeholder if present
|
||||
_this.$el_window.find('.files-tab .files > div:not(.item):not(.place-row):not(.tabfiles-selection-area)').remove();
|
||||
// Add the new file incrementally
|
||||
@@ -5412,11 +5449,15 @@ const TabFiles = {
|
||||
_this.applyColumnWidths();
|
||||
_this.updateFooterStats();
|
||||
}
|
||||
} else {
|
||||
} else if ( settled && _this.currentPath === pathAtClick ) {
|
||||
// Same navigate-to-target treatment as New
|
||||
// Folder above.
|
||||
_this.pushNavHistory(targetPath);
|
||||
await _this.renderDirectory(targetPath, { consistency: 'strong' });
|
||||
} else {
|
||||
// The user went elsewhere meanwhile; the
|
||||
// file is there when they come back.
|
||||
return;
|
||||
}
|
||||
const $newRow = _this.$el_window.find(`.files-tab .files .item[data-uid='${result.uid}']`);
|
||||
if ( $newRow.length > 0 ) {
|
||||
@@ -5427,7 +5468,8 @@ const TabFiles = {
|
||||
} catch ( err ) {
|
||||
UIAlert(err?.message || i18n('error_unknown_cause', [], false));
|
||||
} finally {
|
||||
window.create_file = origCreateFile;
|
||||
createFileInterceptors.splice(createFileInterceptors.indexOf(createFile), 1);
|
||||
window.create_file = createFileInterceptors.at(-1) ?? realCreateFile;
|
||||
if ( uploadPromise ) _this.doneCreating();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -116,6 +116,131 @@ describe('TabFiles emptying the Trash', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles restoring from the Trash', () => {
|
||||
beforeEach(() => {
|
||||
window.trash_path = TRASH;
|
||||
window.byte_format = bytes => `${bytes} B`;
|
||||
window.refresh_trash_state = vi.fn(async () => {});
|
||||
window.puter = { fs: { move: vi.fn(async () => ({})) } };
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('says in the user\'s language when an item has no record of where it came from', async () => {
|
||||
const { default: UIAlert } = await import('../UIAlert.js');
|
||||
UIAlert.mockClear();
|
||||
mountListing(['uid-1']);
|
||||
const row = $('.files .row')[0];
|
||||
row.setAttribute('data-name', 'notes.txt');
|
||||
row.setAttribute('data-uid', 'uid-1');
|
||||
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
await TabFiles.restoreRows([row]);
|
||||
|
||||
expect(puter.fs.move).not.toHaveBeenCalled();
|
||||
expect(UIAlert).toHaveBeenCalledWith('“notes.txt” can’t be restored because where it was deleted from isn’t known.');
|
||||
expect($('.files .row')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles New menu creates', () => {
|
||||
const menuItem = (pattern, folder) => TabFiles.generateFolderContextMenu(folder)
|
||||
.find(item => item && item.items).items.find(item => item && pattern.test(item.html));
|
||||
let uploads;
|
||||
|
||||
beforeEach(() => {
|
||||
mountListing([], '/alice/Documents');
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = TRASH;
|
||||
window.shared_path = '/alice/Shared';
|
||||
window.file_templates = [];
|
||||
window.sites = [];
|
||||
window.actions_history = [];
|
||||
window.activate_item_name_editor = vi.fn();
|
||||
vi.spyOn(TabFiles, 'pushNavHistory').mockImplementation(() => {});
|
||||
uploads = [];
|
||||
window.puter = { fs: { upload: vi.fn((file, dirname) => new Promise(resolve => {
|
||||
uploads.push(() => resolve({ uid: `u${uploads.length}`, name: file.name, path: `${dirname}/${file.name}` }));
|
||||
})) } };
|
||||
vi.spyOn(TabFiles, 'acceptsNewItemsHere').mockReturnValue(true);
|
||||
vi.spyOn(TabFiles, 'acceptsNewItems').mockReturnValue(true);
|
||||
vi.spyOn(TabFiles, 'renderItem').mockResolvedValue();
|
||||
TabFiles.loadingFolder = false;
|
||||
TabFiles._creatingItem = 0;
|
||||
TabFiles.trashedNames ??= new Map();
|
||||
TabFiles.deferredAdds ??= [];
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('puts the real create_file back when two overlap, whichever finishes first', async () => {
|
||||
const real = vi.fn();
|
||||
window.create_file = real;
|
||||
|
||||
const first = menuItem(/text_document|Text/).onClick();
|
||||
const second = menuItem(/html_document|HTML/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(uploads).toHaveLength(2);
|
||||
uploads[0]();
|
||||
await first;
|
||||
uploads[1]();
|
||||
await second;
|
||||
|
||||
expect(window.create_file).toBe(real);
|
||||
expect(TabFiles._creatingItem).toBe(0);
|
||||
|
||||
const third = menuItem(/text_document|Text/).onClick();
|
||||
const fourth = menuItem(/html_document|HTML/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
uploads[3]();
|
||||
await fourth;
|
||||
uploads[2]();
|
||||
await third;
|
||||
|
||||
expect(window.create_file).toBe(real);
|
||||
expect(TabFiles._creatingItem).toBe(0);
|
||||
});
|
||||
|
||||
it('leaves a listing the user moved to alone when the upload lands after', async () => {
|
||||
window.create_file = vi.fn();
|
||||
vi.spyOn(TabFiles, 'renderDirectory').mockResolvedValue();
|
||||
const created = menuItem(/text_document|Text/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
// The user opened Pictures; its listing is still loading.
|
||||
TabFiles.loadingFolder = true;
|
||||
uploads[0]();
|
||||
await created;
|
||||
expect(TabFiles.renderItem).not.toHaveBeenCalled();
|
||||
expect(TabFiles.renderDirectory).not.toHaveBeenCalled();
|
||||
expect(window.activate_item_name_editor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not pull the user back once they are in another folder', async () => {
|
||||
window.create_file = vi.fn();
|
||||
vi.spyOn(TabFiles, 'renderDirectory').mockResolvedValue();
|
||||
const created = menuItem(/text_document|Text/).onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
TabFiles.currentPath = '/alice/Pictures';
|
||||
uploads[0]();
|
||||
await created;
|
||||
expect(TabFiles.renderDirectory).not.toHaveBeenCalled();
|
||||
expect(TabFiles.renderItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still goes to the folder whose menu made the file', async () => {
|
||||
window.create_file = vi.fn();
|
||||
vi.spyOn(TabFiles, 'renderDirectory').mockResolvedValue();
|
||||
const created = menuItem(/text_document|Text/, '/alice/Videos').onClick();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
uploads[0]();
|
||||
await created;
|
||||
expect(TabFiles.renderDirectory).toHaveBeenCalledWith('/alice/Videos', { consistency: 'strong' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('failedUploadsMessage', () => {
|
||||
it('puts each failed item on its own line', () => {
|
||||
const message = failedUploadsMessage({ failedItems: [
|
||||
@@ -1086,6 +1211,57 @@ describe('TabFiles names in a narrow listing', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles names in an auto-width name column', () => {
|
||||
const mountNames = (names) => {
|
||||
document.body.innerHTML = `
|
||||
<div class="window"><div class="files-tab">
|
||||
<div class="header"><div class="columns"></div></div>
|
||||
<div class="files files-list-view">${names.map(name => `
|
||||
<div class="row item" data-name="${name}">
|
||||
<div class="item-name-wrapper" style="padding: 0 40px 0 0"><pre class="item-name" style="padding: 0 8px"></pre></div>
|
||||
</div>`).join('')}
|
||||
</div>
|
||||
</div></div>`;
|
||||
TabFiles.$el_window = $('.window');
|
||||
TabFiles.currentView = 'list';
|
||||
TabFiles.appliedColumnWidths = { name: null, sharedBy: 160, size: 60, modified: 80 };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// 10px a character; jsdom has no canvas.
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ measureText: text => ({ width: text.length * 10 }) });
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('cut a long name in the middle to the room its wrapper leaves, keeping the end', () => {
|
||||
const long = `${'x'.repeat(60)} (1).txt`;
|
||||
mountNames([long, 'short.txt']);
|
||||
// 256px wrapper, less its 40px and the name's 16px of padding: 200px, 20 characters.
|
||||
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(256);
|
||||
|
||||
TabFiles.fitItemNames($('.files .item-name'));
|
||||
|
||||
const [$long, $short] = $('.files .item-name').toArray().map(el => $(el));
|
||||
expect($long.text().length).toBeLessThanOrEqual(20);
|
||||
expect($long.text().length).toBeGreaterThan(15);
|
||||
expect($long.text()).toMatch(/^x+…x* \(1\)\.txt$/);
|
||||
expect($long.attr('title')).toBe(long);
|
||||
expect($short.text()).toBe('short.txt');
|
||||
expect($short.attr('title') ?? '').toBe('');
|
||||
});
|
||||
|
||||
it('show the full name while the listing has no width yet', () => {
|
||||
const long = 'y'.repeat(80);
|
||||
mountNames([long]);
|
||||
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(0);
|
||||
|
||||
TabFiles.fitItemNames($('.files .item-name'));
|
||||
|
||||
expect($('.files .item-name').text()).toBe(long);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles uploads', () => {
|
||||
beforeEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -1369,6 +1545,22 @@ describe('TabFiles keyboard', () => {
|
||||
expect(selected()).toEqual(['/alice/Documents/a.txt']);
|
||||
});
|
||||
|
||||
it('leaves Alt and Cmd arrows to the browser', () => {
|
||||
mountKeyboard(['a.txt', 'b.txt']);
|
||||
$('.files .row').first().addClass('selected');
|
||||
|
||||
const back = new KeyboardEvent('keydown', { key: 'ArrowLeft', which: 37, keyCode: 37, altKey: true, bubbles: true, cancelable: true });
|
||||
document.body.dispatchEvent(back);
|
||||
const down = new KeyboardEvent('keydown', { key: 'ArrowDown', which: 40, keyCode: 40, metaKey: true, bubbles: true, cancelable: true });
|
||||
document.body.dispatchEvent(down);
|
||||
|
||||
expect(back.defaultPrevented).toBe(false);
|
||||
expect(down.defaultPrevented).toBe(false);
|
||||
expect(selected()).toEqual(['/alice/Documents/a.txt']);
|
||||
press(document.body, 'ArrowDown', { which: 40, keyCode: 40 });
|
||||
expect(selected()).toEqual(['/alice/Documents/b.txt']);
|
||||
});
|
||||
|
||||
it('takes a space typed into a name as part of it', () => {
|
||||
mountKeyboard(['my notes.txt', 'my zebra.txt']);
|
||||
for ( const key of ['m', 'y', ' ', 'z'] ) press(document.body, key, { which: key.toUpperCase().charCodeAt(0) });
|
||||
|
||||
@@ -168,15 +168,19 @@ function buildUsageHTML() {
|
||||
// what the badge carries: a date says when, only a countdown says how long
|
||||
// there is to decide. Returns null when the subscription carries no end date,
|
||||
// so callers fall back to unqualified "Free trial" wording.
|
||||
function formatTrialEnd(trialEndsAt) {
|
||||
export function formatTrialEnd(trialEndsAt, now = Date.now()) {
|
||||
if (!Number.isFinite(trialEndsAt)) return null;
|
||||
const date = new Date(trialEndsAt);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
// Rounded up, so a trial with any time on it never reads "0 days left"
|
||||
// before the day it actually converts.
|
||||
// Calendar days in the user's time zone, so the countdown agrees with the
|
||||
// date beside it: a trial ending this afternoon ends "today", and one
|
||||
// ending tomorrow morning has one day left. Rounded, for the 23- and
|
||||
// 25-hour days daylight saving makes.
|
||||
const startOfDay = (d) =>
|
||||
new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const days = Math.max(
|
||||
0,
|
||||
Math.ceil((date.getTime() - Date.now()) / 86400000),
|
||||
Math.round((startOfDay(date) - startOfDay(new Date(now))) / 86400000),
|
||||
);
|
||||
// In the dashboard's language, which the sentences around it are in.
|
||||
const locale = intlLocale(window.locale);
|
||||
|
||||
@@ -31,7 +31,7 @@ globalThis.i18n = key => key;
|
||||
window.icons = {};
|
||||
window.launch_apps = { recent: [] };
|
||||
|
||||
const { default: TabHome } = await import('./TabHome.js');
|
||||
const { default: TabHome, formatTrialEnd } = await import('./TabHome.js');
|
||||
const { openAppInNewTab } = await import('../../helpers/dashboardAppLaunch.js');
|
||||
|
||||
describe('TabHome recently used', () => {
|
||||
@@ -96,3 +96,25 @@ describe('TabHome recent app clicks', () => {
|
||||
expect(openAppInNewTab).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatTrialEnd', () => {
|
||||
const at = (day, hour) => new Date(2026, 10, day, hour).getTime();
|
||||
|
||||
it('counts calendar days, so the countdown agrees with the date', () => {
|
||||
// Ends at 3pm today: today, not "1 day left".
|
||||
expect(formatTrialEnd(at(8, 15), at(8, 9)).days).toBe(0);
|
||||
// Ends tomorrow at 11am: one day, not two.
|
||||
expect(formatTrialEnd(at(9, 11), at(8, 9)).days).toBe(1);
|
||||
expect(formatTrialEnd(at(9, 11), at(8, 23)).days).toBe(1);
|
||||
expect(formatTrialEnd(at(15, 0), at(8, 23)).days).toBe(7);
|
||||
});
|
||||
|
||||
it('reads an end that has passed as today', () => {
|
||||
expect(formatTrialEnd(at(7, 12), at(8, 9)).days).toBe(0);
|
||||
});
|
||||
|
||||
it('has nothing to say without an end date', () => {
|
||||
expect(formatTrialEnd(undefined)).toBeNull();
|
||||
expect(formatTrialEnd(NaN)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -49,7 +49,9 @@ const ICONS = {
|
||||
puter: svg('<rect x="3" y="3" width="18" height="18" rx="4"/><path d="M8 12h8M12 8v8"/>'),
|
||||
};
|
||||
|
||||
const PLATFORM_KEYS = { web: 'push_platform_web', ios: 'push_platform_ios', android: 'push_platform_android' };
|
||||
// `webpush` is Puter's own Web Push (see webPushClient.js); both are browsers.
|
||||
const PLATFORM_KEYS = { web: 'push_platform_web', webpush: 'push_platform_web', ios: 'push_platform_ios', android: 'push_platform_android' };
|
||||
const BROWSER_PLATFORMS = new Set(['web', 'webpush']);
|
||||
|
||||
/** @param {{ pushEnabled?: boolean }|undefined} params - `window.gui_params` */
|
||||
export const notificationsTabEnabled = (params) => params?.pushEnabled === true;
|
||||
@@ -106,7 +108,7 @@ export const deviceCardHtml = (device, now) => {
|
||||
? i18n('push_device_last_seen', { time: formatRelativeTime(seenAt, now, locale) })
|
||||
: '';
|
||||
return card({
|
||||
icon: device.platform === 'web' ? ICONS.laptop : ICONS.phone,
|
||||
icon: BROWSER_PLATFORMS.has(device.platform) ? ICONS.laptop : ICONS.phone,
|
||||
title: html_encode(deviceName(device)),
|
||||
badge: device.current ? i18n('push_this_browser') : '',
|
||||
detail: [platform, seen].filter(Boolean).join(' · '),
|
||||
@@ -230,11 +232,18 @@ const TabNotifications = {
|
||||
? devices.map(device => deviceCardHtml(device, now)).join('')
|
||||
: emptyHtml('push_devices_empty'));
|
||||
};
|
||||
// Only the newest listing draws, and a local removal outdates any
|
||||
// listing still in flight: it may predate the removal.
|
||||
let devicesSeq = 0;
|
||||
const refreshDevices = async () => {
|
||||
const seq = ++devicesSeq;
|
||||
try {
|
||||
devices = await listPushDevices();
|
||||
const listed = await listPushDevices();
|
||||
if ( seq !== devicesSeq ) return;
|
||||
devices = listed;
|
||||
renderDevices();
|
||||
} catch ( e ) {
|
||||
if ( seq !== devicesSeq ) return;
|
||||
console.warn('[push] device list failed', e);
|
||||
$section.find('.push-devices-list').html(emptyHtml(loadFailedKey(e)));
|
||||
}
|
||||
@@ -245,11 +254,16 @@ const TabNotifications = {
|
||||
? apps.map(appCardHtml).join('')
|
||||
: emptyHtml('push_apps_empty'));
|
||||
};
|
||||
let appsSeq = 0;
|
||||
const refreshApps = async () => {
|
||||
const seq = ++appsSeq;
|
||||
try {
|
||||
apps = await listPushApps();
|
||||
const listed = await listPushApps();
|
||||
if ( seq !== appsSeq ) return;
|
||||
apps = listed;
|
||||
renderApps();
|
||||
} catch ( e ) {
|
||||
if ( seq !== appsSeq ) return;
|
||||
console.warn('[push] app list failed', e);
|
||||
$section.find('.push-apps-list').html(emptyHtml(loadFailedKey(e)));
|
||||
}
|
||||
@@ -257,12 +271,15 @@ const TabNotifications = {
|
||||
|
||||
const refreshPreference = async () => {
|
||||
const $toggle = $section.find('.push-puter-toggle');
|
||||
const $hint = $section.find('.push-puter-card .dashboard-settings-card-info > span');
|
||||
try {
|
||||
$toggle.prop('checked', await getPuterPushPreference()).prop('disabled', false);
|
||||
// A failed earlier read replaced the hint.
|
||||
$hint.html(i18n('push_puter_notifications_hint'));
|
||||
} catch ( e ) {
|
||||
console.warn('[push] preference read failed', e);
|
||||
$toggle.prop('checked', false).prop('disabled', true);
|
||||
$section.find('.push-puter-card .dashboard-settings-card-info > span').html(i18n(loadFailedKey(e)));
|
||||
$hint.html(i18n(loadFailedKey(e)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -362,13 +379,21 @@ const TabNotifications = {
|
||||
if ( confirmed !== true ) return;
|
||||
// disable() drops the token and record; the DELETE covers a lost record.
|
||||
const client = device.current ? getPushClient() : null;
|
||||
let disabled = false;
|
||||
try {
|
||||
if ( client ) await client.disable();
|
||||
if ( client ) {
|
||||
await client.disable();
|
||||
disabled = true;
|
||||
// Push is off here even if the DELETE fails; without the
|
||||
// opt-out the next load would turn it back on.
|
||||
setBrowserPushOptOut(window.user?.uuid, true);
|
||||
}
|
||||
await removePushDevice(uid);
|
||||
} catch ( e ) {
|
||||
if ( e?.status !== 404 || e?.code === PUSH_UNAVAILABLE ) {
|
||||
console.warn('[push] device removal failed', e);
|
||||
showError('push_device_remove_failed', $el_window);
|
||||
if ( disabled ) refreshBrowser();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -377,6 +402,7 @@ const TabNotifications = {
|
||||
await Promise.all([refreshBrowser(), refreshDevices()]);
|
||||
return;
|
||||
}
|
||||
devicesSeq++;
|
||||
devices = devices.filter(d => d.uid !== uid);
|
||||
renderDevices();
|
||||
if ( device.current ) refreshBrowser();
|
||||
@@ -393,6 +419,7 @@ const TabNotifications = {
|
||||
showError('push_app_turn_off_failed', $el_window);
|
||||
return;
|
||||
}
|
||||
appsSeq++;
|
||||
apps = apps.filter(app => app.uid !== appUid);
|
||||
renderApps();
|
||||
});
|
||||
|
||||
@@ -412,6 +412,26 @@ describe('Puter notifications', () => {
|
||||
expect($('.push-puter-card').text()).toContain('push_load_failed');
|
||||
});
|
||||
|
||||
it('puts the hint back once a later visit reads the preference', async () => {
|
||||
serve({
|
||||
'GET /push/devices': { devices: [] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': () => reply(500, {}),
|
||||
});
|
||||
await open();
|
||||
serve({
|
||||
'GET /push/devices': { devices: [] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
});
|
||||
await tab.onActivate($('.win'));
|
||||
await settle();
|
||||
|
||||
expect($('.push-puter-toggle').prop('disabled')).toBe(false);
|
||||
expect($('.push-puter-card').text()).toContain('push_puter_notifications_hint');
|
||||
expect($('.push-puter-card').text()).not.toContain('push_load_failed');
|
||||
});
|
||||
|
||||
it('puts the switch back when the save fails', async () => {
|
||||
serve({
|
||||
'GET /push/devices': { devices: [] },
|
||||
@@ -471,6 +491,21 @@ describe('your devices', () => {
|
||||
expect($cards.eq(2).find('strong').text()).toBe('push_device_unknown');
|
||||
});
|
||||
|
||||
it('labels a browser on Puter\'s own Web Push as a browser', async () => {
|
||||
serve({
|
||||
'GET /push/devices': { devices: [device({ uid: 'a', platform: 'webpush' }), device({ uid: 'b', platform: 'ios' })] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
});
|
||||
await open();
|
||||
|
||||
const $cards = $('.push-device-card');
|
||||
expect($cards.eq(0).find('.dashboard-settings-card-info > span').text()).toContain('push_platform_web');
|
||||
// Laptop, not phone.
|
||||
expect($cards.eq(0).find('svg rect').attr('width')).toBe('18');
|
||||
expect($cards.eq(1).find('svg rect').attr('width')).toBe('12');
|
||||
});
|
||||
|
||||
it('removes a device once the user confirms', async () => {
|
||||
const remove = vi.fn(() => reply(200, { removed: true }));
|
||||
serve({
|
||||
@@ -522,6 +557,30 @@ describe('your devices', () => {
|
||||
expect(pushClient.browserPushOptedOut('u-1')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps this browser opted out when its push is off but the server removal fails', async () => {
|
||||
const client = fakeClient({ permission: 'granted', registered: true, deviceUid: 'a' });
|
||||
pushClient.registerPushClient(client);
|
||||
serve({
|
||||
'GET /push/devices': { devices: [device({ uid: 'a', current: true })] },
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
'DELETE /push/devices/a': () => reply(500, {}),
|
||||
});
|
||||
await open();
|
||||
client.disable.mockImplementation(async () => {
|
||||
client.status.mockResolvedValue({ permission: 'granted', registered: false });
|
||||
});
|
||||
|
||||
$('.push-remove-device[data-uid="a"]').trigger('click');
|
||||
await settle();
|
||||
dialogButton('push_device_remove').trigger('click');
|
||||
await settle();
|
||||
|
||||
expect(dialog('.dashboard-dialog-message').text()).toContain('push_device_remove_failed');
|
||||
expect(pushClient.browserPushOptedOut('u-1')).toBe(true);
|
||||
expect(browserCard().hasClass('push-browser-off')).toBe(true);
|
||||
});
|
||||
|
||||
it('still removes this browser on the server when it has no local record', async () => {
|
||||
const client = fakeClient({ permission: 'granted', registered: false });
|
||||
pushClient.registerPushClient(client);
|
||||
@@ -548,6 +607,36 @@ describe('your devices', () => {
|
||||
expect($('.push-device-card')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not bring back a removed device when an older listing lands after the removal', async () => {
|
||||
const both = [device({ uid: 'a' }), device({ uid: 'b', label: 'Phone' })];
|
||||
let releaseListing;
|
||||
let deferred = false;
|
||||
serve({
|
||||
'GET /push/devices': () => (deferred
|
||||
? new Promise(resolve => { releaseListing = () => resolve(reply(200, { devices: both })); })
|
||||
: reply(200, { devices: both })),
|
||||
'GET /push/apps': { apps: [] },
|
||||
'GET /push/preferences': { puter: true },
|
||||
'DELETE /push/devices/b': () => reply(200, { removed: true }),
|
||||
});
|
||||
await open();
|
||||
// Coming back to the tab starts a listing that is slow to answer.
|
||||
deferred = true;
|
||||
void tab.onActivate($('.win'));
|
||||
await settle();
|
||||
|
||||
$('.push-remove-device[data-uid="b"]').trigger('click');
|
||||
await settle();
|
||||
dialogButton('push_device_remove').trigger('click');
|
||||
await settle();
|
||||
expect($('.push-remove-device[data-uid="b"]')).toHaveLength(0);
|
||||
|
||||
releaseListing();
|
||||
await settle();
|
||||
expect($('.push-remove-device[data-uid="b"]')).toHaveLength(0);
|
||||
expect($('.push-device-card')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('removes another device with the server alone', async () => {
|
||||
const client = fakeClient({ permission: 'granted', registered: true, deviceUid: 'a' });
|
||||
pushClient.registerPushClient(client);
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
|
||||
import { formatCount, formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
|
||||
import { isOrgSeat } from './orgSeat.js';
|
||||
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { getMonthlyUsage, getStorageSpace } from './usageRequests.js';
|
||||
@@ -281,7 +281,7 @@ function renderUsageTable () {
|
||||
for ( const row of rowsToShow ) {
|
||||
h += `
|
||||
<tr>
|
||||
<td>${window.html_encode(row.resource.replaceAll('_dot_', '.'))}</td>
|
||||
<td title="${window.html_encode(row.resource.replaceAll('_dot_', '.'))}">${window.html_encode(row.resource.replaceAll('_dot_', '.'))}</td>
|
||||
<td>${row.formattedUnits}</td>
|
||||
<td>${row.formattedCost}</td>
|
||||
</tr>`;
|
||||
@@ -351,7 +351,7 @@ async function update_usage_details ($el_window) {
|
||||
if ( key.endsWith(':bytes') ) {
|
||||
formattedUnits = window.byte_format(rawUnits);
|
||||
} else {
|
||||
formattedUnits = window.number_format(rawUnits, { decimals: 0, thousandSeparator: ',' });
|
||||
formattedUnits = formatCount(rawUnits);
|
||||
}
|
||||
|
||||
usageTableData.push({
|
||||
|
||||
@@ -548,12 +548,13 @@ async function UIDashboard (options) {
|
||||
const filePath = route.path;
|
||||
notifications.close({ restoreFocus: false });
|
||||
// What was open over the tab being left goes with it, as on a
|
||||
// sidebar click: the phone drawer, a menu, and Files' Share and
|
||||
// sidebar click: the phone drawer, a menu, Files' Share and
|
||||
// Properties, which act on its rows (their changes are already saved),
|
||||
// and its image preview.
|
||||
// its image preview, and a dialog or the photo crop, each through its
|
||||
// own close button.
|
||||
setMobileSidebar(false);
|
||||
$('.context-menu').remove();
|
||||
$el_window.find('.share-modal-close, .item-props-close').trigger('click');
|
||||
$el_window.find('.share-modal-close, .item-props-close, .dashboard-dialog-overlay .dashboard-dialog-close, .profile-crop-close').trigger('click');
|
||||
if ( tab !== 'files' && TabFiles.previewOpen ) TabFiles.closeImagePreview();
|
||||
|
||||
// Switch to correct tab
|
||||
|
||||
@@ -33,6 +33,7 @@ import { startPushWorker } from '../../helpers/pushWorker.js';
|
||||
import { syncBrowserPush } from '../../helpers/pushSync.js';
|
||||
import { get_app_by_uid } from '../../helpers/getAppByUid.js';
|
||||
import launch_app from '../../helpers/launchApp.js';
|
||||
import { runLimited } from '../../helpers/runLimited.js';
|
||||
import {
|
||||
badgeLabel,
|
||||
glyphKey,
|
||||
@@ -46,6 +47,7 @@ import {
|
||||
senderNameFor,
|
||||
setReadAt,
|
||||
takeMarksSince,
|
||||
titleBadge,
|
||||
titleWithBadge,
|
||||
toEntry,
|
||||
unreadCount,
|
||||
@@ -144,27 +146,6 @@ const whenFilesIdle = async (filesTab, timeoutMs = 4_000) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run `task` over `items`, at most `limit` at a time. Resolves to the items
|
||||
* whose task rejected.
|
||||
*/
|
||||
const runLimited = async (items, limit, task) => {
|
||||
const failed = [];
|
||||
let index = 0;
|
||||
const worker = async () => {
|
||||
while ( index < items.length ) {
|
||||
const item = items[index++];
|
||||
try {
|
||||
await task(item);
|
||||
} catch {
|
||||
failed.push(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return failed;
|
||||
};
|
||||
|
||||
/**
|
||||
* The dashboard's notification center: a bell in the sidebar with the unread
|
||||
* count, a panel listing the most recent notifications read or not, and
|
||||
@@ -360,7 +341,26 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
target.focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
// The badge last put in front of the title, the only prefix replaced.
|
||||
let appliedBadge = '';
|
||||
const applyTitleBadge = () => {
|
||||
const count = unreadCount(entries);
|
||||
const wanted = titleWithBadge(document.title, count, appliedBadge);
|
||||
appliedBadge = titleBadge(count);
|
||||
if ( document.title !== wanted ) document.title = wanted;
|
||||
};
|
||||
|
||||
// Changes made in other tabs arrive one socket event per notification
|
||||
// (Mark all read there sends one ack each), so they redraw once a beat.
|
||||
// Not a frame: a hidden tab's title still carries the count.
|
||||
let renderTimer = null;
|
||||
const scheduleRender = () => {
|
||||
renderTimer ??= setTimeout(render, 50);
|
||||
};
|
||||
|
||||
const render = () => {
|
||||
clearTimeout(renderTimer);
|
||||
renderTimer = null;
|
||||
const hadFocus = $panel[0].contains(document.activeElement);
|
||||
const count = unreadCount(entries);
|
||||
const label = badgeLabel(count);
|
||||
@@ -373,7 +373,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
$sidebarToggle.toggleClass('has-unread', count > 0);
|
||||
$count.text(label);
|
||||
$markAll.attr('hidden', count > 0 ? null : '');
|
||||
document.title = titleWithBadge(document.title, count);
|
||||
applyTitleBadge();
|
||||
|
||||
const showLoading = ! loaded && loading !== null;
|
||||
const showError = ! loaded && loadFailed && loading === null;
|
||||
@@ -582,9 +582,12 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
timeout: TOAST_TIMEOUT_MS,
|
||||
// With nothing to open on the dashboard, a click only dismisses;
|
||||
// it mustn't send the apps the user is working in away.
|
||||
// A regrouped notification rewrites the toast under the same uid,
|
||||
// so a click acts on what it says now.
|
||||
click: () => {
|
||||
if ( notificationTarget(notification) === null ) void markRead(entry.uid);
|
||||
else void reveal_dashboard().then(() => actOn(entry));
|
||||
const current = entries.find((e) => e.uid === entry.uid) ?? entry;
|
||||
if ( notificationTarget(current.notification) === null ) void markRead(current.uid);
|
||||
else void reveal_dashboard().then(() => actOn(current));
|
||||
},
|
||||
// The ✕ is a dismissal; timing out is not, so `close` alone acks.
|
||||
close: () => void markRead(entry.uid),
|
||||
@@ -798,10 +801,8 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
// same title again is a no-op, so this can't loop.
|
||||
const titleEl = document.querySelector('title');
|
||||
if ( titleEl ) {
|
||||
new MutationObserver(() => {
|
||||
const wanted = titleWithBadge(document.title, unreadCount(entries));
|
||||
if ( document.title !== wanted ) document.title = wanted;
|
||||
}).observe(titleEl, { childList: true, characterData: true, subtree: true });
|
||||
new MutationObserver(applyTitleBadge)
|
||||
.observe(titleEl, { childList: true, characterData: true, subtree: true });
|
||||
}
|
||||
|
||||
// -- Arrivals -----------------------------------------------------------------
|
||||
@@ -840,7 +841,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
acked.set(uid, now);
|
||||
if ( ! entries.some((e) => e.uid === uid && isUnread(e)) ) return;
|
||||
entries = setReadAt(entries, uid, now);
|
||||
render();
|
||||
scheduleRender();
|
||||
});
|
||||
// Removed in another tab. Not gated, for the same reason as the ack.
|
||||
socket.on('notif.removed', ({ uid }) => {
|
||||
@@ -848,7 +849,7 @@ export default function UIDashboardNotifications ({ $el_window, socket }) {
|
||||
removed.set(uid, Date.now());
|
||||
const listed = entries.some((e) => e.uid === uid);
|
||||
dropEntry(uid);
|
||||
if ( listed ) render();
|
||||
if ( listed ) scheduleRender();
|
||||
});
|
||||
// Every (re)connection: anything read elsewhere while this tab was
|
||||
// offline is marked so in the server's list, and anything new is in it.
|
||||
|
||||
@@ -291,10 +291,24 @@ export default function UIItemPropertiesModal ({ name, path: item_path, uid, $co
|
||||
const $link = $(this);
|
||||
if ( $link.prop('disabled') ) return;
|
||||
$link.prop('disabled', true);
|
||||
puter.hosting.update($link.attr('data-subdomain'), null).then(() => {
|
||||
const subdomain = $link.attr('data-subdomain');
|
||||
puter.hosting.update(subdomain, null).then(() => {
|
||||
const $entry = $link.closest('.item-props-website-entry');
|
||||
const $row = $entry.closest('.item-props-row');
|
||||
$entry.remove();
|
||||
// Rows inside the folder carry addresses under the site:
|
||||
// work them out again without it (another site may still
|
||||
// serve them).
|
||||
if ( Array.isArray(window.sites) ) {
|
||||
window.sites = window.sites.filter((site) => site.subdomain !== subdomain);
|
||||
}
|
||||
$('.item').each(function () {
|
||||
const path = this.dataset.path ?? '';
|
||||
if ( ! path.startsWith(`${item_path}/`) ) return;
|
||||
const url = window.determine_website_url?.(path) || '';
|
||||
$(this).attr('data-website_url', url)
|
||||
.find('.item-has-website-url-badge').css('display', url ? 'block' : 'none');
|
||||
});
|
||||
// The focused button just left the DOM; keep focus in the dialog.
|
||||
el_modal.focus({ preventScroll: true });
|
||||
if ( $row.find('.item-props-website-entry').length > 0 ) return;
|
||||
|
||||
@@ -68,4 +68,40 @@ describe('UIItemPropertiesModal', () => {
|
||||
expect(window.update_sites_cache).toHaveBeenCalled();
|
||||
expect(puter._cache.del).toHaveBeenCalledWith('readdir:/alice');
|
||||
});
|
||||
|
||||
it('takes the site address off rows inside the folder, keeping one another site serves', async () => {
|
||||
const fsentry = { uid: 'u1', name: 'site', path: '/alice/site', is_dir: true, has_website: true };
|
||||
$('<div class="item" data-uid="u1" data-has_website="1"><img class="item-has-website-badge"></div>')
|
||||
.data('fsentry', fsentry).appendTo('body');
|
||||
const child = (path, url) => $(`<div class="item" data-path="${path}" data-website_url="${url}"><img class="item-has-website-url-badge" style="display:block"></div>`).appendTo('body');
|
||||
const $inside = child('/alice/site/a.txt', 'https://mysite.puter.site/a.txt');
|
||||
const $nested = child('/alice/site/docs/b.txt', 'https://docs.puter.site/b.txt');
|
||||
const site = (subdomain, path) => ({ subdomain, root_dir: { path, subdomains: [{ subdomain, address: `https://${subdomain}.puter.site` }] } });
|
||||
window.sites = [site('mysite', '/alice/site'), site('docs', '/alice/site/docs')];
|
||||
window.determine_website_url = (path) => {
|
||||
const match = window.sites.find((s) => path.startsWith(`${s.root_dir.path}/`));
|
||||
return match ? `https://${match.subdomain}.puter.site${path.slice(match.root_dir.path.length)}` : null;
|
||||
};
|
||||
window.extractSubdomain = () => 'mysite';
|
||||
window.update_sites_cache = vi.fn();
|
||||
globalThis.puter = {
|
||||
fs: { stat: vi.fn(({ success }) => {
|
||||
success({ ...fsentry, id: 'u1', modified: 1700000000, created: 1700000000, subdomains: [{ uuid: 's1', address: 'https://mysite.puter.site' }] });
|
||||
return Promise.resolve();
|
||||
}) },
|
||||
hosting: { update: vi.fn(async () => ({})) },
|
||||
fsCacheKey: (kind, path) => `${kind}:${path}`,
|
||||
_cache: { del: vi.fn() },
|
||||
};
|
||||
|
||||
UIItemPropertiesModal({ name: 'site', path: '/alice/site', uid: 'u1' });
|
||||
await tick();
|
||||
$('.item-props-disassociate').trigger('click');
|
||||
await tick();
|
||||
|
||||
expect($inside.attr('data-website_url')).toBe('');
|
||||
expect($inside.find('.item-has-website-url-badge').css('display')).toBe('none');
|
||||
expect($nested.attr('data-website_url')).toBe('https://docs.puter.site/b.txt');
|
||||
expect($nested.find('.item-has-website-url-badge').css('display')).toBe('block');
|
||||
});
|
||||
});
|
||||
@@ -651,17 +651,25 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
|
||||
// One request per run of MAX_ITEMS_PER_REQUEST, in series so a large
|
||||
// selection can't burst through the share rate limit. Resolves with every
|
||||
// grant that landed, the way a single call would.
|
||||
// A run that fails after others landed rejects with those grants on the
|
||||
// error as `landed`.
|
||||
const grant_access = async (recipient, mode, paths) => {
|
||||
const created = [];
|
||||
for ( const run of chunk(paths, MAX_ITEMS_PER_REQUEST) ) {
|
||||
created.push(...(await with_verification_gate(
|
||||
() => puter.fs.share({ paths: run, recipient, mode }),
|
||||
) ?? []));
|
||||
}
|
||||
// A selection too large to list again (see refresh) learns which rows
|
||||
// are now shared from the grants themselves.
|
||||
if ( total > MAX_ITEMS_PER_REQUEST ) {
|
||||
for ( const share of created ) mark_item_shared(share.path, true);
|
||||
try {
|
||||
for ( const run of chunk(paths, MAX_ITEMS_PER_REQUEST) ) {
|
||||
created.push(...(await with_verification_gate(
|
||||
() => puter.fs.share({ paths: run, recipient, mode }),
|
||||
) ?? []));
|
||||
}
|
||||
} catch (err) {
|
||||
if ( created.length && err && typeof err === 'object' ) err.landed = created;
|
||||
throw err;
|
||||
} finally {
|
||||
// A selection too large to list again (see refresh) learns which
|
||||
// rows are now shared from the grants themselves.
|
||||
if ( total > MAX_ITEMS_PER_REQUEST ) {
|
||||
for ( const share of created ) mark_item_shared(share.path, true);
|
||||
}
|
||||
}
|
||||
return created;
|
||||
};
|
||||
@@ -848,8 +856,16 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
|
||||
if ( ! focus_moved_on() ) $recipient.get(0)?.focus({ preventScroll: true });
|
||||
} catch (err) {
|
||||
sharing = false;
|
||||
show_error(error_html(err));
|
||||
// Runs that landed before the failure are shared all the same.
|
||||
const landed = err?.landed?.length ?? 0;
|
||||
show_error(landed
|
||||
? `${i18n('share_shared_with_partial', { recipient, count: landed, total })}. ${error_html(err)}`
|
||||
: error_html(err));
|
||||
sync_add_actions();
|
||||
if ( landed ) {
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
}
|
||||
// Disabling the clicked button dropped focus to <body>; put it
|
||||
// where the correction happens.
|
||||
$recipient.get(0)?.focus({ preventScroll: true });
|
||||
|
||||
@@ -226,4 +226,28 @@ describe('UIShareModal adding people', () => {
|
||||
await settle();
|
||||
expect($('.share-modal-submit').prop('disabled')).toBe(false);
|
||||
});
|
||||
|
||||
it('says how many items were shared when a later run fails, and badges those rows', async () => {
|
||||
const selection = Array.from({ length: 60 }, (_, i) => ({ path: `/alice/f${i}.txt` }));
|
||||
document.body.insertAdjacentHTML('beforeend', selection
|
||||
.map(item => `<div class="item" data-path="${item.path}" data-is_shared="0"></div>`).join(''));
|
||||
let call = 0;
|
||||
puter.fs.share = vi.fn(async ({ paths }) => {
|
||||
if ( ++call === 2 ) throw { message: 'Daily share limit reached', code: 'share_daily_limit_reached' };
|
||||
return paths.map(p => ({ path: p }));
|
||||
});
|
||||
UIShareModal({ items: selection });
|
||||
await settle();
|
||||
picked.recipient = { value: 'bob', label: 'bob' };
|
||||
picked.onChange();
|
||||
|
||||
$('.share-modal-add').trigger('submit');
|
||||
await settle();
|
||||
|
||||
expect(puter.fs.share).toHaveBeenCalledTimes(2);
|
||||
const status = $('.share-modal-status').text();
|
||||
expect(status).toContain('Shared with bob on 50 of 60 items');
|
||||
expect(status).toContain('Daily share limit reached');
|
||||
expect($('.item[data-is_shared="1"]')).toHaveLength(50);
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,16 @@ const numberFormat = (options) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A whole count (usage units) in the dashboard's language: "1,234,567" in
|
||||
* English, "1.234.567" in German.
|
||||
*
|
||||
* @param {number} count
|
||||
* @returns {string}
|
||||
*/
|
||||
export const formatCount = (count) =>
|
||||
numberFormat({ maximumFractionDigits: 0 }).format(Number.isFinite(count) ? count : 0);
|
||||
|
||||
/** Whether a `getMonthlyUsage()` response reports credits. */
|
||||
export const usageIsCredits = (allowanceInfo) =>
|
||||
allowanceInfo?.unit === 'credits';
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
|
||||
import {
|
||||
formatCount,
|
||||
formatCredits,
|
||||
formatDollarsFromMicrocents,
|
||||
usageIsCredits,
|
||||
@@ -86,6 +87,14 @@ describe('amounts in the dashboard\'s language', () => {
|
||||
expect(formatCredits(2.5)).toBe('2,5');
|
||||
expect(formatCredits(0.001)).toBe('<0,01');
|
||||
expect(formatDollarsFromMicrocents(123_450_000_000).replace(/\s/g, ' ')).toBe('1.234,50 $');
|
||||
expect(formatCount(1234567)).toBe('1.234.567');
|
||||
});
|
||||
|
||||
it('counts usage units in English by default', () => {
|
||||
delete globalThis.window.locale;
|
||||
expect(formatCount(1234567)).toBe('1,234,567');
|
||||
expect(formatCount(12.6)).toBe('13');
|
||||
expect(formatCount(undefined)).toBe('0');
|
||||
});
|
||||
|
||||
it("reads Puter's codes that aren't BCP 47 tags", () => {
|
||||
|
||||
@@ -346,20 +346,26 @@ export const badgeLabel = (count) => {
|
||||
return count > 99 ? '99+' : String(count);
|
||||
};
|
||||
|
||||
const TITLE_BADGE = /^\((\d+\+?)\) /;
|
||||
/** What the unread count puts in front of the title: "(3) ", or nothing. */
|
||||
export const titleBadge = (count) => {
|
||||
const label = badgeLabel(count);
|
||||
return label ? `(${label}) ` : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* The document title with the unread count in front, replacing any count
|
||||
* already there so repeated application never stacks prefixes.
|
||||
* The document title with the unread count in front. Only `applied`, the
|
||||
* badge this page last put there, is replaced, so repeated application never
|
||||
* stacks prefixes and an app's own "(3) Inbox" title keeps its count.
|
||||
*
|
||||
* @param {string} title
|
||||
* @param {number} count
|
||||
* @param {string} [applied]
|
||||
* @returns {string}
|
||||
*/
|
||||
export const titleWithBadge = (title, count) => {
|
||||
const base = String(title ?? '').replace(TITLE_BADGE, '');
|
||||
const label = badgeLabel(count);
|
||||
return label ? `(${label}) ${base}` : base;
|
||||
export const titleWithBadge = (title, count, applied = '') => {
|
||||
let base = String(title ?? '');
|
||||
if ( applied && base.startsWith(applied) ) base = base.slice(applied.length);
|
||||
return titleBadge(count) + base;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -370,16 +376,17 @@ export const titleWithBadge = (title, count) => {
|
||||
export const MAX_BURST_TOASTS = 3;
|
||||
|
||||
/**
|
||||
* Split a burst into the entries that get their own toast and the number
|
||||
* that don't.
|
||||
* Split a burst into the entries that get their own toast, newest first, and
|
||||
* the number that don't. Bursts arrive in either order (a catch-up listing is
|
||||
* oldest first), and the newest are the ones worth a toast.
|
||||
*
|
||||
* @param {NotificationEntry[]} entries - Newest first
|
||||
* @param {NotificationEntry[]} entries
|
||||
* @param {number} [max]
|
||||
* @returns {{ shown: NotificationEntry[], folded: number }}
|
||||
*/
|
||||
export const planBurstToasts = (entries, max = MAX_BURST_TOASTS) => {
|
||||
if ( entries.length <= max ) return { shown: entries, folded: 0 };
|
||||
const newestFirst = sortEntries(entries);
|
||||
// One over the cap is no quieter shown as a summary than as a toast.
|
||||
if ( entries.length === max + 1 ) return { shown: entries, folded: 0 };
|
||||
return { shown: entries.slice(0, max), folded: entries.length - max };
|
||||
if ( newestFirst.length <= max + 1 ) return { shown: newestFirst, folded: 0 };
|
||||
return { shown: newestFirst.slice(0, max), folded: newestFirst.length - max };
|
||||
};
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
setReadAt,
|
||||
sortEntries,
|
||||
takeMarksSince,
|
||||
titleBadge,
|
||||
titleWithBadge,
|
||||
toEntry,
|
||||
unreadCount,
|
||||
@@ -424,16 +425,24 @@ describe('titleWithBadge', () => {
|
||||
expect(titleWithBadge('Puter', 3)).toBe('(3) Puter');
|
||||
});
|
||||
|
||||
it('replaces an existing count instead of stacking', () => {
|
||||
expect(titleWithBadge('(2) Puter', 5)).toBe('(5) Puter');
|
||||
expect(titleWithBadge('(99+) Puter', 1)).toBe('(1) Puter');
|
||||
it('replaces the count it put there instead of stacking', () => {
|
||||
expect(titleWithBadge('(2) Puter', 5, '(2) ')).toBe('(5) Puter');
|
||||
expect(titleWithBadge('(99+) Puter', 1, '(99+) ')).toBe('(1) Puter');
|
||||
});
|
||||
|
||||
it('clears the prefix at zero', () => {
|
||||
expect(titleWithBadge('(2) Puter', 0)).toBe('Puter');
|
||||
expect(titleWithBadge('(2) Puter', 0, '(2) ')).toBe('Puter');
|
||||
expect(titleWithBadge('Puter', 0)).toBe('Puter');
|
||||
});
|
||||
|
||||
it('leaves a count that is part of an app\'s own title alone', () => {
|
||||
expect(titleWithBadge('(3) Inbox', 0)).toBe('(3) Inbox');
|
||||
expect(titleWithBadge('(3) Inbox', 2)).toBe('(2) (3) Inbox');
|
||||
// The app rewrote the title after the badge was applied.
|
||||
expect(titleWithBadge('(3) Inbox', 2, '(2) ')).toBe('(2) (3) Inbox');
|
||||
expect(titleWithBadge('(2) (3) Inbox', 0, '(2) ')).toBe('(3) Inbox');
|
||||
});
|
||||
|
||||
it('leaves a parenthesised title that is not a badge alone', () => {
|
||||
expect(titleWithBadge('(draft) Notes', 0)).toBe('(draft) Notes');
|
||||
expect(titleWithBadge('(draft) Notes', 2)).toBe('(2) (draft) Notes');
|
||||
@@ -445,6 +454,14 @@ describe('titleWithBadge', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('titleBadge', () => {
|
||||
it('is the prefix a count puts in front of the title', () => {
|
||||
expect(titleBadge(3)).toBe('(3) ');
|
||||
expect(titleBadge(120)).toBe('(99+) ');
|
||||
expect(titleBadge(0)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('planBurstToasts', () => {
|
||||
const many = (n) => Array.from({ length: n }, (_, i) => entry(`n${i}`, NOW - i));
|
||||
|
||||
@@ -463,6 +480,12 @@ describe('planBurstToasts', () => {
|
||||
expect(shown.map((e) => e.uid)).toEqual(['n0', 'n1', 'n2']);
|
||||
expect(folded).toBe(9);
|
||||
});
|
||||
|
||||
it('toasts the newest of a burst that arrives oldest first', () => {
|
||||
const { shown, folded } = planBurstToasts(many(6).reverse());
|
||||
expect(shown.map((e) => e.uid)).toEqual(['n0', 'n1', 'n2']);
|
||||
expect(folded).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('senderNameFor', () => {
|
||||
|
||||
@@ -18,9 +18,8 @@
|
||||
*/
|
||||
|
||||
import UIWindowItemProperties from './UIWindowItemProperties.js';
|
||||
import UIWindowSaveAccount from './UIWindowSaveAccount.js';
|
||||
import ensureConfirmedEmail from '../helpers/ensureConfirmedEmail.js';
|
||||
import UIPopover from './UIPopover.js';
|
||||
import UIWindowEmailConfirmationRequired from './UIWindowEmailConfirmationRequired.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import UIWindowPublishWorker from './UIWindowPublishWorker.js';
|
||||
@@ -1255,23 +1254,7 @@ async function UIItem (options) {
|
||||
menu_items.push({
|
||||
html: i18n('publish_as_serverless_worker'),
|
||||
onClick: async function () {
|
||||
if ( window.user.is_temp &&
|
||||
!await UIWindowSaveAccount({
|
||||
send_confirmation_code: true,
|
||||
message: 'Please create an account to proceed.',
|
||||
window_options: {
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
},
|
||||
}) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
else if ( !window.user.email_confirmed && !await UIWindowEmailConfirmationRequired() )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! await ensureConfirmedEmail(i18n('save_account_to_publish')) ) return;
|
||||
UIWindowPublishWorker(options.uid, $(el_item).attr('data-name'), $(el_item).attr('data-path'));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -934,7 +934,7 @@ async function UIWindow (options) {
|
||||
// LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
|
||||
// this is literally put in here to support Polotno's legacy code
|
||||
...(selected_files.length === 1 && selected_files[0]),
|
||||
}, '*');
|
||||
}, window.openerOrigin);
|
||||
|
||||
window.close();
|
||||
window.open('', '_self').close();
|
||||
@@ -1018,7 +1018,7 @@ async function UIWindow (options) {
|
||||
// LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
|
||||
// this is literally put in here to support Polotno's legacy code
|
||||
...(selected_dirs.length === 1 && selected_dirs[0]),
|
||||
}, '*');
|
||||
}, window.openerOrigin);
|
||||
|
||||
window.close();
|
||||
window.open('', '_self').close();
|
||||
|
||||
@@ -666,22 +666,22 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
|
||||
h += '<div class="tfa-progress" style="display:none;">';
|
||||
h += ' <div class="tfa-progress-step">';
|
||||
h += ' <div class="tfa-progress-dot active" data-step="1">1</div>';
|
||||
h += ' <span class="tfa-progress-label active">Scan</span>';
|
||||
h += ` <span class="tfa-progress-label active">${i18n('setup2fa_step_scan')}</span>`;
|
||||
h += ' </div>';
|
||||
h += ' <div class="tfa-progress-line"><div class="tfa-progress-line-fill"></div></div>';
|
||||
h += ' <div class="tfa-progress-step">';
|
||||
h += ' <div class="tfa-progress-dot" data-step="2">2</div>';
|
||||
h += ' <span class="tfa-progress-label">Backup</span>';
|
||||
h += ` <span class="tfa-progress-label">${i18n('setup2fa_step_backup')}</span>`;
|
||||
h += ' </div>';
|
||||
h += ' <div class="tfa-progress-line"><div class="tfa-progress-line-fill"></div></div>';
|
||||
h += ' <div class="tfa-progress-step">';
|
||||
h += ' <div class="tfa-progress-dot" data-step="3">3</div>';
|
||||
h += ' <span class="tfa-progress-label">Verify</span>';
|
||||
h += ` <span class="tfa-progress-label">${i18n('setup2fa_step_verify')}</span>`;
|
||||
h += ' </div>';
|
||||
h += ' <div class="tfa-progress-line"><div class="tfa-progress-line-fill"></div></div>';
|
||||
h += ' <div class="tfa-progress-step">';
|
||||
h += ` <div class="tfa-progress-dot" data-step="4">${SVG_CHECK}</div>`;
|
||||
h += ' <span class="tfa-progress-label">Done</span>';
|
||||
h += ` <span class="tfa-progress-label">${i18n('done')}</span>`;
|
||||
h += ' </div>';
|
||||
h += '</div>';
|
||||
|
||||
@@ -703,7 +703,7 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
|
||||
// Manual secret key, filled in once setup returns it
|
||||
h += '<div class="tfa-secret-row" style="display:none;">';
|
||||
h += ' <span class="tfa-secret-key"></span>';
|
||||
h += ` <button class="tfa-copy-secret" title="Copy secret key">${SVG_COPY}</button>`;
|
||||
h += ` <button class="tfa-copy-secret" title="${i18n('setup2fa_copy_secret')}" aria-label="${i18n('setup2fa_copy_secret')}">${SVG_COPY}</button>`;
|
||||
h += '</div>';
|
||||
|
||||
h += `<button class="tfa-btn tfa-btn-primary tfa-scan-continue-btn">${i18n('continue')}</button>`;
|
||||
@@ -747,7 +747,7 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
|
||||
}
|
||||
h += ' </div>';
|
||||
h += ' <div class="tfa-code-error"></div>';
|
||||
h += ` <div class="tfa-code-spinner"><div class="tfa-spinner-icon"></div><span>Enabling...</span></div>`;
|
||||
h += ` <div class="tfa-code-spinner"><div class="tfa-spinner-icon"></div><span>${i18n('setup2fa_enabling')}</span></div>`;
|
||||
h += '</div>';
|
||||
h += '</div>'; // end screen 3
|
||||
|
||||
@@ -755,8 +755,8 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
|
||||
h += '<div class="tfa-screen" data-screen="4">';
|
||||
h += `<div class="tfa-success-icon">${SVG_SHIELD_CHECK}</div>`;
|
||||
h += `<div class="tfa-success-title">${i18n('two_factor_enabled')}</div>`;
|
||||
h += '<p class="tfa-success-text">Your account is now protected with two-factor authentication. You\'ll be asked for a verification code each time you sign in.</p>';
|
||||
h += `<button class="tfa-btn tfa-btn-success tfa-done-btn">Done</button>`;
|
||||
h += `<p class="tfa-success-text">${i18n('setup2fa_success_text')}</p>`;
|
||||
h += `<button class="tfa-btn tfa-btn-success tfa-done-btn">${i18n('done')}</button>`;
|
||||
h += '</div>'; // end screen 4
|
||||
|
||||
h += '</div>'; // end tfa-setup
|
||||
@@ -1019,7 +1019,7 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
|
||||
navigator.clipboard.writeText(setup_data.codes.join('\n'));
|
||||
const $span = $(this).find('span');
|
||||
const orig = $span.text();
|
||||
$span.text('Copied!');
|
||||
$span.text(i18n('copied', [], false));
|
||||
$(this).addClass('copied');
|
||||
setTimeout(() => {
|
||||
$span.text(orig);
|
||||
@@ -1031,7 +1031,7 @@ const UIWindow2FASetup = async function UIWindow2FASetup () {
|
||||
const grid_html = $w.find('.tfa-codes-grid').get(0).outerHTML;
|
||||
const print_frame = $w.find('.tfa-print-frame').get(0);
|
||||
const style = '<style>body{font-family:monospace;padding:20px} .tfa-codes-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px} .tfa-code-item{padding:8px;font-size:14px;display:flex;gap:8px} .tfa-code-item-idx{color:#999}</style>';
|
||||
print_frame.contentWindow.document.body.innerHTML = style + '<h2>Recovery Codes</h2>' + grid_html;
|
||||
print_frame.contentWindow.document.body.innerHTML = `${style}<h2>${i18n('setup2fa_recovery_codes')}</h2>${grid_html}`;
|
||||
print_frame.contentWindow.focus();
|
||||
print_frame.contentWindow.print();
|
||||
});
|
||||
|
||||
@@ -40,7 +40,9 @@ let feedback_modal_seq = 0;
|
||||
* server is the authority on the app's canonical title — then submits to
|
||||
* `POST /app-feedback`.
|
||||
*
|
||||
* @param {{ app?: string, origin?: string, source?: 'app' | 'web' }} options
|
||||
* @param {{ app?: string, origin?: string, source?: 'app' | 'web', fullpage?: boolean }} options
|
||||
* `fullpage` fills the viewport instead of floating over it, for a popup
|
||||
* window that exists only to host this dialog.
|
||||
* @returns {Promise<boolean>} true iff feedback was submitted successfully.
|
||||
* Resolves false on cancel/close/unavailable — never rejects, so IPC and
|
||||
* popup callers can always report an answer.
|
||||
@@ -54,7 +56,8 @@ async function UIWindowAppFeedback (options) {
|
||||
let sending = false;
|
||||
let closed = false;
|
||||
|
||||
const authToken = puter.authToken ?? window.auth_token;
|
||||
// The feedback embed runs without puter.js.
|
||||
const authToken = globalThis.puter?.authToken ?? window.auth_token;
|
||||
const target_params = options.app
|
||||
? { app: options.app }
|
||||
: { origin: options.origin };
|
||||
@@ -70,7 +73,7 @@ async function UIWindowAppFeedback (options) {
|
||||
|
||||
const titleId = `${modal_id}-title`;
|
||||
const h = `
|
||||
<div class="app-feedback-overlay" role="dialog" aria-modal="true" aria-labelledby="${titleId}">
|
||||
<div class="app-feedback-overlay${options.fullpage ? ' app-feedback-fullpage' : ''}" role="dialog" aria-modal="true" aria-labelledby="${titleId}">
|
||||
<div class="app-feedback-modal" tabindex="-1">
|
||||
<div class="app-feedback-head">
|
||||
<h2 class="app-feedback-title" id="${titleId}">${i18n('app_feedback_title')}</h2>
|
||||
@@ -79,16 +82,16 @@ async function UIWindowAppFeedback (options) {
|
||||
</button>
|
||||
</div>
|
||||
<div class="app-feedback-body">
|
||||
<div class="app-feedback-loading">${i18n('loading')}…</div>
|
||||
<div class="app-feedback-pane app-feedback-loading">${i18n('loading')}…</div>
|
||||
|
||||
<div class="app-feedback-unavailable" style="display:none;">
|
||||
<div class="app-feedback-pane app-feedback-unavailable" style="display:none;">
|
||||
<p class="app-feedback-unavailable-message"></p>
|
||||
<div class="app-feedback-actions">
|
||||
<button type="button" class="app-feedback-btn app-feedback-btn-primary app-feedback-close-btn">${i18n('close')}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="app-feedback-form" style="display:none;">
|
||||
<div class="app-feedback-pane app-feedback-form" style="display:none;">
|
||||
<div class="app-feedback-target">
|
||||
<div class="app-feedback-target-title"></div>
|
||||
<div class="app-feedback-target-name"></div>
|
||||
@@ -104,7 +107,7 @@ async function UIWindowAppFeedback (options) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="app-feedback-success" style="display:none;">
|
||||
<div class="app-feedback-pane app-feedback-success" style="display:none;">
|
||||
<div class="app-feedback-success-check" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
const { default: UIWindowAppFeedback } = await import('./UIWindowAppFeedback.js');
|
||||
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0));
|
||||
const $ = (sel) => jQuery(sel);
|
||||
const visiblePanes = () => $('.app-feedback-pane').filter((_, el) => el.style.display !== 'none');
|
||||
|
||||
/** Opens the dialog against an app that accepts feedback and waits for the form. */
|
||||
const open = async (options) => {
|
||||
globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({
|
||||
enabled: true,
|
||||
app: { title: 'Build with AI', name: 'builder' },
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } }));
|
||||
UIWindowAppFeedback({ origin: 'https://builder.puter.test', source: 'web', ...options });
|
||||
await flush();
|
||||
await flush();
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.i18n = (key) => key;
|
||||
globalThis.html_encode = (value) => jQuery('<div>').text(value).html();
|
||||
window.api_origin = 'https://api.puter.test';
|
||||
window.auth_token = 'token';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
$(document).off('keydown');
|
||||
});
|
||||
|
||||
describe('UIWindowAppFeedback', () => {
|
||||
it('floats over the page by default', async () => {
|
||||
await open();
|
||||
expect($('.app-feedback-overlay').hasClass('app-feedback-fullpage')).toBe(false);
|
||||
expect(visiblePanes().hasClass('app-feedback-form')).toBe(true);
|
||||
});
|
||||
|
||||
it('fills the page when hosted in its own popup', async () => {
|
||||
await open({ fullpage: true });
|
||||
expect($('.app-feedback-overlay').hasClass('app-feedback-fullpage')).toBe(true);
|
||||
expect(visiblePanes()).toHaveLength(1);
|
||||
expect(visiblePanes().hasClass('app-feedback-form')).toBe(true);
|
||||
expect($('.app-feedback-target-title').text()).toBe('Build with AI');
|
||||
});
|
||||
});
|
||||
@@ -83,7 +83,7 @@ async function UIWindowAttachCustomDomain (options) {
|
||||
const titleId = `${modal_id}-title`;
|
||||
const closeLabel = html_encode(i18n('close'));
|
||||
const h = `
|
||||
<div class="app-feedback-overlay custom-domain-overlay${options.fullpage ? ' custom-domain-fullpage' : ''}" role="dialog" aria-modal="true" aria-labelledby="${titleId}">
|
||||
<div class="app-feedback-overlay custom-domain-overlay${options.fullpage ? ' app-feedback-fullpage' : ''}" role="dialog" aria-modal="true" aria-labelledby="${titleId}">
|
||||
<div class="app-feedback-modal custom-domain-modal" tabindex="-1">
|
||||
<div class="app-feedback-head custom-domain-head">
|
||||
<div class="custom-domain-head-icon">${ICON_GLOBE}</div>
|
||||
@@ -95,13 +95,13 @@ async function UIWindowAttachCustomDomain (options) {
|
||||
<button type="button" class="app-feedback-x" aria-label="${closeLabel}" title="${closeLabel}">${ICON_X}</button>
|
||||
</div>
|
||||
<div class="app-feedback-body custom-domain-body">
|
||||
<div class="custom-domain-pane" data-pane="loading" aria-busy="true">
|
||||
<div class="app-feedback-pane custom-domain-pane" data-pane="loading" aria-busy="true">
|
||||
<span class="custom-domain-sr">${i18n('loading')}…</span>
|
||||
<div class="custom-domain-skeleton"><span></span><span></span></div>
|
||||
<div class="custom-domain-skeleton"><span></span><span></span></div>
|
||||
</div>
|
||||
|
||||
<div class="custom-domain-pane custom-domain-state" data-pane="unavailable" style="display:none;">
|
||||
<div class="app-feedback-pane custom-domain-pane custom-domain-state" data-pane="unavailable" style="display:none;">
|
||||
<div class="custom-domain-state-icon">${ICON_ALERT}</div>
|
||||
<p class="app-feedback-unavailable-message"></p>
|
||||
<div class="app-feedback-actions">
|
||||
@@ -109,7 +109,7 @@ async function UIWindowAttachCustomDomain (options) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="custom-domain-pane" data-pane="list" style="display:none;">
|
||||
<div class="app-feedback-pane custom-domain-pane" data-pane="list" style="display:none;">
|
||||
<ul class="custom-domain-list"></ul>
|
||||
<div class="custom-domain-state custom-domain-empty" style="display:none;">
|
||||
<div class="custom-domain-state-icon">${ICON_GLOBE}</div>
|
||||
@@ -124,7 +124,7 @@ async function UIWindowAttachCustomDomain (options) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="custom-domain-pane" data-pane="add" style="display:none;" novalidate>
|
||||
<form class="app-feedback-pane custom-domain-pane" data-pane="add" style="display:none;" novalidate>
|
||||
<label class="custom-domain-label" for="${modal_id}-hostname">${i18n('custom_domain_hostname_label')}</label>
|
||||
<div class="custom-domain-field">
|
||||
${ICON_GLOBE}
|
||||
@@ -143,7 +143,7 @@ async function UIWindowAttachCustomDomain (options) {
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="custom-domain-pane" data-pane="records" style="display:none;">
|
||||
<div class="app-feedback-pane custom-domain-pane" data-pane="records" style="display:none;">
|
||||
<div class="custom-domain-status-card">
|
||||
<div class="custom-domain-status-icon"></div>
|
||||
<div class="custom-domain-status-main">
|
||||
@@ -165,7 +165,7 @@ async function UIWindowAttachCustomDomain (options) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="custom-domain-pane app-feedback-success custom-domain-success" data-pane="success" role="status" style="display:none;">
|
||||
<div class="app-feedback-pane custom-domain-pane app-feedback-success custom-domain-success" data-pane="success" role="status" style="display:none;">
|
||||
<div class="app-feedback-success-check">${ICON_CHECK}</div>
|
||||
<p class="app-feedback-success-text custom-domain-success-text"></p>
|
||||
<p class="app-feedback-note custom-domain-success-note"></p>
|
||||
|
||||
@@ -20,12 +20,24 @@
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
|
||||
/**
|
||||
* Asks for the code sent to the user's email.
|
||||
*
|
||||
* @returns {Promise<boolean>} True once the email is confirmed, false when the
|
||||
* window closes without it. A logout, from its footer or anywhere else,
|
||||
* leaves it unsettled, so a gate that reopens it on false doesn't race the
|
||||
* logout.
|
||||
*/
|
||||
function UIWindowEmailConfirmationRequired (options) {
|
||||
return new Promise(async (resolve) => {
|
||||
options = options ?? {};
|
||||
options.window_options = options.window_options ?? {};
|
||||
let final_code = '';
|
||||
let is_checking_code = false;
|
||||
let logging_out = false;
|
||||
let submit_timer = null;
|
||||
let code_sent = false;
|
||||
let close_after_check = false;
|
||||
|
||||
const submit_btn_txt = 'Confirm Email';
|
||||
|
||||
@@ -92,6 +104,20 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
// A code on its way to the server answers for the window, so the
|
||||
// window waits for it. One not sent yet isn't sent.
|
||||
on_before_exit: () => {
|
||||
if ( code_sent && ! logging_out ) {
|
||||
close_after_check = true;
|
||||
return false;
|
||||
}
|
||||
clearTimeout(submit_timer);
|
||||
return true;
|
||||
},
|
||||
// A no-op after a confirmation, which resolves first.
|
||||
on_close: () => {
|
||||
if ( ! logging_out && window.auth_token ) resolve(false);
|
||||
},
|
||||
body_css: {
|
||||
padding: '30px',
|
||||
width: 'initial',
|
||||
@@ -122,7 +148,8 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
// set animation
|
||||
$(el_window).find('.email-confirm-btn').html('<svg style="width:20px; margin-top: 5px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#fff" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#eee" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>');
|
||||
|
||||
setTimeout(() => {
|
||||
submit_timer = setTimeout(() => {
|
||||
code_sent = true;
|
||||
$.ajax({
|
||||
url: `${window.api_origin }/confirm-email`,
|
||||
type: 'POST',
|
||||
@@ -141,9 +168,13 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
},
|
||||
success: function (res) {
|
||||
if ( res.email_confirmed ) {
|
||||
// Callers check window.user next, before the refresh lands.
|
||||
if ( window.user ) window.user.email_confirmed = true;
|
||||
resolve(true);
|
||||
code_sent = false;
|
||||
close_after_check = false;
|
||||
$(el_window).close();
|
||||
window.refresh_user_data(window.auth_token);
|
||||
resolve(true);
|
||||
} else {
|
||||
$(el_window).find('.error').html('Invalid confirmation code.');
|
||||
$(el_window).find('.error').fadeIn();
|
||||
@@ -155,7 +186,8 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
}
|
||||
},
|
||||
error: function (res) {
|
||||
$(el_window).find('.error').html(html_encode(res.responseJSON.error));
|
||||
// A network failure has no body to read.
|
||||
$(el_window).find('.error').html(html_encode(res.responseJSON?.error ?? i18n('error_unknown_cause')));
|
||||
$(el_window).find('.error').fadeIn();
|
||||
$(el_window).find('.digit-input').val('');
|
||||
$(el_window).find('.digit-input').first().focus();
|
||||
@@ -165,6 +197,8 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
},
|
||||
complete: function () {
|
||||
is_checking_code = false;
|
||||
code_sent = false;
|
||||
if ( close_after_check ) $(el_window).close();
|
||||
},
|
||||
});
|
||||
}, 1000);
|
||||
@@ -172,6 +206,7 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
|
||||
// send email confirmation
|
||||
$(el_window).find('.send-conf-email').on('click', function (e) {
|
||||
$(el_window).find('.error').hide();
|
||||
$.ajax({
|
||||
url: `${window.api_origin }/send-confirm-email`,
|
||||
type: 'POST',
|
||||
@@ -194,19 +229,22 @@ function UIWindowEmailConfirmationRequired (options) {
|
||||
});
|
||||
$(el_window).find('.digit-input').first().focus();
|
||||
},
|
||||
complete: function () {
|
||||
error: function (res) {
|
||||
$(el_window).find('.error').html(html_encode(res.responseJSON?.error ?? i18n('error_unknown_cause')));
|
||||
$(el_window).find('.error').fadeIn();
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// logout
|
||||
$(el_window).find('.conf-email-log-out').on('click', function (e) {
|
||||
logging_out = true;
|
||||
window.logout();
|
||||
$(el_window).close();
|
||||
});
|
||||
|
||||
// Elements
|
||||
const numberCodeForm = document.querySelector('[data-number-code-form]');
|
||||
const numberCodeForm = $(el_window).find('[data-number-code-form]').get(0);
|
||||
const numberCodeInputs = [...numberCodeForm.querySelectorAll('[data-number-code-input]')];
|
||||
|
||||
// Event listeners
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
// Renders the body and, as the real window does, asks on_before_exit before
|
||||
// closing and runs on_close once it's removed.
|
||||
vi.mock('./UIWindow.js', () => ({
|
||||
default: vi.fn(async (opts) => {
|
||||
const el = document.createElement('div');
|
||||
el.className = `window ${opts.window_class}`;
|
||||
el.innerHTML = opts.body_content;
|
||||
el.onClose = opts.on_close;
|
||||
el.onBeforeExit = opts.on_before_exit;
|
||||
document.body.append(el);
|
||||
return el;
|
||||
}),
|
||||
}));
|
||||
vi.mock('./UIAlert.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.def = globalThis.def ?? (value => value);
|
||||
|
||||
const { default: UIWindowEmailConfirmationRequired } = await import('./UIWindowEmailConfirmationRequired.js');
|
||||
|
||||
const PENDING = Symbol('pending');
|
||||
const settled = (promise) => Promise.race([promise, new Promise((r) => setTimeout(() => r(PENDING), 0))]);
|
||||
const win = () => jQuery('.window-confirm-email-using-code');
|
||||
|
||||
/** Opens the window and waits for it to render. Returns its answer, still pending. */
|
||||
const open = async (options) => {
|
||||
const result = UIWindowEmailConfirmationRequired(options);
|
||||
await vi.waitFor(() => expect(win()).toHaveLength(1));
|
||||
return { result };
|
||||
};
|
||||
|
||||
const enterCode = () => {
|
||||
const first = document.querySelector('[data-number-code-input="0"]');
|
||||
first.value = '123456';
|
||||
first.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
globalThis.$ = jQuery;
|
||||
jQuery.fn.close = function () {
|
||||
this.each((_, el) => {
|
||||
if ( ! el.isConnected || el.onBeforeExit?.() === false ) return;
|
||||
el.remove();
|
||||
el.onClose?.();
|
||||
});
|
||||
return this;
|
||||
};
|
||||
globalThis.i18n = (key) => key;
|
||||
globalThis.html_encode = (value) => String(value);
|
||||
window.icons = {};
|
||||
window.api_origin = 'https://api.puter.test';
|
||||
window.auth_token = 'token-1';
|
||||
window.user = { email: '[email protected]', email_confirmed: false };
|
||||
window.refresh_user_data = vi.fn();
|
||||
window.logout = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
delete jQuery.fn.close;
|
||||
});
|
||||
|
||||
describe('UIWindowEmailConfirmationRequired', () => {
|
||||
it('resolves true once the code confirms the email, and says so on window.user straight away', async () => {
|
||||
const ajax = vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => {
|
||||
opts.success({ email_confirmed: true });
|
||||
opts.complete?.();
|
||||
});
|
||||
const { result } = await open();
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(ajax).toHaveBeenCalledWith(expect.objectContaining({
|
||||
url: 'https://api.puter.test/confirm-email',
|
||||
data: JSON.stringify({ code: '123456' }),
|
||||
}));
|
||||
// Callers read it next, before the refresh lands.
|
||||
expect(window.user.email_confirmed).toBe(true);
|
||||
expect(window.refresh_user_data).toHaveBeenCalledWith('token-1');
|
||||
expect(win()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('stays open on a wrong code', async () => {
|
||||
vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => {
|
||||
opts.success({ email_confirmed: false });
|
||||
opts.complete?.();
|
||||
});
|
||||
const { result } = await open();
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
expect(win()).toHaveLength(1);
|
||||
expect(window.user.email_confirmed).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the server\'s error', { status: 429, responseJSON: { error: 'Too many requests.' } }, 'Too many requests.'],
|
||||
['an unknown error on a network failure', { status: 0 }, 'error_unknown_cause'],
|
||||
])('shows %s and lets the user try again', async (_label, xhr, shown) => {
|
||||
vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => {
|
||||
opts.error(xhr);
|
||||
opts.complete?.();
|
||||
});
|
||||
const { result } = await open();
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
|
||||
expect(win().find('.error').text()).toBe(shown);
|
||||
expect(win().find('.digit-input').prop('disabled')).toBe(false);
|
||||
expect(win().find('.email-confirm-btn').text()).toBe('Confirm Email');
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
});
|
||||
|
||||
it('takes the code typed in a second window open over another', async () => {
|
||||
const ajax = vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => {
|
||||
opts.success({ email_confirmed: true });
|
||||
opts.complete?.();
|
||||
});
|
||||
const { result: under } = await open();
|
||||
const over = UIWindowEmailConfirmationRequired();
|
||||
await vi.waitFor(() => expect(win()).toHaveLength(2));
|
||||
vi.useFakeTimers();
|
||||
const first = win().get(1).querySelector('[data-number-code-input="0"]');
|
||||
first.value = '123456';
|
||||
first.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
|
||||
await expect(over).resolves.toBe(true);
|
||||
expect(ajax).toHaveBeenCalledWith(expect.objectContaining({ data: JSON.stringify({ code: '123456' }) }));
|
||||
expect(win()).toHaveLength(1);
|
||||
expect(await settled(under)).toBe(PENDING);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the server\'s error', { status: 429, responseJSON: { error: 'Too many requests.' } }, 'Too many requests.'],
|
||||
['an unknown error on a network failure', { status: 0 }, 'error_unknown_cause'],
|
||||
])('shows %s when a new code can\'t be sent', async (_label, xhr, shown) => {
|
||||
const ajax = vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => opts.error(xhr));
|
||||
await open();
|
||||
win().find('.send-conf-email').trigger('click');
|
||||
|
||||
expect(ajax).toHaveBeenCalledWith(expect.objectContaining({ url: 'https://api.puter.test/send-confirm-email' }));
|
||||
expect(win().find('.error').text()).toBe(shown);
|
||||
});
|
||||
|
||||
it('resolves false when it closes without a confirmation', async () => {
|
||||
const { result } = await open();
|
||||
win().close();
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('sends no code when it closes before the code is sent', async () => {
|
||||
const ajax = vi.spyOn(jQuery, 'ajax').mockImplementation(() => {});
|
||||
const { result } = await open();
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
win().close();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
|
||||
await expect(result).resolves.toBe(false);
|
||||
expect(ajax).not.toHaveBeenCalled();
|
||||
expect(window.user.email_confirmed).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['true when the code confirms the email', { email_confirmed: true }, true],
|
||||
['false when it doesn\'t', { email_confirmed: false }, false],
|
||||
])('waits for a code already sent when asked to close, and resolves %s', async (_label, answer, expected) => {
|
||||
let respond;
|
||||
vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => {
|
||||
respond = () => {
|
||||
opts.success(answer);
|
||||
opts.complete();
|
||||
};
|
||||
});
|
||||
const { result } = await open();
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
win().close();
|
||||
expect(win()).toHaveLength(1);
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
|
||||
respond();
|
||||
await expect(result).resolves.toBe(expected);
|
||||
expect(win()).toHaveLength(0);
|
||||
expect(window.user.email_confirmed).toBe(expected);
|
||||
});
|
||||
|
||||
it('closes once a code already sent fails, when asked to close meanwhile', async () => {
|
||||
let fail;
|
||||
vi.spyOn(jQuery, 'ajax').mockImplementation((opts) => {
|
||||
fail = () => {
|
||||
opts.error({ status: 0 });
|
||||
opts.complete();
|
||||
};
|
||||
});
|
||||
const { result } = await open();
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
win().close();
|
||||
fail();
|
||||
|
||||
await expect(result).resolves.toBe(false);
|
||||
expect(win()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('closes for a logout from its footer while a code is being checked', async () => {
|
||||
vi.spyOn(jQuery, 'ajax').mockImplementation(() => {});
|
||||
const { result } = await open({ logout_in_footer: true });
|
||||
vi.useFakeTimers();
|
||||
enterCode();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
vi.useRealTimers();
|
||||
win().find('.conf-email-log-out').trigger('click');
|
||||
|
||||
expect(win()).toHaveLength(0);
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
});
|
||||
|
||||
it('stays unsettled when a logout elsewhere closes it, so a gate doesn\'t reopen it', async () => {
|
||||
const { result } = await open();
|
||||
// As the logout handler leaves things when it closes every window.
|
||||
window.auth_token = null;
|
||||
win().close();
|
||||
expect(win()).toHaveLength(0);
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
});
|
||||
|
||||
it('stays unsettled on a logout from its footer, so a gate doesn\'t reopen it', async () => {
|
||||
const { result } = await open({ logout_in_footer: true });
|
||||
win().find('.conf-email-log-out').trigger('click');
|
||||
expect(window.logout).toHaveBeenCalledTimes(1);
|
||||
expect(win()).toHaveLength(0);
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
});
|
||||
});
|
||||
@@ -117,6 +117,12 @@ async function UIWindowSaveAccount (options) {
|
||||
},
|
||||
});
|
||||
|
||||
// One is already open, which UIWindow focused instead of opening this.
|
||||
if ( ! el_window ) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
$(el_window).find('.signup-btn').on('click', function (e) {
|
||||
// todo do some basic validation client-side
|
||||
|
||||
@@ -164,10 +170,15 @@ async function UIWindowSaveAccount (options) {
|
||||
|
||||
//close this window
|
||||
if ( data.user.requires_email_confirmation && !data.user.email_confirmed ) {
|
||||
// The code window brings its own backdrop; this
|
||||
// one under it would dim the page twice.
|
||||
const $backdrop = $(el_window).closest('.window-backdrop');
|
||||
$backdrop.css('visibility', 'hidden');
|
||||
let is_verified = await UIWindowEmailConfirmationRequired({
|
||||
stay_on_top: true,
|
||||
has_head: true,
|
||||
});
|
||||
$backdrop.css('visibility', '');
|
||||
resolve(is_verified);
|
||||
} else {
|
||||
resolve(true);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
// As the real window does, opens once: a second one focuses the first and returns nothing.
|
||||
vi.mock('./UIWindow.js', () => ({
|
||||
default: vi.fn(async (opts) => {
|
||||
if ( document.querySelector('.window-save-account') ) return undefined;
|
||||
const el = document.createElement('div');
|
||||
el.className = `window ${opts.window_class}`;
|
||||
el.innerHTML = opts.body_content;
|
||||
el.onClose = opts.on_close;
|
||||
document.body.append(el);
|
||||
return el;
|
||||
}),
|
||||
}));
|
||||
vi.mock('./UIWindowEmailConfirmationRequired.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.def = globalThis.def ?? (value => value);
|
||||
|
||||
const { default: UIWindowSaveAccount } = await import('./UIWindowSaveAccount.js');
|
||||
|
||||
const PENDING = Symbol('pending');
|
||||
const settled = (promise) => Promise.race([promise, new Promise((r) => setTimeout(() => r(PENDING), 0))]);
|
||||
const win = () => jQuery('.window-save-account');
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
globalThis.$ = jQuery;
|
||||
jQuery.fn.close = function () {
|
||||
this.each((_, el) => {
|
||||
el.remove();
|
||||
el.onClose?.();
|
||||
});
|
||||
return this;
|
||||
};
|
||||
globalThis.i18n = (key) => key;
|
||||
globalThis.html_encode = (value) => String(value);
|
||||
window.icons = {};
|
||||
window.uuidv4 = () => 'id-1';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete jQuery.fn.close;
|
||||
});
|
||||
|
||||
describe('UIWindowSaveAccount', () => {
|
||||
it('resolves false when it closes without saving', async () => {
|
||||
const result = UIWindowSaveAccount();
|
||||
await vi.waitFor(() => expect(win()).toHaveLength(1));
|
||||
win().close();
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('resolves false when one is already open, and leaves that one waiting', async () => {
|
||||
const first = UIWindowSaveAccount();
|
||||
await vi.waitFor(() => expect(win()).toHaveLength(1));
|
||||
|
||||
await expect(UIWindowSaveAccount()).resolves.toBe(false);
|
||||
expect(win()).toHaveLength(1);
|
||||
expect(await settled(first)).toBe(PENDING);
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,7 @@ import { appTileLink } from './UI/Dashboard/appLink.js';
|
||||
import { installAppIconFallback } from './helpers/appIcon.js';
|
||||
import { guestAppLaunchUrl, launchAppInTab } from './helpers/appTabLaunch.js';
|
||||
import { embedHostTheme, forceColorScheme } from './helpers/embedHostTheme.js';
|
||||
import { embedHostUser } from './helpers/embedHostUser.js';
|
||||
import { embedSession } from './helpers/embedSession.js';
|
||||
|
||||
window.$ = window.jQuery = jQuery;
|
||||
window.html_encode = value => encode(String(value ?? ''), { mode: 'nonAsciiPrintable' });
|
||||
@@ -104,56 +104,12 @@ function launchTile ({ appName, targetLink }) {
|
||||
.finally(() => launching.delete(appName));
|
||||
}
|
||||
|
||||
/**
|
||||
* The GUI session, from local storage or else the session cookie. Safari keys a
|
||||
* frame's local storage by the top-level origin, so under a sibling subdomain
|
||||
* the GUI's stored token is out of reach while its cookie is still sent.
|
||||
*/
|
||||
async function readSession () {
|
||||
let stored = null;
|
||||
try {
|
||||
stored = localStorage.getItem('auth_token_v2');
|
||||
} catch { /* Storage the browser refuses holds no session; the cookie may. */ }
|
||||
if ( stored ) return stored;
|
||||
const response = await fetch('/get-gui-token', { credentials: 'include' });
|
||||
// Only a 401 means there is no session; a rate limit or server error
|
||||
// must not pass a signed-in user off as signed out.
|
||||
if ( response.status === 401 ) return null;
|
||||
if ( ! response.ok ) throw new Error(`Session lookup responded ${response.status}`);
|
||||
return (await response.json())?.token || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The uuid of the user a GUI token belongs to, or null when the API refuses it.
|
||||
*/
|
||||
async function sessionUser (token) {
|
||||
const response = await fetch(new URL('/whoami', config.apiOrigin), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if ( response.status === 401 ) return null;
|
||||
if ( ! response.ok ) throw new Error(`Session check responded ${response.status}`);
|
||||
const uuid = (await response.json())?.uuid;
|
||||
return typeof uuid === 'string' ? uuid.toLowerCase() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The GUI session, only when it belongs to the user the host page names. A
|
||||
* host signed out, or signed in as someone else, gets the signed-out view.
|
||||
*/
|
||||
async function hostSession () {
|
||||
const hostUser = embedHostUser(window.location.hash);
|
||||
if ( ! hostUser ) return null;
|
||||
const token = await readSession();
|
||||
if ( ! token ) return null;
|
||||
return await sessionUser(token) === hostUser ? token : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signed in, the user's own apps through the SDK. Without a session, the
|
||||
* recommended apps the page was rendered with, and no SDK.
|
||||
*/
|
||||
async function mount () {
|
||||
window.auth_token = await hostSession();
|
||||
window.auth_token = (await embedSession(config.apiOrigin, window.location.hash))?.token ?? null;
|
||||
const guestApps = window.auth_token ? undefined : config.guestApps;
|
||||
if ( !window.auth_token && !guestApps?.length ) throw new Error('No apps to show without a session');
|
||||
|
||||
|
||||
@@ -2739,15 +2739,17 @@ input.myapps-group-name:focus {
|
||||
}
|
||||
}
|
||||
|
||||
/* In a popup that exists only for this dialog, the dialog is the page: a
|
||||
centered column, with the actions pinned to the bottom edge. */
|
||||
.custom-domain-fullpage {
|
||||
--cd-column: min(552px, 100% - 48px);
|
||||
/* In a popup that exists only to host one of these dialogs, the dialog is the
|
||||
page: a centered column, with the actions pinned to the bottom edge. */
|
||||
.app-feedback-fullpage {
|
||||
--afb-column: min(552px, 100% - 48px);
|
||||
padding: 0;
|
||||
align-items: stretch;
|
||||
background: var(--afb-bg);
|
||||
}
|
||||
.custom-domain-fullpage .custom-domain-modal {
|
||||
.app-feedback-fullpage .app-feedback-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: 100dvh;
|
||||
max-height: none;
|
||||
@@ -2758,39 +2760,39 @@ input.myapps-group-name:focus {
|
||||
padding-bottom: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.custom-domain-fullpage .app-feedback-x {
|
||||
.app-feedback-fullpage .app-feedback-x {
|
||||
display: none;
|
||||
}
|
||||
.custom-domain-fullpage .custom-domain-head {
|
||||
width: var(--cd-column);
|
||||
.app-feedback-fullpage .app-feedback-head {
|
||||
width: var(--afb-column);
|
||||
margin: 0 auto;
|
||||
padding: 28px 0 4px;
|
||||
}
|
||||
.custom-domain-fullpage .custom-domain-body {
|
||||
.app-feedback-fullpage .app-feedback-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
padding: 20px 0 0;
|
||||
}
|
||||
.custom-domain-fullpage .custom-domain-pane {
|
||||
.app-feedback-fullpage .app-feedback-pane {
|
||||
flex: 1 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.custom-domain-fullpage .custom-domain-pane > :not(.app-feedback-actions, .app-feedback-success-check, .custom-domain-state-icon) {
|
||||
.app-feedback-fullpage .app-feedback-pane > :not(.app-feedback-actions, .app-feedback-success-check, .custom-domain-state-icon) {
|
||||
box-sizing: border-box;
|
||||
width: var(--cd-column);
|
||||
width: var(--afb-column);
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
/* Keeps the actions off the content when it fills the page. */
|
||||
.custom-domain-fullpage .custom-domain-pane::after {
|
||||
.app-feedback-fullpage .app-feedback-pane::after {
|
||||
content: '';
|
||||
flex: 1 0 20px;
|
||||
order: 1;
|
||||
}
|
||||
.custom-domain-fullpage .app-feedback-actions {
|
||||
.app-feedback-fullpage .app-feedback-actions {
|
||||
order: 2;
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
@@ -2799,9 +2801,18 @@ input.myapps-group-name:focus {
|
||||
background: var(--afb-bg);
|
||||
border-top: 1px solid var(--afb-border);
|
||||
}
|
||||
.custom-domain-fullpage .custom-domain-state .app-feedback-actions {
|
||||
.app-feedback-fullpage .app-feedback-unavailable .app-feedback-actions,
|
||||
.app-feedback-fullpage .custom-domain-state .app-feedback-actions {
|
||||
justify-content: center;
|
||||
}
|
||||
/* The message box takes the spare height instead of the spacer. */
|
||||
.app-feedback-fullpage .app-feedback-form::after {
|
||||
flex-grow: 0;
|
||||
}
|
||||
.app-feedback-fullpage .app-feedback-message {
|
||||
flex: 1 0 160px;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
/* Add-an-app chooser (see showAddAppModal): the three ways to get an app, as
|
||||
rows in the same modal shell. min-width gives the two-line rows room without
|
||||
@@ -5246,7 +5257,9 @@ body.myapps-reordering .myapps-tile {
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-bottom: 30px;
|
||||
/* Ends above the footer, not under it, so a drop outline drawn on its
|
||||
edge shows all the way round. */
|
||||
margin-bottom: 30px;
|
||||
overflow-y: auto;
|
||||
touch-action: pan-y;
|
||||
}
|
||||
@@ -7026,7 +7039,7 @@ body.myapps-reordering .myapps-tile {
|
||||
}
|
||||
|
||||
.dashboard-section-files .files {
|
||||
padding-bottom: calc(30px + env(safe-area-inset-bottom, 0px));
|
||||
margin-bottom: calc(30px + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
|
||||
/* The grids keep their own padding and clear the footer with a margin,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/* Transparent, so the dialog's own scrim covers the framing page. */
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: transparent;
|
||||
font-family: "Inter", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
/* A scroll over the scrim must not scroll the framing page behind it. */
|
||||
html {
|
||||
overscroll-behavior: none;
|
||||
/* Matches the frame's, so it stays transparent and follows the OS theme. */
|
||||
color-scheme: light dark;
|
||||
}
|
||||
@@ -140,6 +140,21 @@ body {
|
||||
background-color: #ccccccbe !important;
|
||||
}
|
||||
|
||||
/* A popup framed over its whole page, such as the upgrade, shows the page
|
||||
around its own dialog. The root's color scheme matches the frame's, or the
|
||||
browser paints the frame opaque; the GUI inside keeps the light scheme it
|
||||
has everywhere else, so its form fields don't turn dark. */
|
||||
html.popup-frame-transparent,
|
||||
html.popup-frame-transparent body {
|
||||
background: transparent !important;
|
||||
}
|
||||
html.popup-frame-transparent {
|
||||
color-scheme: light dark;
|
||||
}
|
||||
html.popup-frame-transparent body {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.disable-user-select {
|
||||
cursor: default;
|
||||
-webkit-touch-callout: none !important;
|
||||
@@ -181,6 +196,20 @@ input[type=text], input[type=password], input[type=email], select {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
input[type=text], input[type=password], input[type=email], select {
|
||||
background-color: #2d2d2d;
|
||||
border: 1px solid #555;
|
||||
color: #e6e6e6;
|
||||
}
|
||||
|
||||
input[type=text]::placeholder,
|
||||
input[type=password]::placeholder,
|
||||
input[type=email]::placeholder {
|
||||
color: #999;
|
||||
}
|
||||
}
|
||||
|
||||
/* to prevent auto-zoom on input focus in mobile */
|
||||
.device-phone input[type=text], .device-phone input[type=password], .device-phone input[type=email], .device-phone select {
|
||||
font-size: 17px;
|
||||
@@ -1478,6 +1507,18 @@ span.header-sort-icon img {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* The file name shrinks so the buttons stay on one line, on screen, in a narrow dialog. */
|
||||
.window-filedialog-prompt > div {
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.window-filedialog-prompt .button-small {
|
||||
padding: 0 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.savefiledialog-filename {
|
||||
float: left;
|
||||
margin-right: 10px;
|
||||
@@ -1485,10 +1526,21 @@ span.header-sort-icon img {
|
||||
border-width: 1px !important;
|
||||
height: 31px;
|
||||
flex-grow: 1;
|
||||
min-width: 0;
|
||||
width: initial !important;
|
||||
}
|
||||
|
||||
/* In a narrow open dialog, the upload label gives way so its buttons stay whole. */
|
||||
.window-filedialog-upload-here + div {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.window-filedialog-upload-here {
|
||||
min-width: 0;
|
||||
margin-right: 10px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
opacity: 0.7;
|
||||
font-size: 14px;
|
||||
@@ -5169,11 +5221,16 @@ html.dark-mode .usage-table-fade-overlay {
|
||||
}
|
||||
|
||||
/* On a phone, units and cost keep every digit; the resource name is the
|
||||
column that gives way. */
|
||||
column that gives way, wrapping rather than cut off, since a touch screen
|
||||
has no hover to show the rest. */
|
||||
@media (max-width: 480px) {
|
||||
.dashboard-section-usage .driver-usage-details-content-table td:not(:first-child) {
|
||||
max-width: none;
|
||||
}
|
||||
.dashboard-section-usage .driver-usage-details-content-table td:first-child {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
.version {
|
||||
font-size: 9px;
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { chromium } from '@playwright/test';
|
||||
import express from 'express';
|
||||
import webpack from 'webpack';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
|
||||
let browser;
|
||||
let server;
|
||||
let directory;
|
||||
let origin;
|
||||
let hostOrigin;
|
||||
let port;
|
||||
const requests = [];
|
||||
const guiRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||
const sessionToken = 'feedback-embed-test-session';
|
||||
const unconfirmedToken = 'feedback-embed-test-unconfirmed';
|
||||
const sessionUser = '0b1c9a52-3f0e-4c7a-9a65-2f6d1e8b7c40';
|
||||
const unconfirmedUser = '1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f';
|
||||
const otherUser = '7d2e4f10-8a3b-4c5d-9e6f-0a1b2c3d4e5f';
|
||||
|
||||
beforeAll(async () => {
|
||||
directory = await mkdtemp(path.join(tmpdir(), 'puter-feedback-embed-'));
|
||||
await new Promise((resolve, reject) => {
|
||||
const compiler = webpack({
|
||||
mode: 'development',
|
||||
entry: { 'feedback-embed': path.join(guiRoot, 'src/feedbackEmbed.js') },
|
||||
output: { path: directory, filename: '[name].min.js' },
|
||||
module: { rules: [{ test: /jquery-3\.6\.1\.min\.js$/, type: 'javascript/auto' }] },
|
||||
});
|
||||
compiler.run((error, stats) => compiler.close(closeError => {
|
||||
if ( error || closeError ) return reject(error || closeError);
|
||||
if ( stats.hasErrors() ) return reject(new Error(stats.toString()));
|
||||
resolve();
|
||||
}));
|
||||
});
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, res, next) => {
|
||||
requests.push({ path: req.path, query: req.query, body: req.body, auth: req.headers.authorization });
|
||||
next();
|
||||
});
|
||||
app.use('/dist', express.static(directory));
|
||||
app.use('/css', express.static(path.join(guiRoot, 'src/css')));
|
||||
app.get('/get-gui-token', (_req, res) => res.sendStatus(401));
|
||||
const whoamiByToken = {
|
||||
[sessionToken]: { uuid: sessionUser, username: 'session-user', email: '[email protected]', email_confirmed: true },
|
||||
[unconfirmedToken]: {
|
||||
uuid: unconfirmedUser, username: 'new-user', email_confirmed: false, requires_email_confirmation: true,
|
||||
},
|
||||
};
|
||||
app.get('/whoami', (req, res) => {
|
||||
const user = whoamiByToken[req.headers.authorization?.replace(/^Bearer /, '')];
|
||||
if ( ! user ) return res.sendStatus(401);
|
||||
res.json(user);
|
||||
});
|
||||
app.get('/app-feedback/target', (req, res) => {
|
||||
if ( req.headers.authorization !== `Bearer ${sessionToken}` ) return res.sendStatus(401);
|
||||
if ( req.query.origin !== hostOrigin ) return res.json({ enabled: false });
|
||||
res.json({ enabled: true, app: { name: 'notes', title: 'Notes' } });
|
||||
});
|
||||
app.post('/app-feedback', (req, res) => {
|
||||
if ( req.headers.authorization !== `Bearer ${sessionToken}` ) return res.sendStatus(401);
|
||||
res.json({});
|
||||
});
|
||||
// A first-party page that frames the dialog as puter.js does, recording what the embed tells it.
|
||||
app.get('/host', (req, res) => res.send(`<!DOCTYPE html><html><body style="margin:0;background:rgb(255,0,0)">
|
||||
<script>
|
||||
window.received = [];
|
||||
addEventListener('message', (e) => {
|
||||
if ( e.origin === '${origin}' ) window.received.push(e.data);
|
||||
});
|
||||
</script>
|
||||
<iframe referrerpolicy="origin" title="Send feedback" src="${origin}/embed/feedback#user=${req.query.user ?? ''}"
|
||||
style="display:block;border:0;width:100vw;height:100vh;color-scheme:light dark"></iframe>
|
||||
<div style="height:3000px"></div>
|
||||
</body></html>`));
|
||||
app.get('/embed/feedback', (_req, res) => {
|
||||
res.setHeader('Content-Security-Policy', `frame-ancestors 'self' ${hostOrigin}`);
|
||||
res.send(`<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="/css/normalize.css"><link rel="stylesheet" href="/css/dashboard.css">
|
||||
<link rel="stylesheet" href="/css/feedback-embed.css"></head><body>
|
||||
<main id="feedback-embed"></main>
|
||||
<script type="application/json" id="feedback-embed-config">${JSON.stringify({ apiOrigin: origin, hostOrigin })}</script>
|
||||
<script defer src="/dist/feedback-embed.min.js"></script></body></html>`);
|
||||
});
|
||||
server = await new Promise(resolve => {
|
||||
const listener = app.listen(0, '127.0.0.1', () => resolve(listener));
|
||||
});
|
||||
port = server.address().port;
|
||||
origin = `http://puter.localhost:${port}`;
|
||||
hostOrigin = `http://notes.puter.localhost:${port}`;
|
||||
browser = await chromium.launch();
|
||||
}, 60000);
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close();
|
||||
if ( server ) await new Promise(resolve => server.close(resolve));
|
||||
if ( directory ) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** A browser whose GUI origin is signed in with `token`, if any. */
|
||||
const signedIn = (token, options = {}) => browser.newContext({ ...options, storageState: {
|
||||
cookies: [],
|
||||
origins: token ? [{ origin, localStorage: [{ name: 'auth_token_v2', value: token }] }] : [],
|
||||
} });
|
||||
|
||||
const received = page => page.evaluate(() => window.received);
|
||||
|
||||
/** The [r, g, b] of one pixel of the page, from a screenshot. */
|
||||
const pixel = async (page, x, y) => {
|
||||
const png = await page.screenshot({ clip: { x, y, width: 1, height: 1 }, animations: 'disabled' });
|
||||
const data = [];
|
||||
for ( let at = 8; at < png.length; ) {
|
||||
const length = png.readUInt32BE(at);
|
||||
if ( png.toString('ascii', at + 4, at + 8) === 'IDAT' ) data.push(png.subarray(at + 8, at + 8 + length));
|
||||
at += 12 + length;
|
||||
}
|
||||
// One pixel: a filter byte, then its channels unchanged.
|
||||
return [...inflateSync(Buffer.concat(data)).subarray(1, 4)];
|
||||
};
|
||||
|
||||
describe('feedback embed', () => {
|
||||
it('sends feedback for the framing page as the user it names, then tells it', async () => {
|
||||
const context = await signedIn(sessionToken);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
requests.length = 0;
|
||||
await page.goto(`${hostOrigin}/host?user=${sessionUser}`);
|
||||
const frame = page.frameLocator('iframe');
|
||||
await frame.locator('.app-feedback-form').waitFor();
|
||||
expect(await frame.locator('.app-feedback-target-title').textContent()).toBe('Notes');
|
||||
expect(await received(page)).toEqual([
|
||||
{ msg: 'feedbackEmbed', state: 'loading' },
|
||||
{ msg: 'feedbackEmbed', state: 'ready' },
|
||||
]);
|
||||
// The page behind shows through around the dialog, under its scrim.
|
||||
expect(await frame.locator('body').evaluate(el => getComputedStyle(el).backgroundColor)).toBe('rgba(0, 0, 0, 0)');
|
||||
await page.screenshot({ path: path.join(tmpdir(), 'puter-feedback-embed.png'), animations: 'disabled' });
|
||||
|
||||
await frame.locator('.app-feedback-message').fill('Love the new editor');
|
||||
await frame.locator('.app-feedback-send-btn').click();
|
||||
await frame.locator('.app-feedback-success').waitFor();
|
||||
await page.waitForFunction(() => window.received.some(m => m.msg === 'feedbackDialogClosed'));
|
||||
expect((await received(page)).at(-1)).toEqual({ msg: 'feedbackDialogClosed', sent: true });
|
||||
expect(await frame.locator('.app-feedback-overlay').count()).toBe(0);
|
||||
|
||||
const submit = requests.find(req => req.path === '/app-feedback');
|
||||
expect(submit.body).toEqual({ origin: hostOrigin, message: 'Love the new editor', context: 'web' });
|
||||
expect(submit.auth).toBe(`Bearer ${sessionToken}`);
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('answers not sent when the user dismisses it', async () => {
|
||||
const context = await signedIn(sessionToken);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${hostOrigin}/host?user=${sessionUser}`);
|
||||
const frame = page.frameLocator('iframe');
|
||||
await frame.locator('.app-feedback-form').waitFor();
|
||||
await frame.locator('.app-feedback-message').press('Escape');
|
||||
await page.waitForFunction(() => window.received.some(m => m.msg === 'feedbackDialogClosed'));
|
||||
expect((await received(page)).at(-1)).toEqual({ msg: 'feedbackDialogClosed', sent: false });
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it.each(['light', 'dark'])('lets the page show through under the scrim in %s mode', async (colorScheme) => {
|
||||
const context = await signedIn(sessionToken, { colorScheme });
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${hostOrigin}/host?user=${sessionUser}`);
|
||||
const frame = page.frameLocator('iframe');
|
||||
await frame.locator('.app-feedback-form').waitFor();
|
||||
expect(await frame.locator('body').evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches))
|
||||
.toBe(colorScheme === 'dark');
|
||||
await page.waitForTimeout(300);
|
||||
// The red page, dimmed by the scrim, rather than an opaque frame.
|
||||
const [red, green, blue] = await pixel(page, 10, 10);
|
||||
expect(red).toBeGreaterThan(green + 40);
|
||||
expect(green).toBe(blue);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('keeps the page behind from scrolling under the scrim', async () => {
|
||||
const context = await signedIn(sessionToken);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`${hostOrigin}/host?user=${sessionUser}`);
|
||||
await page.frameLocator('iframe').locator('.app-feedback-form').waitFor();
|
||||
await page.mouse.move(10, 10);
|
||||
await page.mouse.wheel(0, 600);
|
||||
await page.waitForTimeout(300);
|
||||
expect(await page.evaluate(() => window.scrollY)).toBe(0);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it.each([
|
||||
['no Puter session', null, sessionUser],
|
||||
['a session for another user', sessionToken, otherUser],
|
||||
['a host that names no user', sessionToken, ''],
|
||||
['an email still to confirm', unconfirmedToken, unconfirmedUser],
|
||||
])('tells the host it is unavailable with %s', async (_label, token, user) => {
|
||||
const context = await signedIn(token);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
requests.length = 0;
|
||||
await page.goto(`${hostOrigin}/host?user=${user}`);
|
||||
await page.waitForFunction(() => window.received.length >= 2);
|
||||
expect(await received(page)).toEqual([
|
||||
{ msg: 'feedbackEmbed', state: 'loading' },
|
||||
{ msg: 'feedbackEmbed', state: 'unavailable' },
|
||||
]);
|
||||
expect(await page.frameLocator('iframe').locator('.app-feedback-overlay').count()).toBe(0);
|
||||
expect(requests.some(req => req.path.startsWith('/app-feedback'))).toBe(false);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('does nothing when opened on its own', async () => {
|
||||
const context = await signedIn(sessionToken);
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
requests.length = 0;
|
||||
await page.goto(`${origin}/embed/feedback#user=${sessionUser}`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
expect(await page.locator('.app-feedback-overlay').count()).toBe(0);
|
||||
expect(requests.some(req => req.path === '/whoami')).toBe(false);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
import { encode } from 'html-entities';
|
||||
import { loadLocale } from './i18n/embedI18n.js';
|
||||
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
|
||||
import { embedSession } from './helpers/embedSession.js';
|
||||
|
||||
window.$ = window.jQuery = jQuery;
|
||||
window.html_encode = value => encode(String(value ?? ''), { mode: 'nonAsciiPrintable' });
|
||||
|
||||
const config = JSON.parse(document.querySelector('#feedback-embed-config').textContent);
|
||||
window.api_origin = config.apiOrigin;
|
||||
window.locale = 'en';
|
||||
try {
|
||||
window.locale = JSON.parse(localStorage.getItem('user_preferences') || '{}')?.language || 'en';
|
||||
} catch { /* Corrupt preferences must not prevent sending feedback. */ }
|
||||
const localeReady = loadLocale(window.locale);
|
||||
|
||||
/** Answers only the page frame-ancestors pinned, which the feedback is for. */
|
||||
const tellHost = (data) => window.parent.postMessage(data, config.hostOrigin);
|
||||
|
||||
/** Resolves once the dialog's overlay has left the page, after its success pane and exit. */
|
||||
const overlayGone = () => new Promise((resolve) => {
|
||||
const gone = () => !document.querySelector('.app-feedback-overlay');
|
||||
if ( gone() ) return resolve();
|
||||
const observer = new MutationObserver(() => {
|
||||
if ( ! gone() ) return;
|
||||
observer.disconnect();
|
||||
resolve();
|
||||
});
|
||||
observer.observe(document.body, { childList: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the app feedback dialog for the framing page, as the signed-in user it
|
||||
* names. Without that user's session, or with an email still to confirm, the
|
||||
* host is told the embed is unavailable and uses the popup, which can sign in.
|
||||
*/
|
||||
async function run () {
|
||||
tellHost({ msg: 'feedbackEmbed', state: 'loading' });
|
||||
let session = null;
|
||||
try {
|
||||
session = await embedSession(config.apiOrigin, window.location.hash);
|
||||
} catch (e) {
|
||||
console.error('feedback embed: session check failed', e);
|
||||
}
|
||||
const user = session?.user;
|
||||
if ( !user || (user.requires_email_confirmation && !user.email_confirmed) ) {
|
||||
tellHost({ msg: 'feedbackEmbed', state: 'unavailable' });
|
||||
return;
|
||||
}
|
||||
window.auth_token = session.token;
|
||||
window.user = user;
|
||||
await localeReady;
|
||||
|
||||
tellHost({ msg: 'feedbackEmbed', state: 'ready' });
|
||||
let sent = false;
|
||||
try {
|
||||
sent = await UIWindowAppFeedback({ origin: config.hostOrigin, source: 'web' });
|
||||
await overlayGone();
|
||||
} catch (e) {
|
||||
console.error('feedback embed: dialog failed', e);
|
||||
}
|
||||
tellHost({ msg: 'feedbackDialogClosed', sent: sent === true });
|
||||
}
|
||||
|
||||
// Opened on its own, there is no page to send feedback for or answer.
|
||||
if ( config.hostOrigin && window.parent !== window ) run();
|
||||
@@ -224,10 +224,11 @@ window.suggest_apps_for_fsentry = async (options) => {
|
||||
*/
|
||||
window.byte_format = (bytes) => {
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
|
||||
if ( bytes === 0 ) return '0 Byte';
|
||||
let i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
if ( i < 0 ) i = 0;
|
||||
if ( ! (i > 0) ) i = 0;
|
||||
if ( i >= sizes.length ) i = sizes.length - 1;
|
||||
// Whole bytes have no fraction: "0 Bytes", "1 Byte", "512 Bytes".
|
||||
if ( i === 0 ) return `${bytes} ${bytes === 1 ? 'Byte' : 'Bytes'}`;
|
||||
return `${(bytes / Math.pow(1024, i)).toFixed(2) } ${ sizes[i]}`;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { embedHostUser } from './embedHostUser.js';
|
||||
|
||||
/**
|
||||
* @typedef {Object} EmbedSession
|
||||
* @property {string} token - the GUI session's token
|
||||
* @property {Record<string, unknown>} user - `/whoami` for that token
|
||||
*/
|
||||
|
||||
/**
|
||||
* The GUI session, from local storage or else the session cookie. Safari keys a
|
||||
* frame's local storage by the top-level origin, so under a sibling subdomain
|
||||
* the GUI's stored token is out of reach while its cookie is still sent.
|
||||
*
|
||||
* @returns {Promise<string | null>}
|
||||
*/
|
||||
async function readSession () {
|
||||
let stored = null;
|
||||
try {
|
||||
stored = localStorage.getItem('auth_token_v2');
|
||||
} catch { /* Storage the browser refuses holds no session; the cookie may. */ }
|
||||
if ( stored ) return stored;
|
||||
const response = await fetch('/get-gui-token', { credentials: 'include' });
|
||||
// Only a 401 means there is no session; a rate limit or server error
|
||||
// must not pass a signed-in user off as signed out.
|
||||
if ( response.status === 401 ) return null;
|
||||
if ( ! response.ok ) throw new Error(`Session lookup responded ${response.status}`);
|
||||
return (await response.json())?.token || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `/whoami` for a GUI token, or null when the API refuses it.
|
||||
*
|
||||
* @param {string} token
|
||||
* @param {string} apiOrigin
|
||||
* @returns {Promise<Record<string, unknown> | null>}
|
||||
*/
|
||||
async function whoami (token, apiOrigin) {
|
||||
const response = await fetch(new URL('/whoami', apiOrigin), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if ( response.status === 401 ) return null;
|
||||
if ( ! response.ok ) throw new Error(`Session check responded ${response.status}`);
|
||||
const user = await response.json();
|
||||
return user && typeof user === 'object' ? user : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The GUI session, only when it belongs to the user the embedding page names
|
||||
* in its `#user=<uuid>` fragment. A host signed out, or signed in as someone
|
||||
* else, gets null. Rejects when the session can't be checked.
|
||||
*
|
||||
* @param {string} apiOrigin
|
||||
* @param {string} hash - `location.hash`
|
||||
* @returns {Promise<EmbedSession | null>}
|
||||
*/
|
||||
export async function embedSession (apiOrigin, hash) {
|
||||
const hostUser = embedHostUser(hash);
|
||||
if ( ! hostUser ) return null;
|
||||
const token = await readSession();
|
||||
if ( ! token ) return null;
|
||||
const user = await whoami(token, apiOrigin);
|
||||
const uuid = typeof user?.uuid === 'string' ? user.uuid.toLowerCase() : null;
|
||||
return uuid === hostUser ? { token, user } : null;
|
||||
}
|
||||
@@ -17,8 +17,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindowSaveAccount from '../UI/UIWindowSaveAccount.js';
|
||||
import UIWindowEmailConfirmationRequired from '../UI/UIWindowEmailConfirmationRequired.js';
|
||||
import ensureConfirmedEmail from './ensureConfirmedEmail.js';
|
||||
|
||||
/**
|
||||
* Walks a temporary account through saving itself, and an unconfirmed one
|
||||
@@ -30,22 +29,7 @@ import UIWindowEmailConfirmationRequired from '../UI/UIWindowEmailConfirmationRe
|
||||
*/
|
||||
const ensure_can_publish = async function (required) {
|
||||
if ( ! required ) return true;
|
||||
if ( window.user.is_temp && ! await UIWindowSaveAccount({
|
||||
send_confirmation_code: true,
|
||||
message: i18n('save_account_to_publish'),
|
||||
window_options: {
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
},
|
||||
}) ) {
|
||||
return false;
|
||||
}
|
||||
// Saving refreshes window.user; a deployment that doesn't confirm at
|
||||
// signup leaves the new account unconfirmed, and it still has to confirm.
|
||||
if ( ! window.user.email_confirmed ) {
|
||||
return !! await UIWindowEmailConfirmationRequired();
|
||||
}
|
||||
return true;
|
||||
return ensureConfirmedEmail(i18n('save_account_to_publish'));
|
||||
};
|
||||
|
||||
export default ensure_can_publish;
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindowSaveAccount from '../UI/UIWindowSaveAccount.js';
|
||||
import UIWindowEmailConfirmationRequired from '../UI/UIWindowEmailConfirmationRequired.js';
|
||||
|
||||
// The walk-through showing, which a call made meanwhile joins.
|
||||
let showing = null;
|
||||
|
||||
const walkThrough = async (message, window_options) => {
|
||||
if ( window.user.is_temp && ! await UIWindowSaveAccount({
|
||||
send_confirmation_code: true,
|
||||
message,
|
||||
window_options: {
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
...window_options,
|
||||
},
|
||||
}) ) {
|
||||
return false;
|
||||
}
|
||||
// Saving refreshes window.user; a deployment that doesn't confirm at
|
||||
// signup leaves the new account unconfirmed, and it still has to confirm.
|
||||
if ( ! window.user.email_confirmed ) {
|
||||
return !! await UIWindowEmailConfirmationRequired({ window_options });
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walks a temporary account through saving itself, and an unconfirmed one
|
||||
* through confirming its email, showing each window at most once. A call made
|
||||
* while the windows show settles with them, without opening its own.
|
||||
*
|
||||
* @param {string} message - What the save-account window says to a temporary account.
|
||||
* @param {Record<string, unknown>} [window_options] - Passed to both windows, such as
|
||||
* `stay_on_top` to show them above an app.
|
||||
* @returns {Promise<boolean>} Whether the email is confirmed; false if the user backed out of either step.
|
||||
*/
|
||||
const ensureConfirmedEmail = (message, window_options = {}) => {
|
||||
showing ??= walkThrough(message, window_options).finally(() => {
|
||||
showing = null;
|
||||
});
|
||||
return showing;
|
||||
};
|
||||
|
||||
export default ensureConfirmedEmail;
|
||||
@@ -0,0 +1,133 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../UI/UIWindowSaveAccount.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../UI/UIWindowEmailConfirmationRequired.js', () => ({ default: vi.fn() }));
|
||||
|
||||
const { default: ensureConfirmedEmail } = await import('./ensureConfirmedEmail.js');
|
||||
const { default: UIWindowSaveAccount } = await import('../UI/UIWindowSaveAccount.js');
|
||||
const { default: UIWindowEmailConfirmationRequired } = await import('../UI/UIWindowEmailConfirmationRequired.js');
|
||||
|
||||
beforeEach(() => {
|
||||
UIWindowSaveAccount.mockReset();
|
||||
UIWindowEmailConfirmationRequired.mockReset();
|
||||
});
|
||||
|
||||
describe('ensureConfirmedEmail', () => {
|
||||
it('shows nothing for a confirmed email', async () => {
|
||||
window.user = { is_temp: false, email_confirmed: true };
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(true);
|
||||
expect(UIWindowSaveAccount).not.toHaveBeenCalled();
|
||||
expect(UIWindowEmailConfirmationRequired).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([true, false])('asks an unconfirmed email for its code once, and answers %s as it does', async (answer) => {
|
||||
window.user = { is_temp: false, email_confirmed: false };
|
||||
UIWindowEmailConfirmationRequired.mockResolvedValueOnce(answer);
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(answer);
|
||||
expect(UIWindowEmailConfirmationRequired).toHaveBeenCalledTimes(1);
|
||||
expect(UIWindowSaveAccount).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('has a temporary account saved first, with the message given', async () => {
|
||||
window.user = { is_temp: true };
|
||||
UIWindowSaveAccount.mockResolvedValueOnce(false);
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(false);
|
||||
expect(UIWindowSaveAccount).toHaveBeenCalledWith(expect.objectContaining({
|
||||
message: 'save it',
|
||||
send_confirmation_code: true,
|
||||
}));
|
||||
expect(UIWindowEmailConfirmationRequired).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes the window options to both windows', async () => {
|
||||
window.user = { is_temp: true };
|
||||
UIWindowSaveAccount.mockImplementationOnce(async () => {
|
||||
window.user = { is_temp: false, email_confirmed: false };
|
||||
return true;
|
||||
});
|
||||
UIWindowEmailConfirmationRequired.mockResolvedValueOnce(true);
|
||||
await ensureConfirmedEmail('save it', { stay_on_top: true });
|
||||
expect(UIWindowSaveAccount.mock.calls[0][0].window_options).toEqual({
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
stay_on_top: true,
|
||||
});
|
||||
expect(UIWindowEmailConfirmationRequired).toHaveBeenCalledWith({ window_options: { stay_on_top: true } });
|
||||
});
|
||||
|
||||
it('asks no code again from an account that confirmed it while saving', async () => {
|
||||
window.user = { is_temp: true };
|
||||
// Saving asked for the code, which marks window.user confirmed.
|
||||
UIWindowSaveAccount.mockImplementationOnce(async () => {
|
||||
window.user = { is_temp: false, email_confirmed: true };
|
||||
return true;
|
||||
});
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(true);
|
||||
expect(UIWindowEmailConfirmationRequired).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks a just-saved account for its code when saving left it unconfirmed', async () => {
|
||||
window.user = { is_temp: true };
|
||||
UIWindowSaveAccount.mockImplementationOnce(async () => {
|
||||
window.user = { is_temp: false, email_confirmed: false };
|
||||
return true;
|
||||
});
|
||||
UIWindowEmailConfirmationRequired.mockResolvedValueOnce(true);
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(true);
|
||||
expect(UIWindowEmailConfirmationRequired).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('answers a call made while the code window shows with that window, without a second one', async () => {
|
||||
window.user = { is_temp: false, email_confirmed: false };
|
||||
let answer;
|
||||
UIWindowEmailConfirmationRequired.mockReturnValueOnce(new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
}));
|
||||
const first = ensureConfirmedEmail('save it');
|
||||
const second = ensureConfirmedEmail('save it');
|
||||
await Promise.resolve();
|
||||
expect(UIWindowEmailConfirmationRequired).toHaveBeenCalledTimes(1);
|
||||
answer(true);
|
||||
expect(await Promise.all([first, second])).toEqual([true, true]);
|
||||
});
|
||||
|
||||
it('answers a call made while the save-account window shows with that window', async () => {
|
||||
window.user = { is_temp: true };
|
||||
let answer;
|
||||
UIWindowSaveAccount.mockReturnValueOnce(new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
}));
|
||||
const first = ensureConfirmedEmail('save it');
|
||||
const second = ensureConfirmedEmail('save it');
|
||||
expect(UIWindowSaveAccount).toHaveBeenCalledTimes(1);
|
||||
answer(false);
|
||||
expect(await Promise.all([first, second])).toEqual([false, false]);
|
||||
});
|
||||
|
||||
it('opens a new window for a call made after the last one answered', async () => {
|
||||
window.user = { is_temp: false, email_confirmed: false };
|
||||
UIWindowEmailConfirmationRequired.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(false);
|
||||
expect(await ensureConfirmedEmail('save it')).toBe(true);
|
||||
expect(UIWindowEmailConfirmationRequired).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -232,7 +232,7 @@ Please try recreating the link.`);
|
||||
// LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
|
||||
// this is literally put in here to support Polotno's legacy code
|
||||
...(!Array.isArray(res) && res),
|
||||
}, '*');
|
||||
}, window.openerOrigin);
|
||||
|
||||
window.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A GUI popup that a first-party page shows in a frame instead of a window,
|
||||
* served at `/embed/<action>`. It runs the popup boot unchanged: the framing
|
||||
* page stands in for `window.opener`, and closing asks it to remove the frame.
|
||||
*/
|
||||
|
||||
/** Popup actions a first-party page can frame. */
|
||||
export const FRAMED_POPUP_ACTIONS = new Set([
|
||||
'sign-in',
|
||||
'show-open-file-picker',
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'request-email-confirmation',
|
||||
]);
|
||||
|
||||
// Actions a frame shows only for the user the framing page is signed in as.
|
||||
const HOST_USER_ACTIONS = new Set([
|
||||
'show-open-file-picker',
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'request-email-confirmation',
|
||||
]);
|
||||
|
||||
// Actions framed over the whole page with no box, which their own dialog's
|
||||
// scrim covers.
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'request-email-confirmation']);
|
||||
|
||||
const UPGRADE_REASONS = new Set(['funds', 'subscription', 'storage']);
|
||||
const UPGRADE_METHOD_MAX = 200;
|
||||
|
||||
// Modal UI the upgrade dialog and the GUI's windows show. Once some has shown
|
||||
// and all of it has been gone this long, the dialog closed without reporting
|
||||
// it, and the frame mustn't be left covering the page.
|
||||
const UPGRADE_MODAL_UI = '.window, [aria-modal="true"]';
|
||||
const UPGRADE_GONE_MS = 500;
|
||||
// How long a hidden frame waits for the page to show it before opening anyway.
|
||||
const FRAME_SIZE_TIMEOUT_MS = 1000;
|
||||
// A focus() the frame ignored is retried this often, this many times.
|
||||
const FOCUS_RETRY_MS = 50;
|
||||
const FOCUS_RETRIES = 20;
|
||||
|
||||
/** Lifecycle messages to the framing page carry this as `msg`. */
|
||||
export const POPUP_FRAME_MSG = 'puterPopupFrame';
|
||||
|
||||
// The popup's query parameters a framing page may pass, in the fragment.
|
||||
const FRAGMENT_PARAMS = ['msg_id', 'options', 'request_auth'];
|
||||
|
||||
// The account checks a sign-in can show (email, phone, card), and the
|
||||
// save-account window an email confirmation shows a temporary account first,
|
||||
// which are windows rather than auth screens.
|
||||
const ACCOUNT_CHECK_WINDOWS = '.window-confirm-email-using-code, .window-confirm-phone-using-code, .window-card-verification, .window-save-account';
|
||||
|
||||
// What a framed popup shows first; until one is on the page the framing page
|
||||
// keeps the frame hidden behind its loading scrim.
|
||||
const VISIBLE_UI = '.window, .dashboard-dialog-overlay, .captcha-modal';
|
||||
|
||||
/**
|
||||
* The action a `/embed/<action>` path frames, or null for any other path.
|
||||
*
|
||||
* @param {string} pathname
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export const framedPopupAction = (pathname) => {
|
||||
const match = /^\/embed\/([a-z-]+)\/?$/.exec(String(pathname ?? ''));
|
||||
return match && FRAMED_POPUP_ACTIONS.has(match[1]) ? match[1] : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a framed `action` serves only the framing page's own user, named in
|
||||
* the fragment as `user`.
|
||||
*
|
||||
* @param {string | null | undefined} action
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const framesHostUser = (action) => HOST_USER_ACTIONS.has(action);
|
||||
|
||||
/**
|
||||
* Whether a framed `action` lets the framing page show through around its
|
||||
* dialog.
|
||||
*
|
||||
* @param {string | null | undefined} action
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const isTransparentPopupFrame = (action) => TRANSPARENT_ACTIONS.has(action);
|
||||
|
||||
/**
|
||||
* The popup parameters the framing page put in the fragment, and no others.
|
||||
* The route refuses a query string, so nothing else reaches the boot.
|
||||
*
|
||||
* @param {string} hash - `location.hash`
|
||||
* @returns {URLSearchParams}
|
||||
*/
|
||||
export const framedPopupParams = (hash) => {
|
||||
const given = new URLSearchParams(String(hash ?? '').replace(/^#/, ''));
|
||||
const params = new URLSearchParams();
|
||||
for ( const key of FRAGMENT_PARAMS ) {
|
||||
if ( given.has(key) ) params.set(key, given.get(key));
|
||||
}
|
||||
return params;
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts a framed popup in `win`: the framing page, at the origin the server
|
||||
* pinned with frame-ancestors, becomes `opener`, `close()` asks it to remove
|
||||
* the frame, and it hears `ready` once the popup shows something. Returns a
|
||||
* function that sends it a lifecycle state, with any fields that go with it,
|
||||
* or null when there is no framing page to answer (opened on its own, or
|
||||
* framed by a page the server refused).
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {string | null | undefined} hostOrigin - `gui_params.embed_host_origin`
|
||||
* @returns {((state: 'loading' | 'ready' | 'unavailable' | 'closed' | 'provider', fields?: Record<string, unknown>) => void) | null}
|
||||
*/
|
||||
export const startPopupFrame = (win, hostOrigin) => {
|
||||
if ( ! hostOrigin || win.parent === win ) return null;
|
||||
const parent = win.parent;
|
||||
if ( isTransparentPopupFrame(framedPopupAction(win.location?.pathname)) ) {
|
||||
win.document.documentElement.classList.add('popup-frame-transparent');
|
||||
}
|
||||
const tell = (state, fields = {}) =>
|
||||
parent.postMessage({ ...fields, msg: POPUP_FRAME_MSG, state }, hostOrigin);
|
||||
|
||||
win.opener = parent;
|
||||
win.close = () => tell('closed');
|
||||
// The popup closes with `window.open('', '_self').close()` as well, which
|
||||
// must reach the `close` above rather than navigate the frame.
|
||||
const open = win.open.bind(win);
|
||||
win.open = (url, target, ...rest) =>
|
||||
url === '' && target === '_self' ? win : open(url, target, ...rest);
|
||||
|
||||
const announceReady = () => {
|
||||
if ( ! win.document.querySelector(VISIBLE_UI) ) return false;
|
||||
tell('ready');
|
||||
return true;
|
||||
};
|
||||
const observer = new win.MutationObserver(() => {
|
||||
if ( announceReady() ) observer.disconnect();
|
||||
});
|
||||
observer.observe(win.document.body, { childList: true, subtree: true });
|
||||
|
||||
tell('loading');
|
||||
return tell;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gives a framed popup's latest focus() back whenever the frame gains focus
|
||||
* with nothing focused, until the user presses a key or the pointer in it. A
|
||||
* cross-origin frame can't take focus until the framing page focuses it, which
|
||||
* also resets it, so a save picker's file name would start unfocused.
|
||||
* Firefox and WebKit also ignore a focus() for a moment after the page shows
|
||||
* the frame, without a `focus` event after it, so one that didn't take is
|
||||
* retried for a while.
|
||||
*
|
||||
* @param {Window} win
|
||||
*/
|
||||
export const focusOnFrameFocus = (win) => {
|
||||
const focus = win.HTMLElement.prototype.focus;
|
||||
let latest = null;
|
||||
let retryTimer = null;
|
||||
let retries = 0;
|
||||
// Whether the latest focus() still needs giving back.
|
||||
const pending = () => {
|
||||
const active = win.document.activeElement;
|
||||
return !!latest?.el.isConnected && (!active || active === win.document.body);
|
||||
};
|
||||
const giveBack = () => {
|
||||
if ( pending() ) focus.apply(latest.el, latest.args);
|
||||
};
|
||||
const retry = () => {
|
||||
retryTimer = null;
|
||||
giveBack();
|
||||
if ( pending() && ++retries < FOCUS_RETRIES ) retryTimer = setTimeout(retry, FOCUS_RETRY_MS);
|
||||
};
|
||||
win.HTMLElement.prototype.focus = function (...args) {
|
||||
latest = { el: this, args };
|
||||
const result = focus.apply(this, args);
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = null;
|
||||
retries = 0;
|
||||
if ( pending() ) retryTimer = setTimeout(retry, FOCUS_RETRY_MS);
|
||||
return result;
|
||||
};
|
||||
const forget = () => {
|
||||
latest = null;
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = null;
|
||||
win.HTMLElement.prototype.focus = focus;
|
||||
};
|
||||
win.addEventListener('pointerdown', forget, { capture: true, once: true });
|
||||
win.addEventListener('keydown', forget, { capture: true, once: true });
|
||||
win.addEventListener('focus', giveBack);
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes a framed sign-in or email confirmation on Escape in one of its
|
||||
* account windows, as Escape on the sign-in's auth screens does. Those
|
||||
* screens handle Escape themselves; the account windows don't.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {(accountWindow: Element) => void} [close] - closes the account window
|
||||
* Escape was pressed in, when its own closing is what answers the frame;
|
||||
* without it the frame closes
|
||||
*/
|
||||
export const closeAccountChecksOnEscape = (win, close = () => win.close()) => {
|
||||
win.document.addEventListener('keydown', (e) => {
|
||||
// Safari sends the Escape that ends an IME conversion as keyCode 229
|
||||
// with isComposing false.
|
||||
if ( e.key !== 'Escape' || e.defaultPrevented || e.isComposing || e.keyCode === 229 ) return;
|
||||
const el = e.target === win.document.body ? win.document.querySelector('.window-active') : e.target;
|
||||
const accountWindow = el?.closest?.(ACCOUNT_CHECK_WINDOWS);
|
||||
if ( accountWindow ) close(accountWindow);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a framed upgrade can show for the GUI session `session` (its
|
||||
* `/whoami`): the deployment has an upgrade dialog that reports when it
|
||||
* closes, and no account check is waiting, which a frame couldn't be closed
|
||||
* from.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowUpgradeFrame = (win, session) =>
|
||||
win.UIUpgradeAccount?.embeddable === true &&
|
||||
!!session &&
|
||||
!session.requires_email_confirmation &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
|
||||
/**
|
||||
* Whether a framed email confirmation can show for the GUI session `session`
|
||||
* (its `/whoami`): no check other than the email is waiting, since those show
|
||||
* at boot with no way to close the frame.
|
||||
*
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowEmailConfirmationFrame = (session) =>
|
||||
!!session &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
|
||||
/**
|
||||
* Confirms the email of the framed user with `confirm`, which shows the GUI's
|
||||
* windows for it. An email already confirmed resolves true without showing
|
||||
* anything, so the page never shows the frame.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {() => Promise<boolean>} confirm
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const confirmEmailInFrame = async (win, confirm, tell) => {
|
||||
if ( win.user?.email_confirmed === true ) return true;
|
||||
// The windows center themselves when they open.
|
||||
await whenFrameSized(win, () => tell('ready'));
|
||||
return (await confirm()) === true;
|
||||
};
|
||||
|
||||
/**
|
||||
* What prompted a framed upgrade, from its `reason` and `method` fragment
|
||||
* parameters, keeping only well-formed values.
|
||||
*
|
||||
* @param {string} hash - `location.hash`
|
||||
* @returns {{ reason?: string, method?: string }}
|
||||
*/
|
||||
export const framedUpgradeDetails = (hash) => {
|
||||
const given = new URLSearchParams(String(hash ?? '').replace(/^#/, ''));
|
||||
const details = {};
|
||||
const reason = given.get('reason');
|
||||
if ( UPGRADE_REASONS.has(reason) ) details.reason = reason;
|
||||
const method = given.get('method');
|
||||
if ( method && method.length <= UPGRADE_METHOD_MAX ) details.method = method;
|
||||
return details;
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the deployment's upgrade dialog in a framed popup and tells the
|
||||
* framing page it's ready once it's open, or before it opens when the page
|
||||
* still hides the frame. Resolves whether the user upgraded,
|
||||
* once the dialog closes, or false once every dialog and window it showed has
|
||||
* gone without it reporting a close.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedUpgrade = (win, attribution, tell) => new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let seen = false;
|
||||
let goneTimer = null;
|
||||
const settle = (finish) => {
|
||||
if ( settled ) return;
|
||||
settled = true;
|
||||
observer.disconnect();
|
||||
clearTimeout(goneTimer);
|
||||
finish();
|
||||
};
|
||||
const shown = () => !!win.document.querySelector(UPGRADE_MODAL_UI);
|
||||
const check = () => {
|
||||
if ( shown() ) {
|
||||
seen = true;
|
||||
clearTimeout(goneTimer);
|
||||
goneTimer = null;
|
||||
} else if ( seen && ! goneTimer ) {
|
||||
goneTimer = setTimeout(() => {
|
||||
goneTimer = null;
|
||||
if ( ! shown() ) settle(() => resolve(false));
|
||||
}, UPGRADE_GONE_MS);
|
||||
}
|
||||
};
|
||||
const observer = new win.MutationObserver(check);
|
||||
observer.observe(win.document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-modal'] });
|
||||
|
||||
let toldReady = false;
|
||||
const ready = () => {
|
||||
if ( toldReady || settled ) return;
|
||||
toldReady = true;
|
||||
tell('ready');
|
||||
};
|
||||
const open = () => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => settle(() => resolve(result?.upgraded === true)),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
};
|
||||
whenFrameSized(win, ready)
|
||||
.then(open)
|
||||
.then(() => {
|
||||
check();
|
||||
ready();
|
||||
}, (e) => settle(() => reject(e)));
|
||||
});
|
||||
|
||||
/**
|
||||
* Resolves once the frame has a viewport. The page keeps a loading frame
|
||||
* hidden, which Chromium and WebKit lay out at 0x0, and a GUI window opened
|
||||
* then (such as an alert) centers itself on that. Without one, `reveal` asks
|
||||
* the page to show the frame first.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {() => void} reveal
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const whenFrameSized = (win, reveal) => new Promise((resolve) => {
|
||||
const sized = () => win.innerWidth > 0 && win.innerHeight > 0;
|
||||
if ( sized() ) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
let timer = null;
|
||||
const done = () => {
|
||||
win.removeEventListener('resize', onResize);
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
const onResize = () => {
|
||||
if ( sized() ) done();
|
||||
};
|
||||
win.addEventListener('resize', onResize);
|
||||
// Opening on a 0x0 viewport is better than never opening.
|
||||
timer = setTimeout(done, FRAME_SIZE_TIMEOUT_MS);
|
||||
reveal();
|
||||
});
|
||||
@@ -0,0 +1,611 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
POPUP_FRAME_MSG,
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
focusOnFrameFocus,
|
||||
framedPopupAction,
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './popupFrame.js';
|
||||
|
||||
const HOST = 'https://notes.puter.test';
|
||||
|
||||
/** A stand-in for the frame's window, with its own parent to post to. */
|
||||
const frameWindow = () => {
|
||||
const parent = { postMessage: vi.fn() };
|
||||
const open = vi.fn(() => 'opened');
|
||||
return {
|
||||
parent,
|
||||
open,
|
||||
opener: null,
|
||||
close: () => {},
|
||||
document,
|
||||
MutationObserver: window.MutationObserver,
|
||||
};
|
||||
};
|
||||
|
||||
const statesSent = (win) => win.parent.postMessage.mock.calls.map(([data, origin]) => {
|
||||
expect(origin).toBe(HOST);
|
||||
expect(data.msg).toBe(POPUP_FRAME_MSG);
|
||||
return data.state;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
document.documentElement.classList.remove('popup-frame-transparent');
|
||||
});
|
||||
|
||||
describe('framedPopupAction', () => {
|
||||
it.each([
|
||||
['/embed/sign-in', 'sign-in'],
|
||||
['/embed/sign-in/', 'sign-in'],
|
||||
['/embed/show-open-file-picker', 'show-open-file-picker'],
|
||||
['/embed/show-save-file-picker', 'show-save-file-picker'],
|
||||
['/embed/show-directory-picker', 'show-directory-picker'],
|
||||
['/embed/upgrade', 'upgrade'],
|
||||
['/embed/request-email-confirmation', 'request-email-confirmation'],
|
||||
['/embed/apps', null],
|
||||
['/embed/feedback', null],
|
||||
['/embed/request-permission', null],
|
||||
['/action/sign-in', null],
|
||||
['/embed/sign-in/extra', null],
|
||||
['/', null],
|
||||
[undefined, null],
|
||||
])('%s frames %s', (pathname, expected) => {
|
||||
expect(framedPopupAction(pathname)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('framedPopupParams', () => {
|
||||
it('keeps only the popup parameters a framing page may pass', () => {
|
||||
const params = framedPopupParams('#msg_id=7&options=%7B%22multiple%22%3Atrue%7D&request_auth=true&user=abc&auth_token=x&attempt_temp_user_creation=true&api_origin=https%3A%2F%2Fevil.test');
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
msg_id: '7',
|
||||
options: '{"multiple":true}',
|
||||
request_auth: 'true',
|
||||
});
|
||||
});
|
||||
|
||||
it('is empty without a fragment', () => {
|
||||
expect([...framedPopupParams('')]).toEqual([]);
|
||||
expect([...framedPopupParams(undefined)]).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('framesHostUser', () => {
|
||||
it.each([
|
||||
['show-open-file-picker', true],
|
||||
['show-save-file-picker', true],
|
||||
['show-directory-picker', true],
|
||||
['upgrade', true],
|
||||
['request-email-confirmation', true],
|
||||
['sign-in', false],
|
||||
[null, false],
|
||||
])('%s serves only the framing page\'s user: %s', (action, expected) => {
|
||||
expect(framesHostUser(action)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('framedUpgradeDetails', () => {
|
||||
it('keeps a known reason and the method', () => {
|
||||
expect(framedUpgradeDetails('#user=abc&reason=storage&method=puter.fs.upload&appUid=app-x'))
|
||||
.toEqual({ reason: 'storage', method: 'puter.fs.upload' });
|
||||
});
|
||||
|
||||
it('drops an unknown reason and an overlong method', () => {
|
||||
expect(framedUpgradeDetails(`#reason=free-money&method=${'m'.repeat(201)}`)).toEqual({});
|
||||
expect(framedUpgradeDetails('')).toEqual({});
|
||||
expect(framedUpgradeDetails(undefined)).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowUpgradeFrame', () => {
|
||||
const win = { UIUpgradeAccount: Object.assign(function () {}, { embeddable: true }) };
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify, when the dialog reports its close', () => {
|
||||
expect(canShowUpgradeFrame(win, session)).toBe(true);
|
||||
});
|
||||
|
||||
it('needs a dialog that reports its close', () => {
|
||||
expect(canShowUpgradeFrame({}, session)).toBe(false);
|
||||
expect(canShowUpgradeFrame({ UIUpgradeAccount: function () {} }, session)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s to the tab', (check) => {
|
||||
expect(canShowUpgradeFrame(win, { ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowUpgradeFrame(win, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowEmailConfirmationFrame', () => {
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify, or only the email', () => {
|
||||
expect(canShowEmailConfirmationFrame(session)).toBe(true);
|
||||
expect(canShowEmailConfirmationFrame({ ...session, requires_email_confirmation: true })).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s unavailable', (check) => {
|
||||
expect(canShowEmailConfirmationFrame({ ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowEmailConfirmationFrame(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('confirmEmailInFrame', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const confirmWindow = ({ user, width = 1280, height = 800 } = {}) =>
|
||||
Object.assign(new EventTarget(), { user, innerWidth: width, innerHeight: height });
|
||||
|
||||
it('resolves true for a confirmed email without showing anything', async () => {
|
||||
const confirm = vi.fn();
|
||||
const tell = vi.fn();
|
||||
await expect(confirmEmailInFrame(confirmWindow({ user: { email_confirmed: true } }), confirm, tell))
|
||||
.resolves.toBe(true);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
expect(tell).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['confirms', true, true],
|
||||
['backs out', false, false],
|
||||
['gets no answer', undefined, false],
|
||||
])('resolves whether the email is confirmed when the user %s', async (_label, answer, expected) => {
|
||||
const confirm = vi.fn(async () => answer);
|
||||
await expect(confirmEmailInFrame(confirmWindow({ user: { email_confirmed: false } }), confirm, vi.fn()))
|
||||
.resolves.toBe(expected);
|
||||
expect(confirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('walks a temporary account through it', async () => {
|
||||
const confirm = vi.fn(async () => true);
|
||||
await expect(confirmEmailInFrame(confirmWindow({ user: { is_temp: true } }), confirm, vi.fn()))
|
||||
.resolves.toBe(true);
|
||||
expect(confirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('has a hidden frame shown before its windows open', async () => {
|
||||
vi.useFakeTimers();
|
||||
const win = confirmWindow({ user: {}, width: 0, height: 0 });
|
||||
const sizes = [];
|
||||
const tell = vi.fn();
|
||||
const result = confirmEmailInFrame(win, async () => {
|
||||
sizes.push([win.innerWidth, win.innerHeight]);
|
||||
return true;
|
||||
}, tell);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(tell).toHaveBeenCalledWith('ready');
|
||||
expect(sizes).toEqual([]);
|
||||
|
||||
win.innerWidth = 1280;
|
||||
win.innerHeight = 800;
|
||||
win.dispatchEvent(new Event('resize'));
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(sizes).toEqual([[1280, 800]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('showFramedUpgrade', () => {
|
||||
const upgradeWindow = (openAsWindow, { width = 1280, height = 800 } = {}) => {
|
||||
const created = [];
|
||||
const events = new EventTarget();
|
||||
const win = {
|
||||
document,
|
||||
innerWidth: width,
|
||||
innerHeight: height,
|
||||
addEventListener: events.addEventListener.bind(events),
|
||||
removeEventListener: events.removeEventListener.bind(events),
|
||||
dispatchEvent: events.dispatchEvent.bind(events),
|
||||
MutationObserver: window.MutationObserver,
|
||||
UIUpgradeAccount: function (options) {
|
||||
created.push(options);
|
||||
this.open_as_window = () => openAsWindow(options);
|
||||
},
|
||||
};
|
||||
return { win, created };
|
||||
};
|
||||
/** Stands in for the dialog's own modal root. */
|
||||
const showModal = () => {
|
||||
const root = document.createElement('div');
|
||||
root.setAttribute('aria-modal', 'true');
|
||||
document.body.append(root);
|
||||
return root;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('passes what prompted it, tells the page it is ready once open, and resolves the close', async () => {
|
||||
const tell = vi.fn();
|
||||
let options;
|
||||
const { win, created } = upgradeWindow(async (o) => {
|
||||
options = o;
|
||||
});
|
||||
const result = showFramedUpgrade(win, { appUid: 'app-1', reason: 'funds' }, tell);
|
||||
await vi.waitFor(() => expect(tell).toHaveBeenCalledWith('ready'));
|
||||
expect(created[0].attribution).toEqual({ appUid: 'app-1', reason: 'funds' });
|
||||
expect(tell).toHaveBeenCalledTimes(1);
|
||||
|
||||
options.onClose({ upgraded: true });
|
||||
await expect(result).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('passes no attribution when nothing is known, so the dialog credits the prompt it remembers', async () => {
|
||||
const { win, created } = upgradeWindow(async (o) => o.onClose());
|
||||
await showFramedUpgrade(win, {}, vi.fn());
|
||||
expect(created[0].attribution).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves false for a close without an upgrade, even one before it opened', async () => {
|
||||
const { win } = upgradeWindow(async (o) => o.onClose({ upgraded: false }));
|
||||
await expect(showFramedUpgrade(win, {}, vi.fn())).resolves.toBe(false);
|
||||
const { win: bare } = upgradeWindow(async (o) => o.onClose());
|
||||
await expect(showFramedUpgrade(bare, {}, vi.fn())).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('resolves false once the dialog is gone without reporting a close', async () => {
|
||||
vi.useFakeTimers();
|
||||
const tell = vi.fn();
|
||||
let root;
|
||||
const { win } = upgradeWindow(async () => {
|
||||
root = showModal();
|
||||
});
|
||||
const result = showFramedUpgrade(win, {}, tell);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(tell).toHaveBeenCalledWith('ready');
|
||||
|
||||
root.remove();
|
||||
await vi.advanceTimersByTimeAsync(499);
|
||||
await expect(Promise.race([result, 'pending'])).resolves.toBe('pending');
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('keeps waiting while one window replaces another', async () => {
|
||||
vi.useFakeTimers();
|
||||
let options;
|
||||
const { win } = upgradeWindow(async (o) => {
|
||||
options = o;
|
||||
// An alert, which is a GUI window, rather than the dialog itself.
|
||||
document.body.append(Object.assign(document.createElement('div'), { className: 'window' }));
|
||||
});
|
||||
const result = showFramedUpgrade(win, {}, vi.fn());
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
document.querySelector('.window').remove();
|
||||
showModal();
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await expect(Promise.race([result, 'pending'])).resolves.toBe('pending');
|
||||
|
||||
options.onClose({ upgraded: true });
|
||||
await expect(result).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('waits for the dialog to show before watching for it to go', async () => {
|
||||
vi.useFakeTimers();
|
||||
let options;
|
||||
const { win } = upgradeWindow(async (o) => {
|
||||
options = o;
|
||||
});
|
||||
const result = showFramedUpgrade(win, {}, vi.fn());
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await expect(Promise.race([result, 'pending'])).resolves.toBe('pending');
|
||||
options.onClose({ upgraded: false });
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('has a hidden frame shown before opening the dialog, so it lays out on a real viewport', async () => {
|
||||
vi.useFakeTimers();
|
||||
const tell = vi.fn();
|
||||
const sizes = [];
|
||||
const { win, created } = upgradeWindow(async () => {
|
||||
sizes.push([win.innerWidth, win.innerHeight]);
|
||||
}, { width: 0, height: 0 });
|
||||
const result = showFramedUpgrade(win, {}, tell);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(tell).toHaveBeenCalledWith('ready');
|
||||
expect(created).toHaveLength(0);
|
||||
|
||||
win.innerWidth = 1280;
|
||||
win.innerHeight = 800;
|
||||
win.dispatchEvent(new Event('resize'));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(sizes).toEqual([[1280, 800]]);
|
||||
// Told once, not again once it opens.
|
||||
expect(tell).toHaveBeenCalledTimes(1);
|
||||
|
||||
created[0].onClose({ upgraded: false });
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('opens the dialog anyway when a hidden frame never gets a viewport', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { win, created } = upgradeWindow(async () => {}, { width: 0, height: 0 });
|
||||
showFramedUpgrade(win, {}, vi.fn());
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(created).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(created).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('rejects when the dialog fails to open', async () => {
|
||||
const { win } = upgradeWindow(async () => {
|
||||
throw new Error('broken');
|
||||
});
|
||||
await expect(showFramedUpgrade(win, {}, vi.fn())).rejects.toThrow('broken');
|
||||
});
|
||||
});
|
||||
|
||||
describe('startPopupFrame', () => {
|
||||
it('does nothing without a framing page to answer', () => {
|
||||
const win = frameWindow();
|
||||
expect(startPopupFrame(win, null)).toBeNull();
|
||||
const top = frameWindow();
|
||||
top.parent = top;
|
||||
expect(startPopupFrame(top, HOST)).toBeNull();
|
||||
expect(win.opener).toBeNull();
|
||||
});
|
||||
|
||||
it('makes the framing page the opener and tells it the frame is loading', () => {
|
||||
const win = frameWindow();
|
||||
startPopupFrame(win, HOST);
|
||||
expect(win.opener).toBe(win.parent);
|
||||
expect(statesSent(win)).toEqual(['loading']);
|
||||
});
|
||||
|
||||
it('asks the framing page to remove the frame on close, either way the popup closes', () => {
|
||||
const win = frameWindow();
|
||||
startPopupFrame(win, HOST);
|
||||
win.close();
|
||||
win.open('', '_self').close();
|
||||
expect(statesSent(win)).toEqual(['loading', 'closed', 'closed']);
|
||||
});
|
||||
|
||||
it('sends the fields that go with a state, without letting them rename it', () => {
|
||||
const win = frameWindow();
|
||||
const tell = startPopupFrame(win, HOST);
|
||||
tell('provider', { url: 'https://puter.test/auth/oidc/google/start', msg: 'x', state: 'y' });
|
||||
expect(win.parent.postMessage).toHaveBeenLastCalledWith(
|
||||
{ url: 'https://puter.test/auth/oidc/google/start', msg: POPUP_FRAME_MSG, state: 'provider' },
|
||||
HOST,
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the framing page show through an upgrade or email confirmation frame only', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/sign-in' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(false);
|
||||
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/upgrade' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
|
||||
document.documentElement.classList.remove('popup-frame-transparent');
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/request-email-confirmation' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
});
|
||||
|
||||
it('sends a boolean field with a state', () => {
|
||||
const win = frameWindow();
|
||||
const tell = startPopupFrame(win, HOST);
|
||||
tell('closed', { upgraded: true });
|
||||
expect(win.parent.postMessage).toHaveBeenLastCalledWith(
|
||||
{ upgraded: true, msg: POPUP_FRAME_MSG, state: 'closed' },
|
||||
HOST,
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves other window.open calls alone', () => {
|
||||
const win = frameWindow();
|
||||
const open = win.open;
|
||||
startPopupFrame(win, HOST);
|
||||
expect(win.open('https://puter.com/terms', '_blank')).toBe('opened');
|
||||
expect(open).toHaveBeenCalledWith('https://puter.com/terms', '_blank');
|
||||
});
|
||||
|
||||
it('tells the framing page it is ready once the popup shows something', async () => {
|
||||
const win = frameWindow();
|
||||
startPopupFrame(win, HOST);
|
||||
document.body.append(Object.assign(document.createElement('div'), { className: 'busy' }));
|
||||
await Promise.resolve();
|
||||
expect(statesSent(win)).toEqual(['loading']);
|
||||
|
||||
const dialog = document.createElement('div');
|
||||
dialog.className = 'dashboard-dialog-overlay auth-dialog-page';
|
||||
document.body.append(dialog);
|
||||
await Promise.resolve();
|
||||
document.body.append(Object.assign(document.createElement('div'), { className: 'window' }));
|
||||
await Promise.resolve();
|
||||
expect(statesSent(win)).toEqual(['loading', 'ready']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('focusOnFrameFocus', () => {
|
||||
/** A window of its own, so patching its focus() leaves the test's alone. */
|
||||
const ownWindow = () => {
|
||||
const iframe = document.createElement('iframe');
|
||||
document.body.append(iframe);
|
||||
const win = iframe.contentWindow;
|
||||
const input = win.document.createElement('input');
|
||||
win.document.body.append(input);
|
||||
return { win, input };
|
||||
};
|
||||
/** The frame losing its focus, then the framing page focusing it again. */
|
||||
const refocusFrame = (win) => {
|
||||
win.document.activeElement?.blur();
|
||||
win.dispatchEvent(new win.FocusEvent('focus'));
|
||||
};
|
||||
|
||||
it('gives the popup\'s latest focus back each time the frame gains focus with nothing focused', () => {
|
||||
const { win, input } = ownWindow();
|
||||
focusOnFrameFocus(win);
|
||||
input.focus();
|
||||
refocusFrame(win);
|
||||
expect(win.document.activeElement).toBe(input);
|
||||
refocusFrame(win);
|
||||
expect(win.document.activeElement).toBe(input);
|
||||
});
|
||||
|
||||
it('leaves focus to the user once they press a key or the pointer', () => {
|
||||
for ( const type of ['keydown', 'pointerdown'] ) {
|
||||
const { win, input } = ownWindow();
|
||||
const focus = win.HTMLElement.prototype.focus;
|
||||
focusOnFrameFocus(win);
|
||||
input.focus();
|
||||
win.document.body.dispatchEvent(new win.Event(type, { bubbles: true }));
|
||||
refocusFrame(win);
|
||||
expect(win.document.activeElement).toBe(win.document.body);
|
||||
expect(win.HTMLElement.prototype.focus).toBe(focus);
|
||||
}
|
||||
});
|
||||
|
||||
/** A window whose focus() is ignored while `blocked`, as a frame just shown is. */
|
||||
const blockableWindow = () => {
|
||||
const { win, input } = ownWindow();
|
||||
const nativeFocus = win.HTMLElement.prototype.focus;
|
||||
const state = { blocked: true };
|
||||
win.HTMLElement.prototype.focus = function (...args) {
|
||||
if ( ! state.blocked ) nativeFocus.apply(this, args);
|
||||
};
|
||||
return { win, input, state };
|
||||
};
|
||||
|
||||
it('retries a focus() the frame ignored until it takes', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { win, input, state } = blockableWindow();
|
||||
focusOnFrameFocus(win);
|
||||
input.focus();
|
||||
expect(win.document.activeElement).toBe(win.document.body);
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
expect(win.document.activeElement).toBe(win.document.body);
|
||||
state.blocked = false;
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(win.document.activeElement).toBe(input);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops retrying after a while, and once the user presses a key', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { win, input, state } = blockableWindow();
|
||||
focusOnFrameFocus(win);
|
||||
input.focus();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
state.blocked = false;
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(win.document.activeElement).toBe(win.document.body);
|
||||
|
||||
const other = blockableWindow();
|
||||
focusOnFrameFocus(other.win);
|
||||
other.input.focus();
|
||||
other.win.document.body.dispatchEvent(new other.win.Event('keydown', { bubbles: true }));
|
||||
other.state.blocked = false;
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(other.win.document.activeElement).toBe(other.win.document.body);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves an element that has focus, and one that has left the page', () => {
|
||||
const { win, input } = ownWindow();
|
||||
const nativeFocus = win.HTMLElement.prototype.focus;
|
||||
const other = win.document.createElement('button');
|
||||
win.document.body.append(other);
|
||||
focusOnFrameFocus(win);
|
||||
input.focus();
|
||||
nativeFocus.call(other);
|
||||
win.dispatchEvent(new win.FocusEvent('focus'));
|
||||
expect(win.document.activeElement).toBe(other);
|
||||
|
||||
input.remove();
|
||||
refocusFrame(win);
|
||||
expect(win.document.activeElement).toBe(win.document.body);
|
||||
});
|
||||
});
|
||||
|
||||
describe('closeAccountChecksOnEscape', () => {
|
||||
/** A sign-in window with its own document, whose close() is spied on. */
|
||||
const signInWindow = () => {
|
||||
const win = { document: document.implementation.createHTMLDocument(), close: vi.fn() };
|
||||
closeAccountChecksOnEscape(win);
|
||||
return win;
|
||||
};
|
||||
const escapeOn = (el, init = {}) => {
|
||||
el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true, ...init }));
|
||||
};
|
||||
const showWindow = (win, className = 'window window-active window-confirm-email-using-code') => {
|
||||
const el = Object.assign(win.document.createElement('div'), { className });
|
||||
el.innerHTML = '<input class="digit-input">';
|
||||
win.document.body.append(el);
|
||||
return el;
|
||||
};
|
||||
|
||||
it.each([
|
||||
'window-confirm-email-using-code',
|
||||
'window-confirm-phone-using-code',
|
||||
'window-card-verification',
|
||||
'window-save-account',
|
||||
])('closes on Escape in the %s window', (cls) => {
|
||||
const win = signInWindow();
|
||||
escapeOn(showWindow(win, `window window-active ${cls}`).querySelector('input'));
|
||||
expect(win.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes on Escape with focus on the page behind an account check', () => {
|
||||
const win = signInWindow();
|
||||
showWindow(win);
|
||||
escapeOn(win.document.body);
|
||||
expect(win.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('leaves Escape that something or an IME handled, other keys, and other windows alone', () => {
|
||||
const win = signInWindow();
|
||||
const input = showWindow(win).querySelector('input');
|
||||
input.addEventListener('keydown', (e) => e.preventDefault(), { once: true });
|
||||
escapeOn(input);
|
||||
escapeOn(input, { key: 'Enter' });
|
||||
escapeOn(input, { isComposing: true });
|
||||
// Safari ends a conversion with keyCode 229 and isComposing false.
|
||||
escapeOn(input, { keyCode: 229 });
|
||||
escapeOn(showWindow(win, 'window window-alert').querySelector('input'));
|
||||
expect(win.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hands the account window to the close it is given, leaving the frame open', () => {
|
||||
const win = { document: document.implementation.createHTMLDocument(), close: vi.fn() };
|
||||
const close = vi.fn();
|
||||
closeAccountChecksOnEscape(win, close);
|
||||
const el = showWindow(win);
|
||||
escapeOn(el.querySelector('input'));
|
||||
escapeOn(win.document.body);
|
||||
expect(close.mock.calls).toEqual([[el], [el]]);
|
||||
expect(win.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Run `task` over `items`, at most `limit` at a time. Resolves to the items
|
||||
* whose task rejected.
|
||||
*
|
||||
* @template T
|
||||
* @param {T[]} items
|
||||
* @param {number} limit
|
||||
* @param {(item: T) => Promise<unknown>} task
|
||||
* @returns {Promise<T[]>}
|
||||
*/
|
||||
export const runLimited = async (items, limit, task) => {
|
||||
const failed = [];
|
||||
let index = 0;
|
||||
const worker = async () => {
|
||||
while ( index < items.length ) {
|
||||
const item = items[index++];
|
||||
try {
|
||||
await task(item);
|
||||
} catch {
|
||||
failed.push(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return failed;
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { runLimited } from './runLimited.js';
|
||||
|
||||
describe('runLimited', () => {
|
||||
it('runs every item, never more than the limit at once', async () => {
|
||||
let running = 0;
|
||||
let peak = 0;
|
||||
const done = [];
|
||||
await runLimited([1, 2, 3, 4, 5, 6, 7], 3, async (n) => {
|
||||
running++;
|
||||
peak = Math.max(peak, running);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
done.push(n);
|
||||
running--;
|
||||
});
|
||||
expect(done.sort()).toEqual([1, 2, 3, 4, 5, 6, 7]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('resolves to the items whose task rejected, after running the rest', async () => {
|
||||
const failed = await runLimited(['a', 'b', 'c'], 2, async (item) => {
|
||||
if ( item === 'b' ) throw new Error('no');
|
||||
});
|
||||
expect(failed).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('does nothing for no items', async () => {
|
||||
expect(await runLimited([], 4, async () => {})).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -27,7 +27,8 @@ const update_username_in_gui = function (new_username) {
|
||||
// ------------------------------------------------------------
|
||||
// Update all item/window/... paths, with the new username
|
||||
// ------------------------------------------------------------
|
||||
$(':not([data-path=""]),:not([data-item-path=""])').each((i, el) => {
|
||||
// With no earlier username there are no paths under it to rewrite.
|
||||
if ( old_username ) $('[data-path], [data-item-path], [data-shortcut_to_path]').each((i, el) => {
|
||||
const $el = $(el);
|
||||
const attr_path = $el.attr('data-path');
|
||||
const attr_item_path = $el.attr('data-item-path');
|
||||
@@ -91,11 +92,11 @@ const update_username_in_gui = function (new_username) {
|
||||
$el.attr('data-item-path', attr_item_path.replace(`/${ window.user.username }/`, `/${ new_username }/`));
|
||||
}
|
||||
}
|
||||
|
||||
// any element with username class
|
||||
$('.username').text(new_username);
|
||||
});
|
||||
|
||||
// any element with username class
|
||||
$('.username').text(new_username);
|
||||
|
||||
// todo update all window paths
|
||||
$('.window').each((i, el) => {
|
||||
});
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
|
||||
const { default: update_username_in_gui } = await import('./updateUsernameInGui.js');
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.puter = { _cache: { flushall: vi.fn() } };
|
||||
document.body.innerHTML = `
|
||||
<div class="item" data-path="/alice/Documents/a.txt"></div>
|
||||
<div class="item" data-path="/alice"></div>
|
||||
<div class="item" data-path="/alicex/b.txt"></div>
|
||||
<div class="window" data-item-path="/alice/Pictures"></div>
|
||||
<div class="shortcut" data-shortcut_to_path="/alice/Videos"></div>
|
||||
<span class="username">alice</span>
|
||||
<span class="username">alice</span>`;
|
||||
});
|
||||
|
||||
describe('update_username_in_gui', () => {
|
||||
it('rewrites the paths under the old username and every username label', () => {
|
||||
window.user = { username: 'alice' };
|
||||
|
||||
update_username_in_gui('bob');
|
||||
|
||||
const paths = $('[data-path]').toArray().map(el => el.dataset.path);
|
||||
expect(paths).toEqual(['/bob/Documents/a.txt', '/bob', '/alicex/b.txt']);
|
||||
expect($('.window').attr('data-item-path')).toBe('/bob/Pictures');
|
||||
expect($('.shortcut').attr('data-shortcut_to_path')).toBe('/bob/Videos');
|
||||
expect($('.username').toArray().map(el => el.textContent)).toEqual(['bob', 'bob']);
|
||||
expect(window.home_path).toBe('/bob');
|
||||
});
|
||||
|
||||
it('only sets the labels while signing in, with no earlier username', () => {
|
||||
window.user = undefined;
|
||||
|
||||
update_username_in_gui('bob');
|
||||
|
||||
expect($('.item').first().attr('data-path')).toBe('/alice/Documents/a.txt');
|
||||
expect($('.username').first().text()).toBe('bob');
|
||||
});
|
||||
});
|
||||
@@ -623,7 +623,6 @@ const cs = {
|
||||
"window_title_open": "Otevřít",
|
||||
"window_title_change_password": "Změnit heslo",
|
||||
"login_email_username_required": "E-mail nebo uživatelské jméno je povinné",
|
||||
"oidc_switched_to_login_message": "Byli jste přihlášeni ke stávajícímu účtu.",
|
||||
"sign_in_with_provider": "Přihlásit se pomocí %%",
|
||||
"sign_up_with_provider": "Zaregistrujte se pomocí %%",
|
||||
"welcome_description": "Ukládejte soubory, hrajte hry, najděte úžasné aplikace a mnoho dalšího! Vše na jednom místě, dostupné odkudkoli a kdykoli.",
|
||||
|
||||
@@ -550,11 +550,14 @@ const en = {
|
||||
'Resources': 'Resources',
|
||||
restart_puter_confirm: 'Are you sure you want to restart Puter?',
|
||||
restore: 'Restore',
|
||||
restore_location_unknown: '“{{name}}” can’t be restored because where it was deleted from isn’t known.',
|
||||
restore_only_trash_items: '“{{name}}” is inside a folder in the Trash. Restore that folder instead.',
|
||||
retry: 'Retry',
|
||||
save: 'Save',
|
||||
saturation: 'Saturation',
|
||||
save_account: 'Save account',
|
||||
save_account_to_get_copy_link: 'Please create an account to proceed.',
|
||||
save_account_to_proceed: 'Please create an account to proceed.',
|
||||
save_account_to_publish: 'Please create an account to proceed.',
|
||||
save_session: 'Save session',
|
||||
save_session_c2a: 'Create an account to save your current session and avoid losing your work.',
|
||||
@@ -887,6 +890,13 @@ const en = {
|
||||
setup2fa_5_button: 'Enable 2FA',
|
||||
setup2fa_password_instructions: 'Enter your password to set up 2FA.',
|
||||
setup2fa_code_expired: 'That code has expired. Enter the current code from your authenticator app to finish.',
|
||||
setup2fa_step_scan: 'Scan',
|
||||
setup2fa_step_backup: 'Backup',
|
||||
setup2fa_step_verify: 'Verify',
|
||||
setup2fa_enabling: 'Enabling…',
|
||||
setup2fa_success_text: 'Your account is now protected with two-factor authentication. You’ll be asked for a verification code each time you sign in.',
|
||||
setup2fa_copy_secret: 'Copy secret key',
|
||||
setup2fa_recovery_codes: 'Recovery Codes',
|
||||
|
||||
// === 2FA Login ===
|
||||
login2fa_otp_title: 'Enter 2FA Code',
|
||||
@@ -1013,7 +1023,6 @@ const en = {
|
||||
sign_up_with_email: 'Sign up using email',
|
||||
popup_opener_uses_puter: '%strong% is powered by Puter',
|
||||
popup_opener_origin_unsupported: 'Puter cannot sign you in to this page because the browser gives it no identifiable address. Pages opened straight from a file (file://) and iframes sandboxed without allow-same-origin are not supported — serve the page over http://localhost or a real domain and try again.',
|
||||
oidc_switched_to_login_message: 'You have been logged in to an existing account.',
|
||||
|
||||
// Login Window
|
||||
'login_email_username_required': 'Email or username is required',
|
||||
|
||||
@@ -60,6 +60,10 @@ window.gui = async (options) => {
|
||||
window.co_isolation_enabled = options.co_isolation_enabled;
|
||||
window.teams_ui = options.teams_ui ?? false;
|
||||
|
||||
// A popup a first-party page frames answers it before the SDK loads, so
|
||||
// the page knows the frame wasn't refused.
|
||||
window.start_popup_frame?.(options.embed_host_origin);
|
||||
|
||||
// DEV: Load the initgui.js file if we are in development mode
|
||||
if ( !window.gui_env || window.gui_env === 'dev' ) {
|
||||
await window.loadScript('/sdk/puter.dev.js');
|
||||
|
||||
+145
-34
@@ -46,7 +46,22 @@ import UIAuthSignup from './UI/Auth/UIAuthSignup.js';
|
||||
import UIAuthRecoverPassword from './UI/Auth/UIAuthRecoverPassword.js';
|
||||
import { PROCESS_RUNNING } from './definitions.js';
|
||||
import { isAttestedOrigin } from './helpers/attestedOrigin.js';
|
||||
import { embedHostUser } from './helpers/embedHostUser.js';
|
||||
import {
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
focusOnFrameFocus,
|
||||
framedPopupAction,
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './helpers/popupFrame.js';
|
||||
import confirm_before_unload from './helpers/confirmBeforeUnload.js';
|
||||
import ensureConfirmedEmail from './helpers/ensureConfirmedEmail.js';
|
||||
import create_access_token from './helpers/createAccessToken.js';
|
||||
import create_gui_token from './helpers/createGuiToken.js';
|
||||
import {
|
||||
@@ -565,7 +580,10 @@ const postAuthActions = async (action) => {
|
||||
window.opener?.postMessage({
|
||||
msg,
|
||||
original_msg_id: msg_id,
|
||||
}, '*');
|
||||
}, window.openerOrigin);
|
||||
// Escape closes only the picker window, which would leave the
|
||||
// page's frame open over an empty desktop.
|
||||
if ( window.embedded_in_frame ) window.close();
|
||||
};
|
||||
|
||||
if ( action === 'show-open-file-picker' ) {
|
||||
@@ -630,14 +648,17 @@ const postAuthActions = async (action) => {
|
||||
// send 'sendMeFileData' event to parent
|
||||
window.opener.postMessage({
|
||||
msg: 'sendMeFileData',
|
||||
}, '*');
|
||||
}, window.openerOrigin);
|
||||
|
||||
// listen for 'showSaveFilePickerPopup' event from parent
|
||||
window.addEventListener('message', async (event) => {
|
||||
if ( event.data.msg !== 'showSaveFilePickerPopup' )
|
||||
// listen for 'showSaveFilePickerPopup' event from parent. Only the
|
||||
// page that asked supplies the file, once; any other window that
|
||||
// can reach this one (a sibling frame of the framing page) can't.
|
||||
window.addEventListener('message', async function onFileData (event) {
|
||||
if ( event.data?.msg !== 'showSaveFilePickerPopup' || event.source !== window.opener )
|
||||
{
|
||||
return;
|
||||
}
|
||||
window.removeEventListener('message', onFileData);
|
||||
|
||||
// Open dialog
|
||||
UIWindow({
|
||||
@@ -650,6 +671,7 @@ const postAuthActions = async (action) => {
|
||||
title: 'Save',
|
||||
is_dir: true,
|
||||
is_saveFileDialog: true,
|
||||
saveFileDialog_default_filename: event.data.suggestedName ?? '',
|
||||
is_resizable: false,
|
||||
has_head: false,
|
||||
cover_page: true,
|
||||
@@ -701,7 +723,7 @@ const postAuthActions = async (action) => {
|
||||
uid: file_signature.uid,
|
||||
path: window.privacy_aware_path(res.path),
|
||||
},
|
||||
}, '*');
|
||||
}, window.openerOrigin);
|
||||
|
||||
window.close();
|
||||
window.open('', '_self').close();
|
||||
@@ -709,7 +731,14 @@ const postAuthActions = async (action) => {
|
||||
catch ( err ) {
|
||||
// item with same name exists
|
||||
if ( err.code === 'item_with_same_name_exists' ) {
|
||||
const alert_resp = await UIAlert({
|
||||
// Escape closes the alert without an answer,
|
||||
// which counts as Cancel, so the picker isn't
|
||||
// left behind its busy mask.
|
||||
let alert_closed;
|
||||
const alert_dismissed = new Promise((resolve) => {
|
||||
alert_closed = () => resolve('cancel');
|
||||
});
|
||||
const alert_resp = await Promise.race([UIAlert({
|
||||
message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
|
||||
buttons: [
|
||||
{
|
||||
@@ -723,10 +752,11 @@ const postAuthActions = async (action) => {
|
||||
},
|
||||
],
|
||||
parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
|
||||
});
|
||||
window_options: { on_close: alert_closed },
|
||||
}), alert_dismissed]);
|
||||
if ( alert_resp === 'replace' ) {
|
||||
overwrite = true;
|
||||
} else if ( alert_resp === 'cancel' ) {
|
||||
} else {
|
||||
// enable parent window
|
||||
$(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
|
||||
return;
|
||||
@@ -941,6 +971,7 @@ const postAuthActions = async (action) => {
|
||||
sent = await UIWindowAppFeedback({
|
||||
origin,
|
||||
source: 'web',
|
||||
fullpage: window.embedded_in_popup === true,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('send-feedback action failed', e);
|
||||
@@ -973,6 +1004,46 @@ const postAuthActions = async (action) => {
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: upgrade — the deployment's upgrade dialog for the first-party page framing
|
||||
// it, which hears whether the user upgraded once the dialog closes. The app it credits
|
||||
// is the one the framing page's origin resolves to, never one the fragment names.
|
||||
// -------------------------------------------------------------------------------------
|
||||
if ( action === 'upgrade' && window.embedded_in_frame ) {
|
||||
let upgraded;
|
||||
try {
|
||||
upgraded = await showFramedUpgrade(window, {
|
||||
...(window.host_app_uid ? { appUid: window.host_app_uid } : {}),
|
||||
...framedUpgradeDetails(window.location.hash),
|
||||
}, window.tell_popup_frame);
|
||||
} catch (e) {
|
||||
// A dialog that failed to open leaves the page to open the upgrade in a tab.
|
||||
console.error('upgrade action failed', e);
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
}
|
||||
window.tell_popup_frame('closed', { upgraded });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: request-email-confirmation — puter.ui.requestEmailConfirmation() on the
|
||||
// first-party page framing it, which hears whether the email is confirmed once the
|
||||
// user is done.
|
||||
// -------------------------------------------------------------------------------------
|
||||
if ( action === 'request-email-confirmation' && window.embedded_in_frame ) {
|
||||
let confirmed = false;
|
||||
try {
|
||||
confirmed = await confirmEmailInFrame(
|
||||
window,
|
||||
() => ensureConfirmedEmail(i18n('save_account_to_proceed')),
|
||||
window.tell_popup_frame,
|
||||
);
|
||||
} catch (e) {
|
||||
console.error('request-email-confirmation action failed', e);
|
||||
}
|
||||
window.tell_popup_frame('closed', { confirmed });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: attach-custom-domain — puter.hosting.attach() on a website. Hosts the custom
|
||||
// domain dialog for `subdomain` and posts the chosen domain back to the opener.
|
||||
@@ -1154,9 +1225,17 @@ if (jQuery) {
|
||||
{
|
||||
const pathname = window.location.pathname;
|
||||
const search_params = new URLSearchParams(window.location.search);
|
||||
if (['true', '1'].includes(search_params.get('embedded_in_popup'))) {
|
||||
// A popup a first-party page frames at `/embed/<action>` boots as one.
|
||||
if (['true', '1'].includes(search_params.get('embedded_in_popup')) || framedPopupAction(pathname)) {
|
||||
window.embedded_in_popup = true;
|
||||
}
|
||||
// Called by the bootstrap in index.js, which can't import.
|
||||
window.start_popup_frame = (hostOrigin) => {
|
||||
if (!framedPopupAction(pathname)) return;
|
||||
window.tell_popup_frame = startPopupFrame(window, hostOrigin);
|
||||
window.embedded_in_frame = !!window.tell_popup_frame;
|
||||
if (window.embedded_in_frame) focusOnFrameFocus(window);
|
||||
};
|
||||
// note: iframe detection is inlined because globals.js (window.is_embedded) loads after this module
|
||||
const in_iframe = window.location !== window.parent.location;
|
||||
const needs_desktop_at_root =
|
||||
@@ -1411,8 +1490,16 @@ window.initgui = async function (options) {
|
||||
const url_paths = parse_url_paths(window.location.pathname);
|
||||
window.url_paths = url_paths;
|
||||
|
||||
// GET query params provided
|
||||
window.url_query_params = new URLSearchParams(window.location.search);
|
||||
// A framed popup without a framing page to answer (opened on its own, or
|
||||
// framed by a page the server refused) has nothing to do.
|
||||
const framed_action = framedPopupAction(window.location.pathname);
|
||||
if (framed_action && !window.embedded_in_frame) return;
|
||||
|
||||
// GET query params provided. A framed popup takes the popup's parameters
|
||||
// from its fragment; its route refuses a query string.
|
||||
window.url_query_params = framed_action
|
||||
? framedPopupParams(window.location.hash)
|
||||
: new URLSearchParams(window.location.search);
|
||||
window.signup_bonus_code = readSignupBonusCode(window.url_query_params);
|
||||
|
||||
// Install device signal helpers; collection is lazy. The fingerprint is
|
||||
@@ -1506,7 +1593,9 @@ window.initgui = async function (options) {
|
||||
// Extract 'action' from URL
|
||||
//--------------------------------------------------------------------------------------
|
||||
let action;
|
||||
if (
|
||||
if (framed_action) {
|
||||
action = framed_action;
|
||||
} else if (
|
||||
window.url_paths[0]?.toLocaleLowerCase() === 'action' &&
|
||||
window.url_paths[1]
|
||||
) {
|
||||
@@ -1520,6 +1609,12 @@ window.initgui = async function (options) {
|
||||
// action. See util/popupAuth.js.
|
||||
window.gui_action = action;
|
||||
|
||||
if (window.embedded_in_frame && action === 'sign-in') closeAccountChecksOnEscape(window);
|
||||
// Closing the window answers the frame, after any code it already sent.
|
||||
if (window.embedded_in_frame && action === 'request-email-confirmation') {
|
||||
closeAccountChecksOnEscape(window, (accountWindow) => $(accountWindow).close());
|
||||
}
|
||||
|
||||
if (action === 'oidc-2fa') {
|
||||
const result = oidcChallenge?.token && await UIAuth2FA(oidcChallenge.token);
|
||||
if (result?.redirectUrl) {
|
||||
@@ -1643,7 +1738,9 @@ window.initgui = async function (options) {
|
||||
action,
|
||||
);
|
||||
try {
|
||||
window.openerOrigin = await resolveOpenerOrigin({
|
||||
// A framed popup's opener is the page the server read from the
|
||||
// referrer and pinned with frame-ancestors.
|
||||
window.openerOrigin = window.embedded_in_frame ? window.gui_params.embed_host_origin : await resolveOpenerOrigin({
|
||||
relaysToken: relaysTokenAtBoot(
|
||||
action,
|
||||
window.url_query_params.get('cross_origin_isolated') ===
|
||||
@@ -1700,6 +1797,32 @@ window.initgui = async function (options) {
|
||||
// this is the referrer in terms of user acquisition
|
||||
window.referrerStr = window.openerOrigin;
|
||||
|
||||
// A framed picker or upgrade shows only the Puter session of the user
|
||||
// the framing page is signed in as; for anyone else the page uses the
|
||||
// popup or tab, which can sign in and switch accounts.
|
||||
if (window.embedded_in_frame && framesHostUser(action)) {
|
||||
const host_user = embedHostUser(window.location.hash);
|
||||
let session = null;
|
||||
let session_user = null;
|
||||
if (host_user && window.is_auth()) {
|
||||
try {
|
||||
session = await puter.os.user({ query: 'icon_size=64' });
|
||||
session_user = String(session?.uuid ?? '').toLowerCase();
|
||||
} catch (e) {
|
||||
session_user = null;
|
||||
}
|
||||
}
|
||||
if (
|
||||
!host_user ||
|
||||
session_user !== host_user ||
|
||||
(action === 'upgrade' && !canShowUpgradeFrame(window, session)) ||
|
||||
(action === 'request-email-confirmation' && !canShowEmailConfirmationFrame(session))
|
||||
) {
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Tell a request-permission opener that this popup can reach it. Sent
|
||||
// here, before any sign-in gate, because the SDK reads its absence as
|
||||
// "the opener link was severed by COOP" — where a close means the
|
||||
@@ -1826,25 +1949,6 @@ window.initgui = async function (options) {
|
||||
});
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------
|
||||
// Inform the user if they chose "signup" but were logged into an existing account
|
||||
//--------------------------------------------------------------------------------------
|
||||
if (
|
||||
window.url_query_params.get('oidc_switched') === 'login' &&
|
||||
window.is_auth()
|
||||
) {
|
||||
await UIAlert({
|
||||
message: i18n('oidc_switched_to_login_message'),
|
||||
});
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.delete('oidc_switched');
|
||||
const cleanSearch = params.toString();
|
||||
const cleanUrl = cleanSearch
|
||||
? `${window.location.pathname}?${cleanSearch}`
|
||||
: window.location.pathname || '/';
|
||||
window.history.replaceState(null, document.title, cleanUrl);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------
|
||||
// Early check for fullpage mode from app metadata
|
||||
// If the user navigated to /app/<app_name> and the app has fullpage_on_landing,
|
||||
@@ -1951,8 +2055,11 @@ window.initgui = async function (options) {
|
||||
);
|
||||
window.userAppToken = response?.token;
|
||||
|
||||
// A framed picker or upgrade already holds the framing page's user,
|
||||
// so it doesn't offer to switch.
|
||||
if (
|
||||
!picked_a_user_for_sdk_login &&
|
||||
!(window.embedded_in_frame && framesHostUser(action)) &&
|
||||
window.logged_in_users.length > 1 &&
|
||||
(!window.userAppToken ||
|
||||
window.url_query_params.get('request_auth'))
|
||||
@@ -2329,8 +2436,12 @@ window.initgui = async function (options) {
|
||||
// assertVerifiedAccount): email → phone (SMS) → card, or card →
|
||||
// phone → email when the account clears email last.
|
||||
let card_gate_cleared_by_fallback = false;
|
||||
// A framed email confirmation asks for the code itself, in a
|
||||
// window the user can close.
|
||||
const confirmsEmailInAction =
|
||||
window.embedded_in_frame && action === 'request-email-confirmation';
|
||||
const emailGate = async () => {
|
||||
if (whoami.requires_email_confirmation) {
|
||||
if (whoami.requires_email_confirmation && !confirmsEmailInAction) {
|
||||
let is_verified;
|
||||
do {
|
||||
is_verified = await UIWindowEmailConfirmationRequired({
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
vi.mock('./UI/UIAlert.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UI/UIWindowSearch.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./helpers/launchApp.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./helpers/openItem.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = key => key;
|
||||
globalThis.def = globalThis.def ?? (value => value);
|
||||
globalThis.use = globalThis.use ?? (() => class {});
|
||||
|
||||
await import('./keyboard.js');
|
||||
|
||||
const escape = () => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, which: 27, bubbles: true }));
|
||||
|
||||
describe('Escape on a file dialog', () => {
|
||||
const closed = [];
|
||||
|
||||
beforeEach(() => {
|
||||
closed.length = 0;
|
||||
jQuery.fn.close = function () {
|
||||
closed.push(...this.toArray());
|
||||
return this;
|
||||
};
|
||||
document.body.innerHTML = '<div class="window window-active window-filedialog"></div>';
|
||||
});
|
||||
|
||||
it('closes the file dialog', () => {
|
||||
escape();
|
||||
expect(closed).toEqual([document.querySelector('.window-filedialog')]);
|
||||
});
|
||||
|
||||
it('closes only a context menu open over it', () => {
|
||||
document.body.insertAdjacentHTML('beforeend', '<div class="context-menu"></div>');
|
||||
escape();
|
||||
expect(document.querySelector('.context-menu')).toBeNull();
|
||||
expect(closed).toEqual([]);
|
||||
|
||||
escape();
|
||||
expect(closed).toEqual([document.querySelector('.window-filedialog')]);
|
||||
});
|
||||
});
|
||||
@@ -448,6 +448,8 @@ $(document).bind('keydown', async function (e) {
|
||||
else if (
|
||||
// escape key code
|
||||
e.which === 27 &&
|
||||
// an open context menu takes the Escape (below) instead
|
||||
$('.context-menu').length === 0 &&
|
||||
// active window must be a FileDialog or Alert
|
||||
($('.window-active').hasClass('window-filedialog') || $('.window-active').hasClass('window-alert')) &&
|
||||
// either don't close if an input is focused or if the input is the filename input
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
/**
|
||||
* A popup's opener can be navigated to another origin while a picker is open,
|
||||
* so messages to it go to the origin attested at boot, not to '*'.
|
||||
*/
|
||||
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
|
||||
|
||||
// Sent before the opener's origin is known, or to report that it is unusable.
|
||||
const unattestedMessages = ['requestOrigin', 'permissionGranted', 'pushEnabled'];
|
||||
|
||||
const openerPosts = (src) => {
|
||||
const posts = [];
|
||||
for (const match of src.matchAll(/window\.opener\??\.postMessage\(/g)) {
|
||||
let depth = 1;
|
||||
let i = match.index + match[0].length;
|
||||
while (depth > 0 && i < src.length) {
|
||||
if (src[i] === '(') depth++;
|
||||
else if (src[i] === ')') depth--;
|
||||
i++;
|
||||
}
|
||||
posts.push(src.slice(match.index, i));
|
||||
}
|
||||
return posts;
|
||||
};
|
||||
|
||||
describe('messages to a popup opener', () => {
|
||||
for (const file of ['./initgui.js', './UI/UIWindow.js', './helpers/openItem.js']) {
|
||||
it(`target the attested opener origin in ${file}`, () => {
|
||||
const posts = openerPosts(read(file));
|
||||
expect(posts.length).toBeGreaterThan(0);
|
||||
for (const post of posts) {
|
||||
if (!/'\*'\s*,?\s*\)$/.test(post)) continue;
|
||||
const msg = post.match(/msg:\s*'([^']+)'/)?.[1];
|
||||
expect(unattestedMessages, post).toContain(msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -93,6 +93,7 @@ module.exports = async (options = {}) => {
|
||||
...entries,
|
||||
],
|
||||
'apps-embed': './src/appsEmbed.js',
|
||||
'feedback-embed': './src/feedbackEmbed.js',
|
||||
};
|
||||
config.output = {
|
||||
path: path.resolve(__dirname, '../dist'),
|
||||
|
||||
Vendored
+15
-13
@@ -18,6 +18,7 @@ declare global {
|
||||
// -- Shared --
|
||||
export type {
|
||||
APILoggingConfig,
|
||||
EmailConfirmationResult,
|
||||
ListPage,
|
||||
ListPaginationOptions,
|
||||
ListStreamOptions,
|
||||
@@ -28,6 +29,7 @@ export type {
|
||||
ToolSchema,
|
||||
UpgradeReason,
|
||||
UpgradeRequestDetails,
|
||||
UpgradeResult,
|
||||
} from './types/lib/types.js';
|
||||
export type { default as APICallLogger } from './types/lib/APICallLogger.js';
|
||||
|
||||
@@ -44,17 +46,17 @@ export type {
|
||||
ListTTSEnginesOptions,
|
||||
ListTTSVoicesOptions,
|
||||
OcrAnnotationFormat,
|
||||
ConvoOptions,
|
||||
ConvoTextEvent,
|
||||
ConvoAudioEvent,
|
||||
ConvoTranscriptEvent,
|
||||
ConvoInterruptedEvent,
|
||||
ConvoTurnDoneEvent,
|
||||
ConvoErrorEvent,
|
||||
ConvoEventMap,
|
||||
ConvoSessionOptions,
|
||||
ConvoPlaybackPosition,
|
||||
ConvoSpeakerOptions,
|
||||
RealtimeOptions,
|
||||
RealtimeTextEvent,
|
||||
RealtimeAudioEvent,
|
||||
RealtimeTranscriptEvent,
|
||||
RealtimeInterruptedEvent,
|
||||
RealtimeTurnDoneEvent,
|
||||
RealtimeErrorEvent,
|
||||
RealtimeEventMap,
|
||||
RealtimeSessionOptions,
|
||||
RealtimePlaybackPosition,
|
||||
RealtimeSpeakerOptions,
|
||||
RealtimeServerEvent,
|
||||
RealtimeClientEvent,
|
||||
Speech2SpeechOptions,
|
||||
@@ -391,5 +393,5 @@ export type Teams = InstanceType<import('./types/modules/teams/index.js').TeamsC
|
||||
export type UI = InstanceType<import('./types/modules/UI.js').UIConstructor>;
|
||||
export type WorkersHandler = InstanceType<import('./types/modules/Workers.js').WorkersConstructor>;
|
||||
|
||||
export type { Conversation, ConvoError } from './types/modules/ai/convo.js';
|
||||
export type { ConvoMicrophone, ConvoSpeaker } from './types/modules/ai/convoMedia.js';
|
||||
export type { Conversation, RealtimeError } from './types/modules/ai/realtime.js';
|
||||
export type { RealtimeMicrophone, RealtimeSpeaker } from './types/modules/ai/realtimeMedia.js';
|
||||
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* Puter GUI pages a first-party site can frame, under `/embed/*` on the GUI
|
||||
* origin. The server lets only a page one label under that origin frame them.
|
||||
*/
|
||||
|
||||
// After the frame loads, how long to wait for the embed's first message
|
||||
// before treating it as refused (a CSP that blocks it still fires `load`).
|
||||
const LOAD_GRACE_MS = 1000;
|
||||
// How long the embed may take to check the session before the popup is used.
|
||||
const READY_TIMEOUT_MS = 15_000;
|
||||
// A session check slower than this shows a loading scrim over the page.
|
||||
const LOADING_DELAY_MS = 200;
|
||||
|
||||
// The loading scrim matches the feedback embed's own, which fades in over it
|
||||
// once ready. A popup frame keeps it as the scrim behind its box. Scrolling
|
||||
// over the dialog stays there rather than scrolling the page behind it.
|
||||
const embedStyle = (cls) => `
|
||||
dialog.${cls}{overscroll-behavior:contain}
|
||||
dialog.${cls}::backdrop{background:transparent}
|
||||
dialog.${cls}:focus{outline:none}
|
||||
.${cls}-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .16s ease-in-out}
|
||||
.${cls}.is-loading .${cls}-loading{opacity:1;pointer-events:auto}
|
||||
.${cls}.is-loading iframe{visibility:hidden}
|
||||
.${cls}-loading span{width:28px;height:28px;box-sizing:border-box;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:${cls}-spin .7s linear infinite}
|
||||
@keyframes ${cls}-spin{to{transform:rotate(360deg)}}
|
||||
@media (prefers-color-scheme:dark){.${cls}-loading{background:rgba(0,0,0,.66)}}
|
||||
@media (prefers-reduced-motion:reduce){.${cls}-loading{transition:none}.${cls}-loading span{animation-duration:1.6s}}
|
||||
`;
|
||||
|
||||
// A popup frame sits in a box the size of the popup window it replaces, over
|
||||
// the scrim, and fills the screen on a phone as the popup's tab would. It's
|
||||
// centered by margins, which snap to device pixels where a translate can
|
||||
// leave its edge on a fraction of one. Its white backing stops 1px inside the
|
||||
// rounded edge, so in dark mode it doesn't show as a light fringe around the
|
||||
// frame. The close button starts from `all:unset` so the page's own button
|
||||
// styles don't reach it.
|
||||
const BOX_STYLE = `
|
||||
.puter-popup-frame .puter-popup-frame-loading{opacity:1;pointer-events:auto}
|
||||
.puter-popup-frame:not(.is-loading) .puter-popup-frame-loading span{display:none}
|
||||
.puter-popup-frame.is-loading .puter-popup-frame-box{visibility:hidden}
|
||||
.puter-popup-frame-box{position:absolute;inset:0;margin:auto;isolation:isolate;box-sizing:border-box;width:min(var(--puter-popup-frame-width),calc(100% - 32px));height:min(var(--puter-popup-frame-height),calc(100% - 32px));border-radius:12px;overflow:hidden;box-shadow:0 24px 64px rgba(0,0,0,.35)}
|
||||
.puter-popup-frame-box::before{content:"";position:absolute;inset:1px;z-index:-1;border-radius:11px;background:#fff}
|
||||
.puter-popup-frame-close{all:unset;box-sizing:border-box;position:absolute;top:10px;right:10px;width:32px;height:32px;display:flex;align-items:center;justify-content:center;padding:0;border:0;border-radius:50%;background:transparent;color:#6b7280;cursor:pointer}
|
||||
.puter-popup-frame-close:hover{background:rgba(127,127,127,.15)}
|
||||
.puter-popup-frame-close:focus-visible{outline:2px solid #3b82f6;outline-offset:1px}
|
||||
.puter-popup-frame-close svg{width:16px;height:16px}
|
||||
@media (prefers-color-scheme:dark){.puter-popup-frame-close{color:#9ca3af}}
|
||||
@media (max-width:600px){.puter-popup-frame-box{width:100%;height:100%;border-radius:0}.puter-popup-frame-box::before{inset:0;border-radius:0}}
|
||||
.puter-popup-frame[open] .puter-popup-frame-loading,.puter-popup-frame:not(.is-loading) .puter-popup-frame-box{animation:puter-popup-frame-in .16s ease-out}
|
||||
@keyframes puter-popup-frame-in{from{opacity:0}}
|
||||
@media (prefers-reduced-motion:reduce){.puter-popup-frame[open] .puter-popup-frame-loading,.puter-popup-frame:not(.is-loading) .puter-popup-frame-box{animation:none}}
|
||||
`;
|
||||
|
||||
const CLOSE_ICON = '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3.5 3.5l9 9m0-9l-9 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" fill="none"/></svg>';
|
||||
|
||||
// Subdomains the server answers or reserves itself, which it never lets frame
|
||||
// an embed (the backend's `isReservedSubdomain`). Framing from one would wait
|
||||
// on a refused frame before falling back.
|
||||
const RESERVED_LABELS = new Set(['www', 'api', 'js', 'dav', 'about', 'developer', 'docs', 'apps', 'puter-app-icons']);
|
||||
|
||||
// Dismisses the single-instance embed showing at each path.
|
||||
const showingEmbeds = new Map();
|
||||
|
||||
// Embed dialogs showing over the page, and the page's own styles to put back
|
||||
// once none is.
|
||||
const scrollLockers = new Set();
|
||||
let pageStyle = null;
|
||||
|
||||
/**
|
||||
* The element whose overflow the page's viewport uses: the body's while the
|
||||
* root's is `visible`. Hiding the root's then would make the body a scroller
|
||||
* of its own, which starts at the top.
|
||||
*
|
||||
* @returns {HTMLElement}
|
||||
*/
|
||||
const viewportOverflowElement = () => {
|
||||
const root = document.documentElement;
|
||||
const body = document.body;
|
||||
const visible = (el) => {
|
||||
const style = getComputedStyle(el);
|
||||
return style.overflowX === 'visible' && style.overflowY === 'visible';
|
||||
};
|
||||
return body && visible(root) && ! visible(body) ? body : root;
|
||||
};
|
||||
|
||||
/**
|
||||
* Stops the page scrolling behind `dialog` while it shows: Firefox and WebKit
|
||||
* pass a scroll over the frame on to the page, whatever the dialog's
|
||||
* `overscroll-behavior`. The root takes the width its scrollbar gave back as
|
||||
* padding, so the page doesn't shift. Returns the function that lets it scroll again.
|
||||
*
|
||||
* @param {HTMLDialogElement} dialog
|
||||
* @returns {() => void}
|
||||
*/
|
||||
const lockPageScroll = (dialog) => {
|
||||
const root = document.documentElement;
|
||||
const unlockPage = () => {
|
||||
const { scroller, overflow, overflowX, overflowY } = pageStyle;
|
||||
scroller.style.overflow = overflow;
|
||||
// A shorthand reads empty when the page set only one axis.
|
||||
if ( ! overflow ) {
|
||||
scroller.style.overflowX = overflowX;
|
||||
scroller.style.overflowY = overflowY;
|
||||
}
|
||||
root.style.paddingRight = pageStyle.paddingRight;
|
||||
pageStyle = null;
|
||||
};
|
||||
// One the page removed itself never unlocks, so the page's own styles
|
||||
// go back before they're read again.
|
||||
for ( const shown of scrollLockers ) if ( ! shown.isConnected ) scrollLockers.delete(shown);
|
||||
if ( scrollLockers.size === 0 && pageStyle ) unlockPage();
|
||||
if ( scrollLockers.size === 0 ) {
|
||||
const scroller = viewportOverflowElement();
|
||||
pageStyle = {
|
||||
scroller,
|
||||
overflow: scroller.style.overflow,
|
||||
overflowX: scroller.style.overflowX,
|
||||
overflowY: scroller.style.overflowY,
|
||||
paddingRight: root.style.paddingRight,
|
||||
};
|
||||
const hasScrollbar = window.innerWidth > root.clientWidth;
|
||||
const width = hasScrollbar ? root.getBoundingClientRect().width : 0;
|
||||
scroller.style.overflow = 'hidden';
|
||||
// Measured, since a gutter the page keeps (`scrollbar-gutter: stable`)
|
||||
// gives nothing back.
|
||||
const released = hasScrollbar ? root.getBoundingClientRect().width - width : 0;
|
||||
if ( released > 0 ) {
|
||||
const padding = parseFloat(getComputedStyle(root).paddingRight) || 0;
|
||||
root.style.paddingRight = `${padding + released}px`;
|
||||
}
|
||||
}
|
||||
scrollLockers.add(dialog);
|
||||
return () => {
|
||||
if ( ! scrollLockers.delete(dialog) ) return;
|
||||
for ( const shown of scrollLockers ) if ( ! shown.isConnected ) scrollLockers.delete(shown);
|
||||
if ( scrollLockers.size === 0 && pageStyle ) unlockPage();
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a page at `pageUrl` may frame an embed served by `guiOrigin`:
|
||||
* exactly one label under its host, on the same scheme and port, and not one
|
||||
* of the GUI's reserved subdomains.
|
||||
*
|
||||
* @param {string | undefined} pageUrl
|
||||
* @param {string} guiOrigin
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canFrameGuiEmbed = (pageUrl, guiOrigin) => {
|
||||
let page;
|
||||
let gui;
|
||||
try {
|
||||
page = new URL(pageUrl);
|
||||
gui = new URL(guiOrigin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const host = page.hostname.replace(/\.$/, '').toLowerCase();
|
||||
const suffix = `.${gui.hostname.toLowerCase()}`;
|
||||
if ( page.protocol !== gui.protocol || page.port !== gui.port || !host.endsWith(suffix) ) return false;
|
||||
const label = host.slice(0, -suffix.length);
|
||||
return label.length > 0 && !label.includes('.') && !RESERVED_LABELS.has(label);
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether every frame above `win` may frame an embed too. The server's
|
||||
* frame-ancestors allows only the GUI and the page, so in a frame of any other
|
||||
* site the embed is refused, and opening the popup straight away is faster.
|
||||
*
|
||||
* @param {Window} win - the page
|
||||
* @param {string} guiOrigin
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const ancestorsAllowGuiEmbed = (win, guiOrigin) => {
|
||||
let gui;
|
||||
try {
|
||||
gui = new URL(guiOrigin).origin;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const page = win.location.origin;
|
||||
const ancestors = win.location.ancestorOrigins;
|
||||
if ( ancestors ) return Array.from(ancestors).every((origin) => origin === page || origin === gui);
|
||||
// Without ancestorOrigins (Firefox), only a same-origin ancestor can be named.
|
||||
try {
|
||||
for ( let w = win; w.parent !== w; w = w.parent ) {
|
||||
if ( w.parent.location.origin !== page ) return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Mounts `/embed/<path>` in a modal frame, hidden until the embed reports
|
||||
* `ready` and behind a loading scrim once its start takes longer than
|
||||
* LOADING_DELAY_MS. Resolves what `onMessage` finishes with, what `dismissed`
|
||||
* returns when the user cancels, or null when the frame is refused, never
|
||||
* answers, or reports itself unavailable. Never rejects.
|
||||
*
|
||||
* @template T
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.guiOrigin
|
||||
* @param {string} opts.path - under the GUI origin, such as `/embed/feedback`
|
||||
* @param {Record<string, string>} opts.fragment - what the embed reads from its fragment
|
||||
* @param {string} opts.className - the dialog's class, prefixing its parts'
|
||||
* @param {string} opts.title - the frame's accessible name
|
||||
* @param {string} opts.stateMsg - `msg` of the embed's loading, ready and unavailable messages
|
||||
* @param {{ width: number, height: number }} [opts.box] - shows the frame in a box this size over a scrim; without it the frame covers the page and the embed draws its own scrim
|
||||
* @param {string} [opts.closeLabel] - puts a close button on the box, which dismisses it
|
||||
* @param {string} [opts.allow] - the frame's permissions policy, for features the embed uses
|
||||
* @param {boolean} [opts.escapeDismisses] - Escape on the page dismisses a ready embed too, instead of handing it the keys
|
||||
* @param {boolean} [opts.single] - a newer embed at this path dismisses this one, as a named popup window is reused
|
||||
* @param {() => T} opts.dismissed - the result of a dismissal: Escape or a click on the loading scrim, or the close button
|
||||
* @param {(data: Record<string, unknown>, finish: (result: T | null) => void) => void} opts.onMessage - every other message from the embed
|
||||
* @param {(frame: Window) => void} [opts.onFrame] - the frame's window, once it exists
|
||||
* @returns {Promise<T | null>}
|
||||
*/
|
||||
const mountGuiEmbed = ({ guiOrigin, path, fragment, className, title, stateMsg, box, closeLabel, allow, escapeDismisses = false, single = false, dismissed, onMessage, onFrame }) => new Promise((resolve) => {
|
||||
let origin;
|
||||
try {
|
||||
origin = new URL(guiOrigin).origin;
|
||||
} catch {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
const url = new URL(path, origin);
|
||||
url.hash = new URLSearchParams(fragment).toString();
|
||||
// Before reading the focus this one restores, which the older one hands back.
|
||||
if ( single ) showingEmbeds.get(path)?.();
|
||||
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.className = className;
|
||||
dialog.setAttribute('aria-label', title);
|
||||
// Inline, so the page's own `dialog` and `iframe` styles can't move,
|
||||
// round or shrink them.
|
||||
dialog.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;min-width:0;min-height:0;max-width:none;max-height:none;margin:0;padding:0;border:0;border-radius:0;box-shadow:none;transform:none;background:transparent;overflow:hidden;';
|
||||
const style = document.createElement('style');
|
||||
style.textContent = embedStyle(className) + (box ? BOX_STYLE : '');
|
||||
const frame = document.createElement('iframe');
|
||||
frame.title = title;
|
||||
// The embed allows a framing page it can name from the referrer.
|
||||
frame.setAttribute('referrerpolicy', 'origin');
|
||||
if ( allow ) frame.setAttribute('allow', allow);
|
||||
const frameBase = 'display:block;width:100%;height:100%;min-width:0;min-height:0;max-width:none;max-height:none;margin:0;padding:0;border:0;';
|
||||
// A frame whose color-scheme differs from its document's is painted
|
||||
// opaque, so this matches the embed's. WebKit also gives the frame this
|
||||
// scheme as its preferred one, so it has to follow the OS.
|
||||
frame.style.cssText = box
|
||||
? frameBase
|
||||
: `${frameBase}background:transparent;color-scheme:light dark;`;
|
||||
const loading = document.createElement('div');
|
||||
loading.className = `${className}-loading`;
|
||||
loading.setAttribute('role', 'status');
|
||||
loading.setAttribute('aria-label', 'Loading');
|
||||
loading.setAttribute('aria-hidden', 'true');
|
||||
loading.append(document.createElement('span'));
|
||||
dialog.append(style, loading);
|
||||
if ( box ) {
|
||||
const container = document.createElement('div');
|
||||
container.className = `${className}-box`;
|
||||
container.style.setProperty('--puter-popup-frame-width', `${box.width}px`);
|
||||
container.style.setProperty('--puter-popup-frame-height', `${box.height}px`);
|
||||
container.append(frame);
|
||||
if ( closeLabel ) {
|
||||
const close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = `${className}-close`;
|
||||
close.setAttribute('aria-label', closeLabel);
|
||||
close.title = closeLabel;
|
||||
close.innerHTML = CLOSE_ICON;
|
||||
close.addEventListener('click', () => dismiss());
|
||||
container.append(close);
|
||||
}
|
||||
dialog.append(container);
|
||||
} else {
|
||||
dialog.insertBefore(frame, loading);
|
||||
}
|
||||
|
||||
let settled = false;
|
||||
let heard = false;
|
||||
let shown = false;
|
||||
let ready = false;
|
||||
let timer = null;
|
||||
let loadingTimer = null;
|
||||
// Each embed document posts `loading` once; these tell a document that
|
||||
// never did (one the server refused) from one that did.
|
||||
let loads = 0;
|
||||
let boots = 0;
|
||||
let wasReady = false;
|
||||
let restarted = false;
|
||||
let restartTimer = null;
|
||||
let unlockScroll = null;
|
||||
// A dialog the page removes itself, such as by re-rendering its body,
|
||||
// counts as dismissed, so whoever awaits it isn't left waiting.
|
||||
const removal = new MutationObserver(() => {
|
||||
if ( ! dialog.isConnected ) dismiss();
|
||||
});
|
||||
const restoreFocus = document.activeElement;
|
||||
const wait = (ms) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => finish(null), ms);
|
||||
};
|
||||
const finish = (result) => {
|
||||
if ( settled ) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(loadingTimer);
|
||||
clearTimeout(restartTimer);
|
||||
removal.disconnect();
|
||||
window.removeEventListener('message', onWindowMessage);
|
||||
if ( showingEmbeds.get(path) === dismiss ) showingEmbeds.delete(path);
|
||||
dialog.remove();
|
||||
unlockScroll?.();
|
||||
if ( shown ) restoreFocus?.focus?.({ preventScroll: true });
|
||||
resolve(result);
|
||||
};
|
||||
const dismiss = () => finish(dismissed());
|
||||
if ( single ) showingEmbeds.set(path, dismiss);
|
||||
// The spinner is only faded out, so assistive tech hears it only while it shows.
|
||||
const setLoading = (on) => {
|
||||
dialog.classList.toggle('is-loading', on);
|
||||
if ( on ) loading.removeAttribute('aria-hidden');
|
||||
else loading.setAttribute('aria-hidden', 'true');
|
||||
};
|
||||
const show = () => {
|
||||
if ( dialog.open ) return;
|
||||
shown = true;
|
||||
dialog.showModal();
|
||||
unlockScroll = lockPageScroll(dialog);
|
||||
};
|
||||
const onWindowMessage = (event) => {
|
||||
if ( event.origin !== origin || event.source !== frame.contentWindow ) return;
|
||||
const data = event.data;
|
||||
if ( !data || typeof data !== 'object' ) return;
|
||||
if ( data.msg !== stateMsg || !['loading', 'ready', 'unavailable'].includes(data.state) ) {
|
||||
onMessage(data, finish);
|
||||
} else if ( data.state === 'loading' ) {
|
||||
heard = true;
|
||||
boots++;
|
||||
wait(READY_TIMEOUT_MS);
|
||||
} else if ( data.state === 'ready' ) {
|
||||
heard = true;
|
||||
ready = true;
|
||||
wasReady = true;
|
||||
restarted = false;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(loadingTimer);
|
||||
setLoading(false);
|
||||
show();
|
||||
frame.focus();
|
||||
} else {
|
||||
finish(null);
|
||||
}
|
||||
};
|
||||
// A reload or navigation the embed starts itself names the embed, not
|
||||
// this page, as its referrer, so the server refuses to let it frame. This
|
||||
// page opens the embed again, once, which it allows.
|
||||
const restart = () => {
|
||||
if ( restarted ) {
|
||||
finish(null);
|
||||
return;
|
||||
}
|
||||
restarted = true;
|
||||
ready = false;
|
||||
loads = boots;
|
||||
setLoading(true);
|
||||
// As long as its first start may take, then the popup.
|
||||
wait(READY_TIMEOUT_MS);
|
||||
// WebKit takes the refused URL itself as a fragment navigation of its
|
||||
// error page, which loads nothing. The server redirects a query away,
|
||||
// and the fragment carries over the redirect.
|
||||
const reopen = new URL(url);
|
||||
reopen.search = 'reopen';
|
||||
frame.src = reopen.href;
|
||||
};
|
||||
window.addEventListener('message', onWindowMessage);
|
||||
frame.addEventListener('load', () => {
|
||||
loads++;
|
||||
if ( ! heard ) wait(LOAD_GRACE_MS);
|
||||
if ( ! wasReady || boots >= loads ) return;
|
||||
// Most likely refused: the spinner covers the error page meanwhile.
|
||||
ready = false;
|
||||
setLoading(true);
|
||||
const expected = loads;
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = setTimeout(() => {
|
||||
if ( boots < expected ) restart();
|
||||
}, LOAD_GRACE_MS);
|
||||
});
|
||||
// Once ready, Escape outside the frame would close the dialog with the
|
||||
// embed's own dialog still open inside it, so the embed owns dismissal
|
||||
// unless it dismisses on Escape too.
|
||||
dialog.addEventListener('cancel', (event) => {
|
||||
event.preventDefault();
|
||||
if ( ready && ! escapeDismisses ) frame.focus();
|
||||
else dismiss();
|
||||
});
|
||||
loading.addEventListener('click', () => {
|
||||
if ( ! ready ) dismiss();
|
||||
});
|
||||
|
||||
try {
|
||||
frame.src = url.href;
|
||||
// Hidden at first, so a quickly refused session shows nothing.
|
||||
document.body.append(dialog);
|
||||
removal.observe(document.documentElement, { childList: true, subtree: true });
|
||||
onFrame?.(frame.contentWindow);
|
||||
wait(READY_TIMEOUT_MS);
|
||||
loadingTimer = setTimeout(() => {
|
||||
setLoading(true);
|
||||
show();
|
||||
}, LOADING_DELAY_MS);
|
||||
} catch {
|
||||
finish(null);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the app feedback dialog from `/embed/feedback` in a modal frame over
|
||||
* the page, as the user named, behind a loading scrim while a slow session
|
||||
* check runs. Resolves `{ sent }` once the dialog closes or the user cancels
|
||||
* the loading scrim, or null when the embed can't serve this user (no
|
||||
* matching Puter session, an email to confirm, or a refused frame), so the
|
||||
* caller can use the popup instead. Never rejects.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.guiOrigin
|
||||
* @param {string} opts.userUuid - the page's signed-in user
|
||||
* @returns {Promise<{ sent: boolean } | null>}
|
||||
*/
|
||||
export const showFeedbackEmbed = ({ guiOrigin, userUuid }) => mountGuiEmbed({
|
||||
guiOrigin,
|
||||
path: '/embed/feedback',
|
||||
fragment: { user: userUuid },
|
||||
className: 'puter-feedback-embed',
|
||||
title: 'Send feedback',
|
||||
stateMsg: 'feedbackEmbed',
|
||||
dismissed: () => ({ sent: false }),
|
||||
onMessage: ({ msg, sent }, finish) => {
|
||||
if ( msg === 'feedbackDialogClosed' ) finish({ sent: sent === true });
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Popup actions a first-party page shows framed, each in a box its popup
|
||||
* window's size. Any other covers the page, and its dialog draws its own scrim.
|
||||
*/
|
||||
const POPUP_FRAME_BOXES = {
|
||||
'sign-in': { width: 600, height: 700 },
|
||||
'show-open-file-picker': { width: 700, height: 400 },
|
||||
'show-save-file-picker': { width: 700, height: 400 },
|
||||
'show-directory-picker': { width: 700, height: 400 },
|
||||
};
|
||||
|
||||
// The upgrade has no box: it covers the page and its dialog draws its own
|
||||
// scrim. A payment in it may use the Payment Request API, which a frame can
|
||||
// use only when allowed, and Escape is left to the dialog, which doesn't close
|
||||
// mid-entry.
|
||||
const UNBOXED_POPUP_FRAMES = {
|
||||
upgrade: { allow: 'payment; otp-credentials', escapeDismisses: false },
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the GUI popup for `action` in a frame over the page instead of a
|
||||
* window, from `/embed/<action>`. The GUI runs the popup unchanged and posts
|
||||
* its answers to this page as it would to an opener; `onMessage` sees each of
|
||||
* them and finishes with the result. The frame closing on its own, as the
|
||||
* popup would, finishes with `closed(data)`, `data` being its closing
|
||||
* message, and the user dismissing it finishes with `closed()`. Resolves null
|
||||
* when the frame can't serve the request (refused, never answering, or
|
||||
* reporting itself unavailable), so the caller can open the popup instead.
|
||||
* Never rejects.
|
||||
*
|
||||
* @template T
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.guiOrigin
|
||||
* @param {'sign-in' | 'show-open-file-picker' | 'show-save-file-picker' | 'show-directory-picker' | 'upgrade' | 'request-email-confirmation'} opts.action
|
||||
* @param {Record<string, string>} opts.fragment - the popup's parameters, and `user` for a picker, the upgrade or the email confirmation
|
||||
* @param {string} opts.title - the frame's accessible name
|
||||
* @param {string} [opts.closeLabel] - puts a close button on the frame
|
||||
* @param {(data?: Record<string, unknown>) => T} opts.closed
|
||||
* @param {(data: Record<string, unknown>, finish: (result: T) => void) => void} opts.onMessage
|
||||
* @param {(frame: Window) => void} [opts.onFrame]
|
||||
* @returns {Promise<T | null>}
|
||||
*/
|
||||
export const showPopupFrame = ({ guiOrigin, action, fragment, title, closeLabel, closed, onMessage, onFrame }) => mountGuiEmbed({
|
||||
guiOrigin,
|
||||
path: `/embed/${action}`,
|
||||
fragment,
|
||||
className: 'puter-popup-frame',
|
||||
title,
|
||||
stateMsg: 'puterPopupFrame',
|
||||
box: POPUP_FRAME_BOXES[action],
|
||||
closeLabel,
|
||||
// Signup and the account checks fill in a texted code, as in the popup.
|
||||
allow: 'otp-credentials',
|
||||
// Escape inside the frame closes it as well.
|
||||
escapeDismisses: true,
|
||||
...UNBOXED_POPUP_FRAMES[action],
|
||||
// A second request for this popup, such as from a double click, replaces the
|
||||
// first. Each popup has its own window name, so other popups stay open.
|
||||
single: true,
|
||||
dismissed: () => closed(),
|
||||
onFrame,
|
||||
onMessage: (data, finish) => {
|
||||
if ( data.msg === 'puterPopupFrame' && data.state === 'closed' ) finish(closed(data));
|
||||
else onMessage(data, finish);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,622 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ancestorsAllowGuiEmbed, canFrameGuiEmbed, showFeedbackEmbed, showPopupFrame } from './guiEmbed.js';
|
||||
|
||||
const GUI_ORIGIN = 'https://puter.test';
|
||||
const USER = '0b1c9a52-3f0e-4c7a-9a65-2f6d1e8b7c40';
|
||||
|
||||
// jsdom has no top-layer dialogs.
|
||||
HTMLDialogElement.prototype.showModal = function () {
|
||||
this.open = true;
|
||||
};
|
||||
|
||||
const frame = () => document.querySelector('dialog.puter-feedback-embed iframe');
|
||||
|
||||
/** A message from the embed, by default from its frame on the GUI origin. */
|
||||
const fromEmbed = (data, { origin = GUI_ORIGIN, source = frame().contentWindow } = {}) =>
|
||||
window.dispatchEvent(new MessageEvent('message', { data, origin, source }));
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('canFrameGuiEmbed', () => {
|
||||
it.each([
|
||||
['https://notes.puter.com/a', 'https://puter.com', true],
|
||||
['https://NOTES.puter.com./a', 'https://puter.com', true],
|
||||
['http://notes.puter.localhost:4100/', 'http://puter.localhost:4100', true],
|
||||
['https://puter.com/', 'https://puter.com', false],
|
||||
['https://a.b.puter.com/', 'https://puter.com', false],
|
||||
['https://notputer.com/', 'https://puter.com', false],
|
||||
['https://notes.puter.com.evil.com/', 'https://puter.com', false],
|
||||
['http://notes.puter.com/', 'https://puter.com', false],
|
||||
['https://notes.puter.com:8443/', 'https://puter.com', false],
|
||||
['https://notes.puter.site/', 'https://puter.com', false],
|
||||
['https://docs.puter.com/playground/', 'https://puter.com', false],
|
||||
['https://api.puter.com/', 'https://puter.com', false],
|
||||
['https://www.puter.com/', 'https://puter.com', false],
|
||||
['http://apps.puter.localhost:4100/', 'http://puter.localhost:4100', false],
|
||||
[undefined, 'https://puter.com', false],
|
||||
])('%s under %s is %s', (page, gui, expected) => {
|
||||
expect(canFrameGuiEmbed(page, gui)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ancestorsAllowGuiEmbed', () => {
|
||||
const PAGE = 'https://notes.puter.test';
|
||||
/** A window at `origin` under `parent`; a cross-origin parent throws on `location`, as in a browser. */
|
||||
const fakeWindow = ({ origin = PAGE, ancestorOrigins, parent } = {}) => {
|
||||
const win = { location: { origin, ancestorOrigins } };
|
||||
win.parent = parent ?? win;
|
||||
return win;
|
||||
};
|
||||
const crossOrigin = () => {
|
||||
const win = {};
|
||||
Object.defineProperty(win, 'location', { get: () => { throw new DOMException('Blocked', 'SecurityError'); } });
|
||||
win.parent = win;
|
||||
return win;
|
||||
};
|
||||
|
||||
it.each([
|
||||
['a top-level page', [], true],
|
||||
['a frame of the same page', [PAGE], true],
|
||||
['a frame in the GUI', [PAGE, GUI_ORIGIN], true],
|
||||
['a frame of another site', ['https://other.test'], false],
|
||||
['a frame of the page inside another site', [PAGE, 'https://other.test'], false],
|
||||
])('reads ancestorOrigins for %s', (_, ancestorOrigins, expected) => {
|
||||
expect(ancestorsAllowGuiEmbed(fakeWindow({ ancestorOrigins }), GUI_ORIGIN)).toBe(expected);
|
||||
});
|
||||
|
||||
it('walks same-origin parents without ancestorOrigins', () => {
|
||||
expect(ancestorsAllowGuiEmbed(fakeWindow(), GUI_ORIGIN)).toBe(true);
|
||||
expect(ancestorsAllowGuiEmbed(fakeWindow({ parent: fakeWindow() }), GUI_ORIGIN)).toBe(true);
|
||||
expect(ancestorsAllowGuiEmbed(fakeWindow({ parent: crossOrigin() }), GUI_ORIGIN)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('showFeedbackEmbed', () => {
|
||||
it('loads the embed for the named user, hidden until it is ready', () => {
|
||||
showFeedbackEmbed({ guiOrigin: `${GUI_ORIGIN}/`, userUuid: USER });
|
||||
const url = new URL(frame().src);
|
||||
expect(url.origin + url.pathname).toBe(`${GUI_ORIGIN}/embed/feedback`);
|
||||
expect(url.search).toBe('');
|
||||
expect(new URLSearchParams(url.hash.slice(1)).get('user')).toBe(USER);
|
||||
expect(frame().getAttribute('referrerpolicy')).toBe('origin');
|
||||
// WebKit hands the frame this as its preferred scheme; it must follow the OS.
|
||||
expect(frame().getAttribute('style')).toContain('color-scheme: light dark');
|
||||
expect(frame().closest('dialog').open).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the dialog once ready and resolves what it reports, restoring focus', async () => {
|
||||
const trigger = document.createElement('button');
|
||||
document.body.append(trigger);
|
||||
trigger.focus();
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
const dialog = frame().closest('dialog');
|
||||
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'loading' });
|
||||
expect(dialog.open).toBe(false);
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'ready' });
|
||||
expect(dialog.open).toBe(true);
|
||||
expect(document.activeElement).toBe(frame());
|
||||
|
||||
fromEmbed({ msg: 'feedbackDialogClosed', sent: true });
|
||||
await expect(result).resolves.toEqual({ sent: true });
|
||||
expect(dialog.isConnected).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
});
|
||||
|
||||
it('shows a loading scrim over the page while a slow session check runs, then the dialog', async () => {
|
||||
vi.useFakeTimers();
|
||||
const trigger = document.createElement('button');
|
||||
document.body.append(trigger);
|
||||
trigger.focus();
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
const dialog = frame().closest('dialog');
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'loading' });
|
||||
await vi.advanceTimersByTimeAsync(199);
|
||||
expect(dialog.open).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(dialog.open).toBe(true);
|
||||
expect(dialog.classList.contains('is-loading')).toBe(true);
|
||||
expect(dialog.querySelector('[role="status"]').hasAttribute('aria-hidden')).toBe(false);
|
||||
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'ready' });
|
||||
expect(dialog.classList.contains('is-loading')).toBe(false);
|
||||
expect(dialog.querySelector('[role="status"]').getAttribute('aria-hidden')).toBe('true');
|
||||
expect(document.activeElement).toBe(frame());
|
||||
fromEmbed({ msg: 'feedbackDialogClosed', sent: true });
|
||||
await expect(result).resolves.toEqual({ sent: true });
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
});
|
||||
|
||||
it('never shows the loading scrim when the embed is ready quickly', async () => {
|
||||
vi.useFakeTimers();
|
||||
showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
const dialog = frame().closest('dialog');
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'ready' });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(dialog.open).toBe(true);
|
||||
expect(dialog.classList.contains('is-loading')).toBe(false);
|
||||
});
|
||||
|
||||
it('takes the loading scrim down for the popup when the embed turns out unavailable', async () => {
|
||||
vi.useFakeTimers();
|
||||
const trigger = document.createElement('button');
|
||||
document.body.append(trigger);
|
||||
trigger.focus();
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'unavailable' });
|
||||
await expect(result).resolves.toBeNull();
|
||||
expect(document.querySelector('dialog')).toBeNull();
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Escape', (dialog) => dialog.dispatchEvent(new Event('cancel', { cancelable: true }))],
|
||||
['a click on the scrim', (dialog) => dialog.querySelector('[role="status"]').click()],
|
||||
])('lets %s cancel while loading, without falling back to the popup', async (_label, cancel) => {
|
||||
vi.useFakeTimers();
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
cancel(frame().closest('dialog'));
|
||||
await expect(result).resolves.toEqual({ sent: false });
|
||||
expect(document.querySelector('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves null without showing anything when the embed is unavailable', async () => {
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
const dialog = frame().closest('dialog');
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'loading' });
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'unavailable' });
|
||||
await expect(result).resolves.toBeNull();
|
||||
expect(dialog.open).toBe(false);
|
||||
expect(dialog.isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores messages from another origin or another window', async () => {
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
fromEmbed({ msg: 'feedbackDialogClosed', sent: true }, { origin: 'https://other.test' });
|
||||
fromEmbed({ msg: 'feedbackDialogClosed', sent: true }, { source: window });
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'ready' }, { origin: 'https://notes.puter.test' });
|
||||
expect(frame().closest('dialog').open).toBe(false);
|
||||
|
||||
fromEmbed({ msg: 'feedbackDialogClosed', sent: false });
|
||||
await expect(result).resolves.toEqual({ sent: false });
|
||||
});
|
||||
|
||||
it('resolves null when the frame loads without the embed answering', async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
frame().dispatchEvent(new Event('load'));
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
await expect(result).resolves.toBeNull();
|
||||
expect(document.querySelector('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('gives a loading embed time to check the session, then gives up', async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'loading' });
|
||||
frame().dispatchEvent(new Event('load'));
|
||||
let settled = false;
|
||||
result.then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
await expect(result).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the dialog open on Escape outside the frame, since the embed owns dismissal', () => {
|
||||
showFeedbackEmbed({ guiOrigin: GUI_ORIGIN, userUuid: USER });
|
||||
fromEmbed({ msg: 'feedbackEmbed', state: 'ready' });
|
||||
const dialog = frame().closest('dialog');
|
||||
const cancel = new Event('cancel', { cancelable: true });
|
||||
dialog.dispatchEvent(cancel);
|
||||
expect(cancel.defaultPrevented).toBe(true);
|
||||
expect(dialog.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it('resolves null for an unusable GUI origin', async () => {
|
||||
await expect(showFeedbackEmbed({ guiOrigin: 'not a url', userUuid: USER })).resolves.toBeNull();
|
||||
expect(document.querySelector('dialog')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('showPopupFrame', () => {
|
||||
const popupFrame = () => document.querySelector('dialog.puter-popup-frame iframe');
|
||||
const fromPopup = (data, { origin = GUI_ORIGIN, source = popupFrame().contentWindow } = {}) =>
|
||||
window.dispatchEvent(new MessageEvent('message', { data, origin, source }));
|
||||
const show = (overrides = {}) => showPopupFrame({
|
||||
guiOrigin: GUI_ORIGIN,
|
||||
action: 'show-open-file-picker',
|
||||
fragment: { msg_id: '3', user: USER },
|
||||
title: 'Open file',
|
||||
closed: () => 'closed',
|
||||
onMessage: () => {},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('loads the popup action with its parameters in the fragment, hidden until ready', () => {
|
||||
let framed;
|
||||
show({ onFrame: (win) => {
|
||||
framed = win;
|
||||
} });
|
||||
const url = new URL(popupFrame().src);
|
||||
expect(url.origin + url.pathname).toBe(`${GUI_ORIGIN}/embed/show-open-file-picker`);
|
||||
expect(url.search).toBe('');
|
||||
expect(Object.fromEntries(new URLSearchParams(url.hash.slice(1)))).toEqual({ msg_id: '3', user: USER });
|
||||
expect(popupFrame().getAttribute('referrerpolicy')).toBe('origin');
|
||||
expect(popupFrame().closest('dialog').getAttribute('aria-label')).toBe('Open file');
|
||||
expect(popupFrame().getAttribute('allow')).toBe('otp-credentials');
|
||||
expect(framed).toBe(popupFrame().contentWindow);
|
||||
expect(popupFrame().closest('dialog').open).toBe(false);
|
||||
});
|
||||
|
||||
it('sizes the box like the popup window it replaces', () => {
|
||||
show({ action: 'sign-in', fragment: { msg_id: 'a' } });
|
||||
const box = document.querySelector('.puter-popup-frame-box');
|
||||
expect(box.style.getPropertyValue('--puter-popup-frame-width')).toBe('600px');
|
||||
expect(box.style.getPropertyValue('--puter-popup-frame-height')).toBe('700px');
|
||||
expect(box.contains(popupFrame())).toBe(true);
|
||||
});
|
||||
|
||||
it('shows once ready and hands every other message to the caller to finish with', async () => {
|
||||
const seen = [];
|
||||
const result = show({ onMessage: (data, finish) => {
|
||||
seen.push(data.msg);
|
||||
if ( data.msg === 'fileOpenPicked' ) finish('picked');
|
||||
} });
|
||||
const dialog = popupFrame().closest('dialog');
|
||||
const status = dialog.querySelector('[role="status"]');
|
||||
expect(status.getAttribute('aria-hidden')).toBe('true');
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
expect(dialog.open).toBe(true);
|
||||
expect(status.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(document.activeElement).toBe(popupFrame());
|
||||
fromPopup({ msg: 'puter.token', success: true });
|
||||
fromPopup({ msg: 'fileOpenPicked' });
|
||||
await expect(result).resolves.toBe('picked');
|
||||
expect(seen).toEqual(['puter.token', 'fileOpenPicked']);
|
||||
expect(dialog.isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('opens itself again when the embed reloads into a refused frame, once per ready', async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = show();
|
||||
const iframe = popupFrame();
|
||||
const dialog = iframe.closest('dialog');
|
||||
const srcSet = vi.spyOn(iframe, 'src', 'set');
|
||||
const load = () => iframe.dispatchEvent(new Event('load'));
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
load();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
|
||||
// A reload the embed starts itself loads a document that never posts.
|
||||
load();
|
||||
expect(dialog.classList.contains('is-loading')).toBe(true);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(srcSet).toHaveBeenCalledTimes(1);
|
||||
// Not just the refused URL again, which WebKit takes as a fragment
|
||||
// navigation of the error page: the server redirects the query away.
|
||||
const opened = new URL(iframe.src);
|
||||
const reopened = new URL(srcSet.mock.calls[0][0]);
|
||||
expect(reopened.search).not.toBe('');
|
||||
expect(reopened.origin + reopened.pathname + reopened.hash).toBe(opened.origin + opened.pathname + opened.hash);
|
||||
expect(dialog.classList.contains('is-loading')).toBe(true);
|
||||
|
||||
// The page's own reload boots, before or after its load event.
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
load();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(srcSet).toHaveBeenCalledTimes(1);
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
expect(dialog.classList.contains('is-loading')).toBe(false);
|
||||
|
||||
// Ready again, so a later refusal is retried too, but not twice running.
|
||||
load();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(srcSet).toHaveBeenCalledTimes(2);
|
||||
load();
|
||||
vi.advanceTimersByTime(1000);
|
||||
await expect(result).resolves.toBeNull();
|
||||
expect(srcSet).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('falls back to the popup when the embed it opens again never loads', async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = show();
|
||||
const iframe = popupFrame();
|
||||
const dialog = iframe.closest('dialog');
|
||||
const load = () => iframe.dispatchEvent(new Event('load'));
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
load();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
|
||||
// Refused after a reload of its own, then reopened on a stalled connection.
|
||||
load();
|
||||
vi.advanceTimersByTime(1000);
|
||||
vi.advanceTimersByTime(14_999);
|
||||
expect(dialog.isConnected).toBe(true);
|
||||
vi.advanceTimersByTime(1);
|
||||
await expect(result).resolves.toBeNull();
|
||||
expect(dialog.isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps showing an embed that was ready before its load event fired', () => {
|
||||
vi.useFakeTimers();
|
||||
show();
|
||||
const iframe = popupFrame();
|
||||
const dialog = iframe.closest('dialog');
|
||||
const srcSet = vi.spyOn(iframe, 'src', 'set');
|
||||
const load = () => iframe.dispatchEvent(new Event('load'));
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
load();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
load();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(srcSet).toHaveBeenCalledTimes(1);
|
||||
|
||||
// The page's reload shows its UI while a slow image still loads.
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
load();
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(dialog.classList.contains('is-loading')).toBe(false);
|
||||
expect(srcSet).toHaveBeenCalledTimes(1);
|
||||
expect(dialog.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it('closes on Escape outside the frame once ready, as Escape inside it does', async () => {
|
||||
const result = show();
|
||||
const dialog = popupFrame().closest('dialog');
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
const cancel = new Event('cancel', { cancelable: true });
|
||||
dialog.dispatchEvent(cancel);
|
||||
expect(cancel.defaultPrevented).toBe(true);
|
||||
await expect(result).resolves.toBe('closed');
|
||||
expect(dialog.isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('finishes as closed when the popup closes itself', async () => {
|
||||
const result = show();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(result).resolves.toBe('closed');
|
||||
expect(document.querySelector('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('offers a close button only when asked, which finishes as closed', async () => {
|
||||
show();
|
||||
expect(document.querySelector('.puter-popup-frame-close')).toBeNull();
|
||||
document.body.innerHTML = '';
|
||||
|
||||
const result = show({ action: 'sign-in', closeLabel: 'Close' });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
const close = document.querySelector('.puter-popup-frame-close');
|
||||
expect(close.getAttribute('aria-label')).toBe('Close');
|
||||
close.click();
|
||||
await expect(result).resolves.toBe('closed');
|
||||
});
|
||||
|
||||
it('resolves null for the popup when the frame is unavailable or refused', async () => {
|
||||
const unavailable = show();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
await expect(unavailable).resolves.toBeNull();
|
||||
|
||||
vi.useFakeTimers();
|
||||
const refused = show();
|
||||
popupFrame().dispatchEvent(new Event('load'));
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
await expect(refused).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('lets the user dismiss the loading scrim, finishing as closed', async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = show();
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
document.querySelector('.puter-popup-frame-loading').click();
|
||||
await expect(result).resolves.toBe('closed');
|
||||
});
|
||||
|
||||
it('replaces a popup frame that is showing, finishing it as closed', async () => {
|
||||
const button = document.createElement('button');
|
||||
document.body.append(button);
|
||||
button.focus();
|
||||
const first = show();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
const firstDialog = popupFrame().closest('dialog');
|
||||
const second = show({ fragment: { msg_id: '4', user: USER } });
|
||||
await expect(first).resolves.toBe('closed');
|
||||
expect(firstDialog.isConnected).toBe(false);
|
||||
expect(document.querySelectorAll('dialog.puter-popup-frame')).toHaveLength(1);
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(second).resolves.toBe('closed');
|
||||
expect(document.activeElement).toBe(button);
|
||||
});
|
||||
|
||||
it('leaves a popup frame for another action showing, as its popup window would stay open', async () => {
|
||||
const picker = show();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
const pickerFrame = popupFrame();
|
||||
const signIn = show({ action: 'sign-in', fragment: { msg_id: 'a' } });
|
||||
expect(document.querySelectorAll('dialog.puter-popup-frame')).toHaveLength(2);
|
||||
const signInFrame = document.querySelectorAll('dialog.puter-popup-frame iframe')[1];
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'closed' }, { source: signInFrame.contentWindow });
|
||||
await expect(signIn).resolves.toBe('closed');
|
||||
expect(pickerFrame.isConnected).toBe(true);
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'closed' }, { source: pickerFrame.contentWindow });
|
||||
await expect(picker).resolves.toBe('closed');
|
||||
});
|
||||
|
||||
it('finishes as closed when the page removes it, letting the page scroll again', async () => {
|
||||
const result = show({ action: 'upgrade', fragment: { user: USER } });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
expect(document.documentElement.style.overflow).toBe('hidden');
|
||||
document.body.innerHTML = '<main>re-rendered</main>';
|
||||
await expect(result).resolves.toBe('closed');
|
||||
expect(document.documentElement.style.overflow).toBe('');
|
||||
});
|
||||
|
||||
it('keeps the scrim behind a ready frame from dismissing it', () => {
|
||||
show();
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
document.querySelector('.puter-popup-frame-loading').click();
|
||||
expect(popupFrame().closest('dialog').isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores messages from another origin or another window', async () => {
|
||||
const onMessage = vi.fn();
|
||||
show({ onMessage });
|
||||
fromPopup({ msg: 'puterPopupFrame', state: 'closed' }, { origin: 'https://other.test' });
|
||||
fromPopup({ msg: 'fileOpenPicked' }, { source: window });
|
||||
expect(onMessage).not.toHaveBeenCalled();
|
||||
expect(popupFrame().closest('dialog').isConnected).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('page scroll behind an embed', () => {
|
||||
const root = document.documentElement;
|
||||
const popupFrame = (action) => document.querySelector(`dialog.puter-popup-frame iframe[src*="/embed/${action}"]`);
|
||||
const show = (action, closed = () => 'closed') => showPopupFrame({
|
||||
guiOrigin: GUI_ORIGIN,
|
||||
action,
|
||||
fragment: { user: USER },
|
||||
title: action,
|
||||
closed,
|
||||
onMessage: () => {},
|
||||
});
|
||||
const tell = (action, state) => window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'puterPopupFrame', state },
|
||||
origin: GUI_ORIGIN,
|
||||
source: popupFrame(action).contentWindow,
|
||||
}));
|
||||
/**
|
||||
* Gives the page a classic scrollbar this wide, or none, whose space comes
|
||||
* back once the root stops scrolling unless the page keeps its gutter.
|
||||
*/
|
||||
const scrollbar = (width, { gutterKept = false } = {}) => {
|
||||
vi.spyOn(root, 'clientWidth', 'get').mockReturnValue(window.innerWidth - width);
|
||||
vi.spyOn(root, 'getBoundingClientRect').mockImplementation(() => ({
|
||||
width: window.innerWidth - (root.style.overflow === 'hidden' && ! gutterKept ? 0 : width),
|
||||
}));
|
||||
};
|
||||
|
||||
// Earlier tests leave dialogs that never closed, which locked the page.
|
||||
beforeEach(() => {
|
||||
root.removeAttribute('style');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
root.removeAttribute('style');
|
||||
document.body.removeAttribute('style');
|
||||
});
|
||||
|
||||
it('stops while the embed shows and comes back as the page had it once it closes', async () => {
|
||||
scrollbar(0);
|
||||
root.style.overflow = 'clip';
|
||||
const result = show('upgrade');
|
||||
tell('upgrade', 'loading');
|
||||
expect(root.style.overflow).toBe('clip');
|
||||
|
||||
tell('upgrade', 'ready');
|
||||
expect(root.style.overflow).toBe('hidden');
|
||||
expect(root.style.paddingRight).toBe('');
|
||||
|
||||
tell('upgrade', 'closed');
|
||||
await expect(result).resolves.toBe('closed');
|
||||
expect(root.style.overflow).toBe('clip');
|
||||
});
|
||||
|
||||
it('stops the body instead when the viewport scrolls by the body\'s overflow', async () => {
|
||||
scrollbar(0);
|
||||
root.style.overflow = 'visible';
|
||||
document.body.style.overflowX = 'hidden';
|
||||
const result = show('upgrade');
|
||||
tell('upgrade', 'ready');
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
expect(root.style.overflow).toBe('visible');
|
||||
|
||||
tell('upgrade', 'closed');
|
||||
await result;
|
||||
expect(document.body.style.overflowX).toBe('hidden');
|
||||
expect(document.body.style.overflowY).toBe('');
|
||||
});
|
||||
|
||||
it('keeps the space of a classic scrollbar, so the page doesn\'t shift', async () => {
|
||||
scrollbar(15);
|
||||
root.style.paddingRight = '8px';
|
||||
const result = show('upgrade');
|
||||
tell('upgrade', 'ready');
|
||||
expect(root.style.overflow).toBe('hidden');
|
||||
expect(root.style.paddingRight).toBe('23px');
|
||||
tell('upgrade', 'closed');
|
||||
await result;
|
||||
expect(root.style.paddingRight).toBe('8px');
|
||||
expect(root.style.overflow).toBe('');
|
||||
});
|
||||
|
||||
it('adds no space for a scrollbar whose gutter the page keeps', async () => {
|
||||
scrollbar(15, { gutterKept: true });
|
||||
const result = show('upgrade');
|
||||
tell('upgrade', 'ready');
|
||||
expect(root.style.overflow).toBe('hidden');
|
||||
expect(root.style.paddingRight).toBe('');
|
||||
tell('upgrade', 'closed');
|
||||
await result;
|
||||
});
|
||||
|
||||
it('stops behind the loading scrim too, and stays stopped until the last embed closes', async () => {
|
||||
vi.useFakeTimers();
|
||||
scrollbar(0);
|
||||
const upgrade = show('upgrade');
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(root.style.overflow).toBe('hidden');
|
||||
const signIn = show('sign-in');
|
||||
tell('sign-in', 'ready');
|
||||
|
||||
tell('sign-in', 'closed');
|
||||
await signIn;
|
||||
expect(root.style.overflow).toBe('hidden');
|
||||
tell('upgrade', 'closed');
|
||||
await upgrade;
|
||||
expect(root.style.overflow).toBe('');
|
||||
});
|
||||
|
||||
it('gives the page its own styles back after an embed the page removed itself', async () => {
|
||||
scrollbar(15);
|
||||
root.style.paddingRight = '8px';
|
||||
show('upgrade');
|
||||
tell('upgrade', 'ready');
|
||||
document.querySelector('dialog.puter-popup-frame').remove();
|
||||
|
||||
const signIn = show('sign-in');
|
||||
tell('sign-in', 'ready');
|
||||
expect(root.style.overflow).toBe('hidden');
|
||||
expect(root.style.paddingRight).toBe('23px');
|
||||
tell('sign-in', 'closed');
|
||||
await signIn;
|
||||
|
||||
expect(root.style.overflow).toBe('');
|
||||
expect(root.style.paddingRight).toBe('8px');
|
||||
});
|
||||
|
||||
it('leaves the page alone for an embed that never showed', async () => {
|
||||
scrollbar(0);
|
||||
const result = show('upgrade');
|
||||
tell('upgrade', 'unavailable');
|
||||
await expect(result).resolves.toBeNull();
|
||||
expect(root.style.overflow).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,23 @@
|
||||
* @property {string} [message] One sentence saying what was refused and why.
|
||||
*/
|
||||
|
||||
/**
|
||||
* How a framed upgrade on a first-party page ended.
|
||||
*
|
||||
* @typedef {Object} UpgradeResult
|
||||
* @property {boolean} upgraded `true` when the user subscribed to a plan or upgraded to a higher
|
||||
* one before closing the dialog. `false` otherwise, including after a downgrade or cancellation,
|
||||
* or when the upgrade opened in a new tab instead.
|
||||
*/
|
||||
|
||||
/**
|
||||
* How `puter.ui.requestEmailConfirmation()` ended.
|
||||
*
|
||||
* @typedef {Object} EmailConfirmationResult
|
||||
* @property {boolean} response `true` when the user's email is confirmed, including when it already
|
||||
* was. `false` when the user closed the dialog first, or when a website couldn't show it.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The legacy positional callbacks most methods accept alongside the promise
|
||||
* they return.
|
||||
|
||||
@@ -26,7 +26,7 @@ import { showUsageLimitDialog } from '../modules/UsageLimitDialog.js';
|
||||
*
|
||||
* @typedef {{
|
||||
* env?: string,
|
||||
* ui?: { requestUpgrade: Function },
|
||||
* ui?: { requestUpgrade: Function, canShowUpgradeFrame_?: () => boolean, upgradeFrameShowing_?: () => boolean },
|
||||
* authToken?: string,
|
||||
* appID?: string,
|
||||
* getAppIDFromAuthToken?: (token: unknown) => string | null,
|
||||
@@ -109,7 +109,8 @@ const messageFor = (reason, error, context) => {
|
||||
* Inside an app the desktop's upgrade flow is asked for (and not awaited: it
|
||||
* never answers). The SDK's own dialog covers storage refusals everywhere
|
||||
* else - the desktop leans on it for those - and funding / plan refusals on
|
||||
* third-party sites only. The error is not consumed; callers still reject.
|
||||
* websites only. On a first-party page its Upgrade button shows the upgrade
|
||||
* in a frame over the page. The error is not consumed; callers still reject.
|
||||
*
|
||||
* @param {unknown} error The rejection, in whatever shape it arrived.
|
||||
* @param {UpgradePromptContext} [context] Which SDK method was refused and,
|
||||
@@ -127,11 +128,26 @@ export const promptIfUpgradeRequired = (error, context = {}, puter = globalThis.
|
||||
if ( puter?.env === 'app' ) {
|
||||
puter.ui.requestUpgrade({ reason, method, message });
|
||||
} else if ( puter?.env === 'web' || reason === 'storage' ) {
|
||||
// The upgrade a first-party page already shows answers this refusal
|
||||
// too, and a dialog over it would block it.
|
||||
if ( puter.ui?.upgradeFrameShowing_?.() === true ) return;
|
||||
// A first-party page shows the upgrade in a frame over itself
|
||||
// instead of a dashboard tab.
|
||||
const framed = puter?.env === 'web' && puter.ui?.canShowUpgradeFrame_?.() === true;
|
||||
showUsageLimitDialog(message, {
|
||||
title: TITLES[reason],
|
||||
method,
|
||||
reason,
|
||||
appID: appIDOf(puter),
|
||||
...(framed ? {
|
||||
// The page may have stopped being able to frame it, such as
|
||||
// by signing out, since the dialog opened.
|
||||
onUpgrade: () => {
|
||||
if ( puter.ui.canShowUpgradeFrame_?.() !== true ) return false;
|
||||
puter.ui.requestUpgrade({ reason, method, message });
|
||||
return true;
|
||||
},
|
||||
} : {}),
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -143,5 +159,5 @@ export const promptIfUpgradeRequired = (error, context = {}, puter = globalThis.
|
||||
* @param {PromptingSdk | undefined} puter
|
||||
* @returns {string | undefined}
|
||||
*/
|
||||
const appIDOf = (puter) =>
|
||||
export const appIDOf = (puter) =>
|
||||
puter?.getAppIDFromAuthToken?.(puter.authToken) || puter?.appID || undefined;
|
||||
@@ -179,6 +179,57 @@ describe('promptIfUpgradeRequired', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('on a first-party page that can frame the upgrade', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.puter = {
|
||||
env: 'web',
|
||||
ui: { requestUpgrade: vi.fn(), canShowUpgradeFrame_: () => true },
|
||||
};
|
||||
});
|
||||
|
||||
it('has the dialog ask for the framed upgrade instead of opening a tab', () => {
|
||||
promptIfUpgradeRequired({ code: 'insufficient_funds', status: 402 }, { method: 'puter.ai.chat' });
|
||||
expect(globalThis.puter.ui.requestUpgrade).not.toHaveBeenCalled();
|
||||
const [message, options] = showUsageLimitDialog.mock.calls[0];
|
||||
expect(message).toBe('Your account does not have enough funding to complete this request.');
|
||||
expect(options).toMatchObject({ title: 'Low Balance', method: 'puter.ai.chat', reason: 'funds' });
|
||||
|
||||
expect(options.onUpgrade()).toBe(true);
|
||||
expect(globalThis.puter.ui.requestUpgrade).toHaveBeenCalledWith({
|
||||
reason: 'funds',
|
||||
method: 'puter.ai.chat',
|
||||
message: 'Your account does not have enough funding to complete this request.',
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves the tab to the dialog when the page can no longer frame it by the click', () => {
|
||||
promptIfUpgradeRequired({ code: 'insufficient_funds', status: 402 }, { method: 'puter.ai.chat' });
|
||||
globalThis.puter.ui.canShowUpgradeFrame_ = () => false;
|
||||
expect(showUsageLimitDialog.mock.calls[0][1].onUpgrade()).toBe(false);
|
||||
expect(globalThis.puter.ui.requestUpgrade).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows no dialog over an upgrade the page already shows', () => {
|
||||
globalThis.puter.ui.upgradeFrameShowing_ = () => true;
|
||||
promptIfUpgradeRequired({ code: 'insufficient_funds', status: 402 }, { method: 'puter.ai.chat' });
|
||||
promptIfUpgradeRequired({ code: 'storage_limit_reached' }, { method: 'puter.fs.upload' });
|
||||
expect(showUsageLimitDialog).not.toHaveBeenCalled();
|
||||
expect(globalThis.puter.ui.requestUpgrade).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the tab when the page cannot frame it', () => {
|
||||
globalThis.puter.ui.canShowUpgradeFrame_ = () => false;
|
||||
promptIfUpgradeRequired({ code: 'storage_limit_reached' }, { method: 'puter.fs.upload' });
|
||||
expect(showUsageLimitDialog.mock.calls[0][1]).not.toHaveProperty('onUpgrade');
|
||||
});
|
||||
|
||||
it('keeps the tab for a storage refusal outside a website', () => {
|
||||
globalThis.puter.env = 'gui';
|
||||
promptIfUpgradeRequired({ code: 'storage_limit_reached' }, { method: 'puter.fs.upload' });
|
||||
expect(showUsageLimitDialog.mock.calls[0][1]).not.toHaveProperty('onUpgrade');
|
||||
});
|
||||
});
|
||||
|
||||
it('does nothing for a rejection an upgrade would not clear', () => {
|
||||
promptIfUpgradeRequired({ status: 403 });
|
||||
promptIfUpgradeRequired(new Error('offline'));
|
||||
|
||||
@@ -3,6 +3,7 @@ import { fetchUrl } from '../lib/networkUtils.js';
|
||||
import { PuterModule } from '../lib/PuterModule.js';
|
||||
import PuterDialog from './PuterDialog.js';
|
||||
import { hasOpaqueOrigin } from '../lib/auth-popup.js';
|
||||
import { ancestorsAllowGuiEmbed, canFrameGuiEmbed, showPopupFrame } from '../lib/guiEmbed.js';
|
||||
|
||||
/**
|
||||
* Puter user details, as returned by `getUser()`.
|
||||
@@ -115,12 +116,19 @@ export class AuthModule extends PuterModule {
|
||||
/** @internal */
|
||||
pendingSignInMessageIds_ = new Set();
|
||||
|
||||
/** The framed sign-in in progress, which a repeated call joins. */
|
||||
#framedSignIn = null;
|
||||
|
||||
/**
|
||||
* Signs the user in, opening a popup with the appropriate authentication
|
||||
* method. Must be called from a user gesture (such as a click) — without
|
||||
* one, a consent dialog is shown first so the popup can be opened from the
|
||||
* user's click on it. Resolves once the user has signed in.
|
||||
*
|
||||
* On a page one label under the Puter origin, the sign-in shows in a frame
|
||||
* over the page instead, and continues in the popup when the user picks a
|
||||
* federated provider or the frame can't be shown.
|
||||
*
|
||||
* Rejects with `{ error: 'popup_blocked' }` if the browser blocked the
|
||||
* popup, `{ error: 'auth_window_closed' }` if the user closed it, `{ error:
|
||||
* 'not_available_in_app' }` when called from an app — an app's token comes
|
||||
@@ -168,12 +176,128 @@ export class AuthModule extends PuterModule {
|
||||
: this.signIn(options));
|
||||
}
|
||||
|
||||
if (this.#canSignInInFrame(options)) {
|
||||
// A second call, such as from a double click or a `puter.*` call
|
||||
// asking for implicit auth, waits on the first rather than
|
||||
// replacing its frame, which would reject the first.
|
||||
if (this.#framedSignIn) return this.#framedSignIn;
|
||||
const promise = this.#signInInFrame(options).then((result) =>
|
||||
result ?? this.#signInWithPopup(options));
|
||||
const done = () => {
|
||||
if (this.#framedSignIn === promise) this.#framedSignIn = null;
|
||||
};
|
||||
this.#framedSignIn = promise;
|
||||
promise.then(done, done);
|
||||
return promise;
|
||||
}
|
||||
return this.#signInWithPopup(options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether this page can show the sign-in framed: a first-party page one
|
||||
* label under the GUI origin, not in a frame of another site. Only the
|
||||
* popup creates a temporary account, so a sign-in that asks for one keeps
|
||||
* it.
|
||||
*/
|
||||
#canSignInInFrame (options) {
|
||||
return !options.attempt_temp_user_creation &&
|
||||
!globalThis.crossOriginIsolated &&
|
||||
!!globalThis.document?.body &&
|
||||
canFrameGuiEmbed(globalThis.location?.href, puter.defaultGUIOrigin) &&
|
||||
ancestorsAllowGuiEmbed(globalThis, puter.defaultGUIOrigin);
|
||||
}
|
||||
|
||||
/** Runs `puter.onAuth`, if set, with the user just signed in. */
|
||||
#notifyAuth () {
|
||||
if (typeof puter.onAuth !== 'function') return;
|
||||
void (async () => {
|
||||
try {
|
||||
const user = await puter.whoamiCache_;
|
||||
puter.onAuth(user ?? (await puter.getUser()));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
* The sign-in in a frame over the page. Settles as the popup would, or
|
||||
* resolves null when the popup has to take over.
|
||||
*
|
||||
* @returns {Promise<SignInResult | null>}
|
||||
*/
|
||||
async #signInInFrame (options) {
|
||||
const msg_id = crypto.randomUUID();
|
||||
this.pendingSignInMessageIds_.add(msg_id);
|
||||
const fragment = { msg_id };
|
||||
if (options.request_auth) fragment.request_auth = 'true';
|
||||
let outcome;
|
||||
try {
|
||||
outcome = await showPopupFrame({
|
||||
guiOrigin: puter.defaultGUIOrigin,
|
||||
action: 'sign-in',
|
||||
fragment,
|
||||
title: 'Sign in to Puter',
|
||||
closeLabel: 'Close',
|
||||
closed: () => ({ closed: true }),
|
||||
onMessage: (data, finish) => {
|
||||
if (data.msg === 'puterPopupFrame' && data.state === 'provider') {
|
||||
if (this.#isProviderStart(data.url, msg_id)) finish({ providerUrl: data.url });
|
||||
return;
|
||||
}
|
||||
if (data.msg !== 'puter.token' || data.msg_id != msg_id) return;
|
||||
finish({ reply: data });
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
this.pendingSignInMessageIds_.delete(msg_id);
|
||||
}
|
||||
if (!outcome) return null;
|
||||
// A provider won't load in a frame, so its sign-in continues in the
|
||||
// popup, which the provider returns as this attempt's sign-in popup.
|
||||
if (outcome.providerUrl) {
|
||||
return this.#signInWithPopup(options, { url: outcome.providerUrl, msgId: msg_id });
|
||||
}
|
||||
if (outcome.closed) {
|
||||
throw {
|
||||
error: 'auth_window_closed',
|
||||
msg: 'Authentication window was closed by the user without completing the process.',
|
||||
};
|
||||
}
|
||||
const { msg: _msg, msg_id: _msgId, ...result } = outcome.reply;
|
||||
if (!result.success) throw result;
|
||||
puter.setAuthToken(result.token);
|
||||
this.#notifyAuth();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `url` is the GUI's start of a provider sign-in that returns as
|
||||
* the popup for sign-in `msgId`.
|
||||
*/
|
||||
#isProviderStart (url, msgId) {
|
||||
try {
|
||||
const start = new URL(url);
|
||||
return start.origin === new URL(puter.defaultGUIOrigin).origin &&
|
||||
/^\/auth\/oidc\/[^/]+\/start$/.test(start.pathname) &&
|
||||
start.searchParams.get('embedded_in_popup') === 'true' &&
|
||||
start.searchParams.get('msg_id') === msgId;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sign-in in a popup window, opened at `start.url` for sign-in
|
||||
* `start.msgId` when a framed sign-in hands one over.
|
||||
*/
|
||||
#signInWithPopup (options, start = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const signinsession = crypto.randomUUID();
|
||||
const msg_id = signinsession;
|
||||
const msg_id = start.msgId ?? signinsession;
|
||||
this.pendingSignInMessageIds_.add(msg_id);
|
||||
const popupName = `Puter-sign-in-${signinsession}`;
|
||||
const url = `${puter.defaultGUIOrigin}/action/sign-in?embedded_in_popup=true&msg_id=${msg_id}${window.crossOriginIsolated ? `&cross_origin_isolated=true&signin_session=${signinsession}` : ''}${options.attempt_temp_user_creation ? '&attempt_temp_user_creation=true' : ''}${options.request_auth ? '&request_auth=true' : ''}`;
|
||||
const url = start.url ?? `${puter.defaultGUIOrigin}/action/sign-in?embedded_in_popup=true&msg_id=${msg_id}${window.crossOriginIsolated ? `&cross_origin_isolated=true&signin_session=${signinsession}` : ''}${options.attempt_temp_user_creation ? '&attempt_temp_user_creation=true' : ''}${options.request_auth ? '&request_auth=true' : ''}`;
|
||||
|
||||
// Guards against settling the promise more than once across the
|
||||
// message, popup-closed, and dialog-cancel code paths.
|
||||
@@ -196,17 +320,7 @@ export class AuthModule extends PuterModule {
|
||||
consentDialog = null;
|
||||
};
|
||||
|
||||
const notifyAuth = () => {
|
||||
if (typeof puter.onAuth !== 'function') return;
|
||||
void (async () => {
|
||||
try {
|
||||
const user = await puter.whoamiCache_;
|
||||
puter.onAuth(user ?? (await puter.getUser()));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
})();
|
||||
};
|
||||
const notifyAuth = () => this.#notifyAuth();
|
||||
|
||||
if (window.crossOriginIsolated) {
|
||||
(async () => {
|
||||
@@ -366,7 +480,7 @@ export class AuthModule extends PuterModule {
|
||||
rejectBlocked();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user is currently signed in.
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment-options {"url": "https://notes.puter.test/doc"}
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { AuthModule } from './Auth.js';
|
||||
|
||||
// An isolated page polls the sign-in relay; nothing here answers it.
|
||||
vi.mock('../lib/networkUtils.js', () => ({ fetchUrl: vi.fn(() => new Promise(() => {})) }));
|
||||
|
||||
const GUI_ORIGIN = 'https://puter.test';
|
||||
|
||||
// jsdom has no top-layer dialogs.
|
||||
HTMLDialogElement.prototype.showModal = function () {
|
||||
this.open = true;
|
||||
};
|
||||
HTMLDialogElement.prototype.close = function () {
|
||||
this.open = false;
|
||||
};
|
||||
|
||||
const signInFrame = () => document.querySelector('dialog.puter-popup-frame iframe');
|
||||
|
||||
/** The framed sign-in's `msg_id`, from its fragment. */
|
||||
const frameMsgId = () => new URLSearchParams(new URL(signInFrame().src).hash.slice(1)).get('msg_id');
|
||||
|
||||
const fromFrame = (data, source = signInFrame().contentWindow) =>
|
||||
window.dispatchEvent(new MessageEvent('message', { data, origin: GUI_ORIGIN, source }));
|
||||
|
||||
let auth;
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
vi.stubGlobal('puter', {
|
||||
env: 'web',
|
||||
defaultGUIOrigin: GUI_ORIGIN,
|
||||
setAuthToken: vi.fn(),
|
||||
trackOpenedWindow_: vi.fn(),
|
||||
});
|
||||
vi.spyOn(window, 'open').mockImplementation((url, name) => ({ name, url, closed: false }));
|
||||
Object.defineProperty(navigator, 'userActivation', {
|
||||
configurable: true,
|
||||
value: { hasBeenActive: true, isActive: true },
|
||||
});
|
||||
auth = new AuthModule(puter);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete navigator.userActivation;
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('auth.signIn on a first-party page', () => {
|
||||
it('signs in through the frame instead of a popup', async () => {
|
||||
const result = auth.signIn();
|
||||
const url = new URL(signInFrame().src);
|
||||
expect(url.origin + url.pathname).toBe(`${GUI_ORIGIN}/embed/sign-in`);
|
||||
expect(url.search).toBe('');
|
||||
expect(auth.pendingSignInMessageIds_.has(frameMsgId())).toBe(true);
|
||||
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({ msg: 'puter.token', msg_id: frameMsgId(), success: true, token: 'tok', app_uid: 'app-1', username: 'alice' });
|
||||
|
||||
await expect(result).resolves.toEqual({ success: true, token: 'tok', app_uid: 'app-1', username: 'alice' });
|
||||
expect(puter.setAuthToken).toHaveBeenCalledWith('tok');
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
expect(signInFrame()).toBeNull();
|
||||
expect(auth.pendingSignInMessageIds_.size).toBe(0);
|
||||
});
|
||||
|
||||
it('passes request_auth on to the frame', () => {
|
||||
auth.signIn({ request_auth: true }).catch(() => {});
|
||||
expect(new URLSearchParams(new URL(signInFrame().src).hash.slice(1)).get('request_auth')).toBe('true');
|
||||
});
|
||||
|
||||
it('ignores a token for another sign-in or from another window', async () => {
|
||||
const result = auth.signIn();
|
||||
let settled = false;
|
||||
result.then(() => {
|
||||
settled = true;
|
||||
}, () => {
|
||||
settled = true;
|
||||
});
|
||||
fromFrame({ msg: 'puter.token', msg_id: 'other', success: true, token: 'x' });
|
||||
fromFrame({ msg: 'puter.token', msg_id: frameMsgId(), success: true, token: 'x' }, window);
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
expect(puter.setAuthToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects as a closed popup when the user closes the frame', async () => {
|
||||
const result = auth.signIn();
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
document.querySelector('.puter-popup-frame-close').click();
|
||||
await expect(result).rejects.toMatchObject({ error: 'auth_window_closed' });
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects as a closed popup when the frame closes without a token', async () => {
|
||||
const result = auth.signIn();
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(result).rejects.toMatchObject({ error: 'auth_window_closed' });
|
||||
});
|
||||
|
||||
it('shares one framed sign-in between calls made while it is open', async () => {
|
||||
const first = auth.signIn();
|
||||
const second = auth.signIn();
|
||||
expect(document.querySelectorAll('dialog.puter-popup-frame')).toHaveLength(1);
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({ msg: 'puter.token', msg_id: frameMsgId(), success: true, token: 'tok' });
|
||||
await expect(first).resolves.toEqual({ success: true, token: 'tok' });
|
||||
await expect(second).resolves.toEqual({ success: true, token: 'tok' });
|
||||
|
||||
// Once it settles, the next call starts a new one.
|
||||
const third = auth.signIn();
|
||||
expect(signInFrame()).not.toBeNull();
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(third).rejects.toMatchObject({ error: 'auth_window_closed' });
|
||||
});
|
||||
|
||||
it('shares the framed sign-in with a call that differs in request_auth', async () => {
|
||||
// Implicit auth (a `puter.*` call without a token) asks with request_auth.
|
||||
const implicit = auth.signIn({ request_auth: true });
|
||||
const explicit = auth.signIn();
|
||||
expect(document.querySelectorAll('dialog.puter-popup-frame')).toHaveLength(1);
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({ msg: 'puter.token', msg_id: frameMsgId(), success: true, token: 'tok' });
|
||||
await expect(implicit).resolves.toEqual({ success: true, token: 'tok' });
|
||||
await expect(explicit).resolves.toEqual({ success: true, token: 'tok' });
|
||||
});
|
||||
|
||||
it('rejects with the reply a failed sign-in sends, as the popup does', async () => {
|
||||
const result = auth.signIn();
|
||||
fromFrame({ msg: 'puter.token', msg_id: frameMsgId(), success: false, token: null });
|
||||
await expect(result).rejects.toEqual({ success: false, token: null });
|
||||
expect(puter.setAuthToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('continues in the popup when the frame hands off, such as for a federated provider', async () => {
|
||||
const result = auth.signIn();
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
await vi.waitFor(() => expect(window.open).toHaveBeenCalledTimes(1));
|
||||
const [url] = window.open.mock.calls[0];
|
||||
expect(url).toContain(`${GUI_ORIGIN}/action/sign-in?embedded_in_popup=true`);
|
||||
expect(signInFrame()).toBeNull();
|
||||
|
||||
const popup = window.open.mock.results[0].value;
|
||||
const msgId = new URL(url).searchParams.get('msg_id');
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'puter.token', msg_id: msgId, success: true, token: 'tok' },
|
||||
origin: GUI_ORIGIN,
|
||||
source: popup,
|
||||
}));
|
||||
await expect(result).resolves.toMatchObject({ success: true, token: 'tok' });
|
||||
});
|
||||
|
||||
it('opens the provider the user picked in the frame straight in the popup', async () => {
|
||||
const result = auth.signIn();
|
||||
const msgId = frameMsgId();
|
||||
const start = `${GUI_ORIGIN}/auth/oidc/google/start?flow=login&referrer=x&embedded_in_popup=true&msg_id=${msgId}&opener_origin=https%3A%2F%2Fnotes.puter.test`;
|
||||
const frameWindow = signInFrame().contentWindow;
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'provider', url: start });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' }, frameWindow);
|
||||
await vi.waitFor(() => expect(window.open).toHaveBeenCalledTimes(1));
|
||||
expect(window.open.mock.calls[0][0]).toBe(start);
|
||||
expect(signInFrame()).toBeNull();
|
||||
expect(auth.pendingSignInMessageIds_.has(msgId)).toBe(true);
|
||||
|
||||
// The provider returns the popup as a sign-in popup for the same attempt.
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'puter.token', msg_id: msgId, success: true, token: 'tok' },
|
||||
origin: GUI_ORIGIN,
|
||||
source: window.open.mock.results[0].value,
|
||||
}));
|
||||
await expect(result).resolves.toMatchObject({ success: true, token: 'tok' });
|
||||
expect(puter.setAuthToken).toHaveBeenCalledWith('tok');
|
||||
expect(auth.pendingSignInMessageIds_.size).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['another origin', (id) => `https://evil.test/auth/oidc/google/start?embedded_in_popup=true&msg_id=${id}`],
|
||||
['another path', (id) => `${GUI_ORIGIN}/action/sign-in?embedded_in_popup=true&msg_id=${id}&auth_token=x`],
|
||||
['another sign-in', () => `${GUI_ORIGIN}/auth/oidc/google/start?embedded_in_popup=true&msg_id=other`],
|
||||
['no popup return', (id) => `${GUI_ORIGIN}/auth/oidc/google/start?msg_id=${id}`],
|
||||
['no URL', () => undefined],
|
||||
])('opens the sign-in popup instead of a provider URL to %s', async (_, url) => {
|
||||
auth.signIn();
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'provider', url: url(frameMsgId()) });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
await vi.waitFor(() => expect(window.open).toHaveBeenCalledTimes(1));
|
||||
expect(window.open.mock.calls[0][0]).toContain(`${GUI_ORIGIN}/action/sign-in?embedded_in_popup=true`);
|
||||
});
|
||||
|
||||
it('continues in the popup when the frame is refused', async () => {
|
||||
vi.useFakeTimers();
|
||||
auth.signIn();
|
||||
signInFrame().dispatchEvent(new Event('load'));
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
expect(signInFrame()).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the popup for a temporary account', () => {
|
||||
auth.signIn({ attempt_temp_user_creation: true });
|
||||
expect(signInFrame()).toBeNull();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
expect(window.open.mock.calls[0][0]).toContain('attempt_temp_user_creation=true');
|
||||
});
|
||||
|
||||
it('keeps the popup for a page outside the Puter origin', () => {
|
||||
puter.defaultGUIOrigin = 'https://puter.com';
|
||||
auth.signIn();
|
||||
expect(signInFrame()).toBeNull();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps the popup for a page in a frame of another site', () => {
|
||||
Object.defineProperty(window.location, 'ancestorOrigins', { configurable: true, value: ['https://other.test'] });
|
||||
try {
|
||||
auth.signIn();
|
||||
expect(signInFrame()).toBeNull();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
delete window.location.ancestorOrigins;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the popup for a cross-origin isolated page', () => {
|
||||
vi.stubGlobal('crossOriginIsolated', true);
|
||||
auth.signIn().catch(() => {});
|
||||
expect(signInFrame()).toBeNull();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+369
-68
@@ -2,6 +2,10 @@ import EventListener from '../lib/EventListener.js';
|
||||
import { PuterJSError } from '../lib/PuterJSError.js';
|
||||
import FSItem from './FSItem.js';
|
||||
import PuterDialog from './PuterDialog.js';
|
||||
import { ancestorsAllowGuiEmbed, canFrameGuiEmbed, showFeedbackEmbed, showPopupFrame } from '../lib/guiEmbed.js';
|
||||
import { hasUserActivation } from '../lib/auth-popup.js';
|
||||
import { appIDOf } from '../lib/upgradePrompt.js';
|
||||
import { upgradeUrl } from './UsageLimitDialog.js';
|
||||
import { checkPermissions } from './perms/lib/holds.js';
|
||||
|
||||
|
||||
@@ -528,6 +532,15 @@ export class UIModule extends EventListener {
|
||||
#guiFeatures = new URLSearchParams(globalThis.location?.search ?? '')
|
||||
.get('puter.gui_features')?.split(',') ?? [];
|
||||
|
||||
// Set while the framed feedback dialog is open on a first-party page.
|
||||
#feedbackEmbedOpen = false;
|
||||
|
||||
// The framed upgrade showing, which a call made while it's open joins.
|
||||
#upgradeFrame = null;
|
||||
|
||||
// The framed email confirmation showing, which a call made while it's open joins.
|
||||
#emailConfirmationFrame = null;
|
||||
|
||||
// Holds the callback functions for the various events
|
||||
// that are triggered when a watched item has changed.
|
||||
itemWatchCallbackFunctions = [];
|
||||
@@ -578,6 +591,142 @@ export class UIModule extends EventListener {
|
||||
if ( popup ) this.#pickerPopups.add(popup);
|
||||
}
|
||||
|
||||
/** What a picker's consent dialog says, when the popup needs a click to open. */
|
||||
static #PICKER_CONSENT = {
|
||||
'show-open-file-picker': 'This website wants you to choose a file from your Puter account.',
|
||||
'show-save-file-picker': 'This website wants to save a file to your Puter account.',
|
||||
'show-directory-picker': 'This website wants you to choose a folder from your Puter account.',
|
||||
};
|
||||
|
||||
/** Opens a picker's popup window, centered, at the pickers' size. */
|
||||
#openPickerPopup (url, title) {
|
||||
const w = 700;
|
||||
const h = 400;
|
||||
const left = (screen.width / 2) - (w / 2);
|
||||
const top = (screen.height / 2) - (h / 2);
|
||||
return window.open(
|
||||
url,
|
||||
title,
|
||||
`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${top}, left=${left}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a picker on a `web` page. A first-party page one label under the
|
||||
* Puter origin that is signed in gets it in a frame over the page; every
|
||||
* other page, or a frame that can't serve this user, gets the popup.
|
||||
* `onWindow` sees the window that will ask for and answer the picker, with
|
||||
* `framed` set for a frame, and may return a function that stops listening
|
||||
* to it.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {'show-open-file-picker' | 'show-save-file-picker' | 'show-directory-picker'} opts.action
|
||||
* @param {number} opts.msgId
|
||||
* @param {string} opts.url - the popup's URL
|
||||
* @param {string} opts.title - the popup's window name, and the frame's accessible name
|
||||
* @param {Record<string, string>} [opts.fragment] - the popup parameters the frame needs besides `msg_id`
|
||||
* @param {(win: Window | null, how?: { framed: boolean }) => (() => void) | void} [opts.onWindow]
|
||||
*/
|
||||
#showWebPicker ({ action, msgId, url, title, fragment = {}, onWindow }) {
|
||||
if ( ! this.#canFrameForUser() ) {
|
||||
// window.open() returns synchronously and the popup cannot post
|
||||
// back until this function yields, so there is no race.
|
||||
const popup = this.#openPickerPopup(url, title);
|
||||
onWindow?.(popup);
|
||||
this.#trackPickerPopup(popup);
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
if ( await this.#showPickerFrame({ action, msgId, title, fragment, onWindow }) ) return;
|
||||
// The click that asked for the picker may have expired by now, so
|
||||
// without it the user opens the popup from a consent dialog.
|
||||
const launched = (popup) => {
|
||||
onWindow?.(popup);
|
||||
this.#trackPickerPopup(popup);
|
||||
};
|
||||
if ( hasUserActivation() ) {
|
||||
const popup = this.#openPickerPopup(url, title);
|
||||
if ( popup ) {
|
||||
launched(popup);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let consent = null;
|
||||
try {
|
||||
consent = PuterDialog.show({
|
||||
message: UIModule.#PICKER_CONSENT[action],
|
||||
onContinue: () => {
|
||||
launched(this.#openPickerPopup(url, title));
|
||||
consent?.remove();
|
||||
},
|
||||
onCancel: () => {
|
||||
consent?.remove();
|
||||
this.#settleCallback(msgId, PICKER_CANCELLED);
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// No dialog either; as with a blocked popup, the picker never opens.
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/** Whether a picker or upgrade can show framed: a signed-in first-party page, not in a frame of another site. */
|
||||
#canFrameForUser () {
|
||||
return this.env === 'web' &&
|
||||
!globalThis.crossOriginIsolated &&
|
||||
!!globalThis.document?.body &&
|
||||
canFrameGuiEmbed(globalThis.location?.href, puter.defaultGUIOrigin) &&
|
||||
ancestorsAllowGuiEmbed(globalThis, puter.defaultGUIOrigin) &&
|
||||
!!puter.auth?.isSignedIn?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker in a frame over the page, for the page's signed-in user. The
|
||||
* GUI answers it as it would the popup, through the module's message
|
||||
* handler. Resolves false when the popup has to take over.
|
||||
*
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async #showPickerFrame ({ action, msgId, title, fragment, onWindow }) {
|
||||
const user = await this.#frameUser();
|
||||
if ( ! user ) return false;
|
||||
let frame = null;
|
||||
let stopListening;
|
||||
// The frame only serves this page's own user, so the token it sends
|
||||
// with the answer isn't adopted; the page keeps the one it has.
|
||||
const closed = await showPopupFrame({
|
||||
guiOrigin: puter.defaultGUIOrigin,
|
||||
action,
|
||||
fragment: { ...fragment, msg_id: String(msgId), user: user.uuid },
|
||||
title,
|
||||
closed: () => true,
|
||||
onMessage: () => {},
|
||||
onFrame: (win) => {
|
||||
frame = win;
|
||||
this.#pickerPopups.add(win);
|
||||
stopListening = onWindow?.(win, { framed: true });
|
||||
},
|
||||
});
|
||||
this.#pickerPopups.delete(frame);
|
||||
stopListening?.();
|
||||
if ( ! closed ) return false;
|
||||
// Gone without an answer: dismissed, so it settles as a cancel.
|
||||
this.#settleCallback(msgId, PICKER_CANCELLED);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's signed-in user that a frame is shown for, from the cached
|
||||
* whoami when there is one, or null without a uuid.
|
||||
*
|
||||
* @returns {Promise<{ uuid: string, email_confirmed?: boolean } | null>}
|
||||
*/
|
||||
async #frameUser () {
|
||||
const known = await Promise.resolve(puter.whoami ?? puter.whoamiCache_).catch(() => null);
|
||||
const user = known?.uuid ? known : await puter.auth.getUser().catch(() => null);
|
||||
return typeof user?.uuid === 'string' && user.uuid ? user : null;
|
||||
}
|
||||
|
||||
// Whether a message on the window may drive this module.
|
||||
#isTrustedMessageSource (e) {
|
||||
if ( this.messageTarget ) {
|
||||
@@ -1188,17 +1337,59 @@ export class UIModule extends EventListener {
|
||||
};
|
||||
|
||||
/**
|
||||
* Asks the desktop to walk the user through confirming their email.
|
||||
* Resolves once the dialog closes.
|
||||
* Walks the user through confirming their email: a temporary account is
|
||||
* saved first, then the user enters the code sent to their address.
|
||||
* Resolves once they're done, or right away when the email is already
|
||||
* confirmed.
|
||||
*
|
||||
* @returns {Promise<unknown>}
|
||||
* Inside an app the desktop shows it. On a signed-in first-party page one
|
||||
* label under the Puter origin, it shows in a frame over the page, and
|
||||
* `response` is false when the frame can't show it. Anywhere else the
|
||||
* promise never settles, since a website has no desktop to ask.
|
||||
*
|
||||
* @returns {Promise<import('../lib/types.js').EmailConfirmationResult>}
|
||||
*/
|
||||
requestEmailConfirmation () {
|
||||
return new Promise((resolve, reject) => {
|
||||
if ( this.#canFrameForUser() ) return this.#showEmailConfirmationFrame();
|
||||
return new Promise((resolve) => {
|
||||
this.#postMessageWithCallback('requestEmailConfirmation', resolve, { });
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* The email confirmation in a frame over the page, for the page's
|
||||
* signed-in user. A call made while one is showing settles with it, and
|
||||
* an email the page already knows is confirmed resolves without one.
|
||||
*
|
||||
* @returns {Promise<import('../lib/types.js').EmailConfirmationResult>}
|
||||
*/
|
||||
#showEmailConfirmationFrame () {
|
||||
if ( this.#emailConfirmationFrame ) return this.#emailConfirmationFrame;
|
||||
this.#emailConfirmationFrame = (async () => {
|
||||
try {
|
||||
const user = await this.#frameUser();
|
||||
// A confirmed email never goes back to unconfirmed, so this
|
||||
// skips the loading scrim the frame would show while it boots.
|
||||
if ( user?.email_confirmed === true ) return { response: true };
|
||||
const framed = user && await showPopupFrame({
|
||||
guiOrigin: puter.defaultGUIOrigin,
|
||||
action: 'request-email-confirmation',
|
||||
fragment: { user: user.uuid },
|
||||
title: 'Confirm your email',
|
||||
closed: (data) => ({ response: data?.confirmed === true }),
|
||||
onMessage: () => {},
|
||||
});
|
||||
// The page's cached whoami still reads it as unconfirmed,
|
||||
// and would frame the next call too.
|
||||
if ( framed?.response ) user.email_confirmed = true;
|
||||
return framed || { response: false };
|
||||
} finally {
|
||||
this.#emailConfirmationFrame = null;
|
||||
}
|
||||
})();
|
||||
return this.#emailConfirmationFrame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the desktop to walk the user through clearing an account
|
||||
* verification gate (a 403 `*_required` code — email confirmation, phone
|
||||
@@ -1378,20 +1569,12 @@ export class UIModule extends EventListener {
|
||||
env: this.env,
|
||||
}, '*');
|
||||
} else {
|
||||
let w = 700;
|
||||
let h = 400;
|
||||
let title = 'Puter: Open Directory';
|
||||
var left = (screen.width / 2) - (w / 2);
|
||||
var top = (screen.height / 2) - (h / 2);
|
||||
// Track the window we opened so the message listener accepts
|
||||
// its reply. window.open() returns synchronously and the popup
|
||||
// cannot post back until this function yields, so there is no
|
||||
// race.
|
||||
this.#trackPickerPopup(window.open(
|
||||
`${puter.defaultGUIOrigin}/action/show-directory-picker?embedded_in_popup=true&msg_id=${msg_id}&appInstanceID=${this.appInstanceID}&env=${this.env}&options=${JSON.stringify(options)}`,
|
||||
title,
|
||||
`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${top}, left=${left}`,
|
||||
));
|
||||
this.#showWebPicker({
|
||||
action: 'show-directory-picker',
|
||||
msgId: msg_id,
|
||||
url: `${puter.defaultGUIOrigin}/action/show-directory-picker?embedded_in_popup=true&msg_id=${msg_id}&appInstanceID=${this.appInstanceID}&env=${this.env}&options=${JSON.stringify(options)}`,
|
||||
title: 'Puter: Open Directory',
|
||||
});
|
||||
}
|
||||
|
||||
this.#registerPickerCallback(msg_id, resolve, undefinedOnCancel);
|
||||
@@ -1428,16 +1611,13 @@ export class UIModule extends EventListener {
|
||||
env: this.env,
|
||||
}, '*');
|
||||
} else {
|
||||
let w = 700;
|
||||
let h = 400;
|
||||
let title = 'Puter: Open File';
|
||||
var left = (screen.width / 2) - (w / 2);
|
||||
var top = (screen.height / 2) - (h / 2);
|
||||
this.#trackPickerPopup(window.open(
|
||||
`${puter.defaultGUIOrigin}/action/show-open-file-picker?embedded_in_popup=true&msg_id=${msg_id}&appInstanceID=${this.appInstanceID}&env=${this.env}&options=${JSON.stringify(options ?? {})}`,
|
||||
title,
|
||||
`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${top}, left=${left}`,
|
||||
));
|
||||
this.#showWebPicker({
|
||||
action: 'show-open-file-picker',
|
||||
msgId: msg_id,
|
||||
url: `${puter.defaultGUIOrigin}/action/show-open-file-picker?embedded_in_popup=true&msg_id=${msg_id}&appInstanceID=${this.appInstanceID}&env=${this.env}&options=${JSON.stringify(options ?? {})}`,
|
||||
title: 'Puter: Open File',
|
||||
fragment: { options: JSON.stringify(options ?? {}) },
|
||||
});
|
||||
}
|
||||
this.#registerPickerCallback(msg_id, resolve, undefinedOnCancel);
|
||||
});
|
||||
@@ -1581,16 +1761,112 @@ export class UIModule extends EventListener {
|
||||
* fills them in when a call is refused for want of credit, a plan, or
|
||||
* storage.
|
||||
*
|
||||
* On a signed-in first-party page one label under the Puter origin, the
|
||||
* upgrade shows in a frame over the page instead, and the promise
|
||||
* resolves once it closes. When the frame can't show it, the upgrade
|
||||
* opens in a new tab and the promise resolves `{ upgraded: false }`.
|
||||
* Anywhere else the promise never settles: the desktop doesn't answer an
|
||||
* app, and a website has no desktop to ask.
|
||||
*
|
||||
* @param {import('../lib/types.js').UpgradeRequestDetails} [details]
|
||||
* @returns {Promise<unknown>}
|
||||
* @returns {Promise<import('../lib/types.js').UpgradeResult>}
|
||||
*/
|
||||
requestUpgrade (details) {
|
||||
const { reason, method, message } = details ?? {};
|
||||
if ( this.canShowUpgradeFrame_() ) return this.#showUpgradeFrame({ reason, method });
|
||||
return new Promise((resolve) => {
|
||||
this.#postMessageWithCallback('requestUpgrade', resolve, { reason, method, message });
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether {@link requestUpgrade} shows the upgrade in a frame over this page.
|
||||
*
|
||||
* @internal
|
||||
* @returns {boolean}
|
||||
*/
|
||||
canShowUpgradeFrame_ () {
|
||||
return this.#canFrameForUser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@link requestUpgrade} is showing the upgrade in a frame, about
|
||||
* to, or asking to open it in a tab instead.
|
||||
*
|
||||
* @internal
|
||||
* @returns {boolean}
|
||||
*/
|
||||
upgradeFrameShowing_ () {
|
||||
return this.#upgradeFrame !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The upgrade in a frame over the page, for the page's signed-in user, or
|
||||
* in a new tab when the frame can't show it. A call made while one is
|
||||
* showing settles with it, so a payment in progress isn't replaced.
|
||||
*
|
||||
* @param {{ reason?: string, method?: string }} details
|
||||
* @returns {Promise<import('../lib/types.js').UpgradeResult>}
|
||||
*/
|
||||
#showUpgradeFrame ({ reason, method }) {
|
||||
if ( this.#upgradeFrame ) return this.#upgradeFrame;
|
||||
this.#upgradeFrame = (async () => {
|
||||
try {
|
||||
const user = await this.#frameUser();
|
||||
const framed = user && await showPopupFrame({
|
||||
guiOrigin: puter.defaultGUIOrigin,
|
||||
action: 'upgrade',
|
||||
fragment: {
|
||||
user: user.uuid,
|
||||
...(reason ? { reason } : {}),
|
||||
...(method ? { method } : {}),
|
||||
},
|
||||
title: 'Upgrade',
|
||||
closed: (data) => ({ upgraded: data?.upgraded === true }),
|
||||
onMessage: () => {},
|
||||
});
|
||||
if ( framed ) return framed;
|
||||
await this.#openUpgradeTab(upgradeUrl({ reason, method, appID: appIDOf(puter) }));
|
||||
return { upgraded: false };
|
||||
} finally {
|
||||
this.#upgradeFrame = null;
|
||||
}
|
||||
})();
|
||||
return this.#upgradeFrame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the upgrade page in a new tab. The click that asked for it may
|
||||
* have expired by now, so without it the user opens it from a consent
|
||||
* dialog. Resolves once the tab opens or the user answers the dialog.
|
||||
*
|
||||
* @param {string} url
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
#openUpgradeTab (url) {
|
||||
if ( hasUserActivation() && window.open(url, '_blank') ) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
let consent = null;
|
||||
const answered = () => {
|
||||
consent?.remove();
|
||||
resolve();
|
||||
};
|
||||
try {
|
||||
consent = PuterDialog.show({
|
||||
message: 'This website wants to open the Puter upgrade page.',
|
||||
onContinue: () => {
|
||||
window.open(url, '_blank');
|
||||
answered();
|
||||
},
|
||||
onCancel: answered,
|
||||
});
|
||||
} catch {
|
||||
// No dialog either; as with a blocked tab, the page never opens.
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a picker for choosing where to save a file, and saves `content`
|
||||
* there. Resolves to the saved `FSItem`; if the user cancels, the promise
|
||||
@@ -1635,47 +1911,43 @@ export class UIModule extends EventListener {
|
||||
// Create an object URL for the Blob
|
||||
let objectUrl = URL.createObjectURL(blob);
|
||||
|
||||
let w = 700;
|
||||
let h = 400;
|
||||
let title = 'Puter: Save File';
|
||||
var left = (screen.width / 2) - (w / 2);
|
||||
var top = (screen.height / 2) - (h / 2);
|
||||
|
||||
// Open the picker popup first so we can bind the data handler to the
|
||||
// exact window we opened. window.open() returns synchronously and the
|
||||
// popup cannot post back until this function yields, so there is no race.
|
||||
const popup = window.open(
|
||||
`${puter.defaultGUIOrigin}/action/show-save-file-picker?embedded_in_popup=true&msg_id=${msg_id}&appInstanceID=${this.appInstanceID}&env=${this.env}&blobUrl=${encodeURIComponent(objectUrl)}`,
|
||||
title,
|
||||
`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${top}, left=${left}`,
|
||||
);
|
||||
|
||||
// Only hand the file content to the trusted Puter GUI popup we just
|
||||
// opened. Without this, any framing parent or sibling iframe could post
|
||||
// Only hand the file content to the Puter GUI window that shows
|
||||
// the picker (its popup, or its frame on a first-party page).
|
||||
// Without this, any framing parent or sibling iframe could post
|
||||
// { msg: 'sendMeFileData' } and receive the content the page meant to save.
|
||||
const onSendMeFileData = (e) => {
|
||||
if ( e.data?.msg !== 'sendMeFileData' ) return;
|
||||
// Reject anything that isn't our popup on the trusted GUI origin.
|
||||
if ( e.origin !== puter.defaultGUIOrigin ) return;
|
||||
if ( ! popup || e.source !== popup ) return;
|
||||
// A frame that reloads asks again, so it's answered until it
|
||||
// closes; a popup is answered once.
|
||||
const sendFileDataTo = (picker, { framed = false } = {}) => {
|
||||
const onSendMeFileData = (e) => {
|
||||
if ( e.data?.msg !== 'sendMeFileData' ) return;
|
||||
// Reject anything that isn't our picker on the trusted GUI origin.
|
||||
if ( e.origin !== puter.defaultGUIOrigin ) return;
|
||||
if ( ! picker || e.source !== picker ) return;
|
||||
|
||||
// Send the file data to the popup, targeting the trusted origin only.
|
||||
e.source.postMessage({
|
||||
msg: 'showSaveFilePickerPopup',
|
||||
content: url ? undefined : content,
|
||||
url: url ? url.toString() : undefined,
|
||||
suggestedName: suggestedName ?? '',
|
||||
env: this.env,
|
||||
uuid: msg_id,
|
||||
}, puter.defaultGUIOrigin);
|
||||
// Send the file data to the picker, targeting the trusted origin only.
|
||||
e.source.postMessage({
|
||||
msg: 'showSaveFilePickerPopup',
|
||||
content: url ? undefined : content,
|
||||
url: url ? url.toString() : undefined,
|
||||
suggestedName: suggestedName ?? '',
|
||||
env: this.env,
|
||||
uuid: msg_id,
|
||||
}, puter.defaultGUIOrigin);
|
||||
|
||||
// The trusted popup has the data; remove this exact listener.
|
||||
window.removeEventListener('message', onSendMeFileData);
|
||||
// A popup has the data now; remove this exact listener.
|
||||
if ( ! framed ) window.removeEventListener('message', onSendMeFileData);
|
||||
};
|
||||
window.addEventListener('message', onSendMeFileData);
|
||||
return () => window.removeEventListener('message', onSendMeFileData);
|
||||
};
|
||||
window.addEventListener('message', onSendMeFileData);
|
||||
|
||||
// Same window, for the picker's own reply on the main listener.
|
||||
this.#trackPickerPopup(popup);
|
||||
this.#showWebPicker({
|
||||
action: 'show-save-file-picker',
|
||||
msgId: msg_id,
|
||||
url: `${puter.defaultGUIOrigin}/action/show-save-file-picker?embedded_in_popup=true&msg_id=${msg_id}&appInstanceID=${this.appInstanceID}&env=${this.env}&blobUrl=${encodeURIComponent(objectUrl)}`,
|
||||
title: 'Puter: Save File',
|
||||
onWindow: sendFileDataTo,
|
||||
});
|
||||
}
|
||||
this.#registerPickerCallback(msg_id, resolve, undefinedOnCancel);
|
||||
});
|
||||
@@ -2249,9 +2521,12 @@ export class UIModule extends EventListener {
|
||||
* have opted in by setting `feedbackEnabled` on the app — otherwise the
|
||||
* dialog tells the user feedback is unavailable.
|
||||
*
|
||||
* In the `app` environment the Puter desktop renders the dialog; in the
|
||||
* `web` environment a puter.com popup hosts it (signing the user in first
|
||||
* if needed). Every other environment resolves `false`.
|
||||
* In the `app` environment the Puter desktop renders the dialog. In the
|
||||
* `web` environment a first-party page one label under the Puter origin
|
||||
* shows it in a frame over the page when the user's Puter session is the
|
||||
* one the page is signed in as; otherwise a puter.com popup hosts it
|
||||
* (signing the user in first if needed). Every other environment
|
||||
* resolves `false`.
|
||||
*
|
||||
* @returns {Promise<boolean>} `true` when the user submitted feedback,
|
||||
* `false` when the dialog was dismissed or feedback is unavailable.
|
||||
@@ -2276,6 +2551,10 @@ export class UIModule extends EventListener {
|
||||
if ( this.env !== 'web' ) {
|
||||
return false;
|
||||
}
|
||||
const embedded = await this.#showFeedbackEmbed();
|
||||
if ( embedded ) {
|
||||
return embedded.sent;
|
||||
}
|
||||
// The app's identity is deliberately NOT in the popup URL: the GUI
|
||||
// derives it from the browser-attested opener origin, so a link
|
||||
// can't open a feedback dialog in another app's name.
|
||||
@@ -2287,6 +2566,28 @@ export class UIModule extends EventListener {
|
||||
return result?.sent === true;
|
||||
};
|
||||
|
||||
/**
|
||||
* The framed feedback dialog for a first-party page that is signed in, or
|
||||
* null when the popup has to host it. One at a time: a call while one is
|
||||
* open resolves `{ sent: false }`, as the desktop does.
|
||||
*
|
||||
* @returns {Promise<{ sent: boolean } | null>}
|
||||
*/
|
||||
async #showFeedbackEmbed () {
|
||||
if ( ! globalThis.document?.body ) return null;
|
||||
if ( ! canFrameGuiEmbed(globalThis.location?.href, puter.defaultGUIOrigin) ) return null;
|
||||
if ( ! puter.auth?.isSignedIn?.() ) return null;
|
||||
if ( this.#feedbackEmbedOpen ) return { sent: false };
|
||||
this.#feedbackEmbedOpen = true;
|
||||
try {
|
||||
const user = await this.#frameUser();
|
||||
if ( ! user ) return null;
|
||||
return await showFeedbackEmbed({ guiOrigin: puter.defaultGUIOrigin, userUuid: user.uuid });
|
||||
} finally {
|
||||
this.#feedbackEmbedOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `/action/<action>` on the GUI origin in a popup and waits for
|
||||
* its single result message. Resolves the message's data, or `null` when
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment-options {"url": "https://notes.puter.test/doc"}
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { UIModule } = await import('./UI.js');
|
||||
|
||||
// jsdom has no top-layer dialogs.
|
||||
HTMLDialogElement.prototype.showModal = function () {
|
||||
this.open = true;
|
||||
};
|
||||
HTMLDialogElement.prototype.close = function () {
|
||||
this.open = false;
|
||||
};
|
||||
|
||||
const GUI_ORIGIN = 'https://puter.test';
|
||||
const USER = '0b1c9a52-3f0e-4c7a-9a65-2f6d1e8b7c40';
|
||||
|
||||
const pickerFrame = () => document.querySelector('dialog.puter-popup-frame iframe');
|
||||
const fragment = () => Object.fromEntries(new URLSearchParams(new URL(pickerFrame().src).hash.slice(1)));
|
||||
|
||||
const fromFrame = (data, source = pickerFrame().contentWindow) =>
|
||||
window.dispatchEvent(new MessageEvent('message', { data, origin: GUI_ORIGIN, source }));
|
||||
|
||||
const makeUI = () => new UIModule(
|
||||
{ env: 'web', authToken: 'token-1', APIOrigin: 'https://api.puter.test', appID: 'app-1', util: {} },
|
||||
{ appInstanceID: 'instance-1' },
|
||||
);
|
||||
|
||||
const fakePuter = ({ signedIn = true } = {}) => {
|
||||
globalThis.puter = {
|
||||
defaultGUIOrigin: GUI_ORIGIN,
|
||||
whoamiCache_: Promise.resolve({ uuid: USER }),
|
||||
trackOpenedWindow_: vi.fn(),
|
||||
auth: {
|
||||
isSignedIn: () => signedIn,
|
||||
getUser: vi.fn(async () => ({ uuid: USER })),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const PENDING = Symbol('pending');
|
||||
const settled = (promise) => Promise.race([promise, new Promise((r) => setTimeout(() => r(PENDING), 0))]);
|
||||
|
||||
let popup;
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
popup = { closed: false, postMessage: vi.fn() };
|
||||
window.open = vi.fn(() => popup);
|
||||
Object.defineProperty(navigator, 'userActivation', {
|
||||
configurable: true,
|
||||
value: { hasBeenActive: true, isActive: true },
|
||||
});
|
||||
fakePuter();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete navigator.userActivation;
|
||||
delete globalThis.puter;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('pickers on a signed-in first-party page', () => {
|
||||
it('shows the open file picker in a frame and resolves what it picks', async () => {
|
||||
const ui = makeUI();
|
||||
const result = ui.showOpenFilePicker({ multiple: false, accept: '.txt' });
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
const url = new URL(pickerFrame().src);
|
||||
expect(url.pathname).toBe('/embed/show-open-file-picker');
|
||||
expect(fragment()).toEqual({ options: '{"multiple":false,"accept":".txt"}', msg_id: '1', user: USER });
|
||||
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({
|
||||
msg: 'fileOpenPicked',
|
||||
original_msg_id: '1',
|
||||
items: [{ uid: 'uid-1', name: 'a.txt', path: '~/Desktop/a.txt' }],
|
||||
});
|
||||
await expect(result).resolves.toMatchObject({ uid: 'uid-1', name: 'a.txt' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
expect(pickerFrame()).toBeNull();
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the page token instead of adopting the one the frame sends', async () => {
|
||||
makeUI().showDirectoryPicker();
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
expect(puter.trackOpenedWindow_).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('settles a picker the GUI reports cancelled', async () => {
|
||||
const result = makeUI().showDirectoryPicker();
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
expect(new URL(pickerFrame().src).pathname).toBe('/embed/show-directory-picker');
|
||||
fromFrame({ msg: 'directoryOpenCancelled', original_msg_id: '1' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(result.undefinedOnCancel).resolves.toBeUndefined();
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
});
|
||||
|
||||
it('settles as cancelled when the frame is dismissed without an answer', async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = makeUI().showOpenFilePicker();
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
document.querySelector('.puter-popup-frame-loading').click();
|
||||
await expect(result.undefinedOnCancel).resolves.toBeUndefined();
|
||||
expect(pickerFrame()).toBeNull();
|
||||
});
|
||||
|
||||
it('hands the file content to the save picker frame, and only to it', async () => {
|
||||
const result = makeUI().showSaveFilePicker('hello', 'a.txt');
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
expect(new URL(pickerFrame().src).pathname).toBe('/embed/show-save-file-picker');
|
||||
const frameWindow = pickerFrame().contentWindow;
|
||||
const post = vi.spyOn(frameWindow, 'postMessage').mockImplementation(() => {});
|
||||
|
||||
window.dispatchEvent(new MessageEvent('message', { data: { msg: 'sendMeFileData' }, origin: GUI_ORIGIN, source: window }));
|
||||
window.dispatchEvent(new MessageEvent('message', { data: { msg: 'sendMeFileData' }, origin: 'https://other.test', source: frameWindow }));
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
|
||||
fromFrame({ msg: 'sendMeFileData' });
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ msg: 'showSaveFilePickerPopup', content: 'hello', suggestedName: 'a.txt' }),
|
||||
GUI_ORIGIN,
|
||||
);
|
||||
fromFrame({ msg: 'fileSaved', original_msg_id: '1', saved_file: { name: 'a.txt', uid: 'uid-2' } });
|
||||
await expect(result).resolves.toMatchObject({ name: 'a.txt' });
|
||||
});
|
||||
|
||||
it('hands the file content again to a save picker frame that reloads, until it closes', async () => {
|
||||
const result = makeUI().showSaveFilePicker('hello', 'a.txt');
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
const frameWindow = pickerFrame().contentWindow;
|
||||
const post = vi.spyOn(frameWindow, 'postMessage').mockImplementation(() => {});
|
||||
|
||||
fromFrame({ msg: 'sendMeFileData' });
|
||||
// The reloaded document asks again.
|
||||
fromFrame({ msg: 'sendMeFileData' });
|
||||
expect(post).toHaveBeenCalledTimes(2);
|
||||
expect(post.mock.calls[1][0]).toMatchObject({ msg: 'showSaveFilePickerPopup', content: 'hello' });
|
||||
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(result.undefinedOnCancel).resolves.toBeUndefined();
|
||||
fromFrame({ msg: 'sendMeFileData' }, frameWindow);
|
||||
expect(post).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('opens the popup instead when the frame cannot serve the user', async () => {
|
||||
const ui = makeUI();
|
||||
const result = ui.showOpenFilePicker();
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
await vi.waitFor(() => expect(window.open).toHaveBeenCalledTimes(1));
|
||||
expect(pickerFrame()).toBeNull();
|
||||
expect(window.open.mock.calls[0][0]).toContain(`${GUI_ORIGIN}/action/show-open-file-picker?embedded_in_popup=true&msg_id=1`);
|
||||
expect(puter.trackOpenedWindow_).toHaveBeenCalledWith(popup);
|
||||
|
||||
// The popup's answer reaches the picker as before.
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'fileOpenPicked', original_msg_id: 1, items: [{ uid: 'uid-1', name: 'a.txt' }] },
|
||||
origin: GUI_ORIGIN,
|
||||
source: popup,
|
||||
}));
|
||||
await expect(result).resolves.toMatchObject({ uid: 'uid-1' });
|
||||
});
|
||||
|
||||
it('asks for a click before opening the popup once the original click has expired', async () => {
|
||||
const result = makeUI().showOpenFilePicker();
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
Object.defineProperty(navigator, 'userActivation', {
|
||||
configurable: true,
|
||||
value: { hasBeenActive: true, isActive: false },
|
||||
});
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
await vi.waitFor(() => expect(document.querySelector('puter-dialog')).not.toBeNull());
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
expect(document.querySelector('puter-dialog').shadowRoot.querySelector('.about').textContent)
|
||||
.toBe('This website wants you to choose a file from your Puter account.');
|
||||
|
||||
document.querySelector('puter-dialog').shadowRoot.querySelector('#launch-auth-popup').click();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
expect(window.open.mock.calls[0][2]).toContain('width=700, height=400');
|
||||
expect(document.querySelector('puter-dialog')).toBeNull();
|
||||
|
||||
const cancelled = makeUI().showDirectoryPicker();
|
||||
await vi.waitFor(() => expect(pickerFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
await vi.waitFor(() => expect(document.querySelector('puter-dialog')).not.toBeNull());
|
||||
expect(document.querySelector('puter-dialog').shadowRoot.querySelector('.about').textContent)
|
||||
.toBe('This website wants you to choose a folder from your Puter account.');
|
||||
document.querySelector('puter-dialog').shadowRoot.querySelector('#launch-auth-popup-cancel').click();
|
||||
await expect(cancelled.undefinedOnCancel).resolves.toBeUndefined();
|
||||
expect(document.querySelector('puter-dialog')).toBeNull();
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
expect(await settled(result.undefinedOnCancel)).toBe(PENDING);
|
||||
});
|
||||
|
||||
it('opens the popup when the page has no user to name', async () => {
|
||||
puter.whoamiCache_ = Promise.resolve(null);
|
||||
puter.auth.getUser = vi.fn(async () => {
|
||||
throw new Error('nope');
|
||||
});
|
||||
makeUI().showDirectoryPicker();
|
||||
await vi.waitFor(() => expect(window.open).toHaveBeenCalledTimes(1));
|
||||
expect(pickerFrame()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('pickers that keep the popup', () => {
|
||||
it('opens it synchronously for a signed-out first-party page', () => {
|
||||
fakePuter({ signedIn: false });
|
||||
makeUI().showOpenFilePicker();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
expect(pickerFrame()).toBeNull();
|
||||
});
|
||||
|
||||
it('opens it synchronously for a page in a frame of another site', () => {
|
||||
Object.defineProperty(window.location, 'ancestorOrigins', { configurable: true, value: ['https://other.test'] });
|
||||
try {
|
||||
makeUI().showOpenFilePicker();
|
||||
expect(window.open).toHaveBeenCalledTimes(1);
|
||||
expect(pickerFrame()).toBeNull();
|
||||
} finally {
|
||||
delete window.location.ancestorOrigins;
|
||||
}
|
||||
});
|
||||
|
||||
it('opens it synchronously for a page outside the Puter origin', () => {
|
||||
globalThis.puter.defaultGUIOrigin = 'https://puter.com';
|
||||
makeUI().showSaveFilePicker('x', 'a.txt');
|
||||
makeUI().showDirectoryPicker();
|
||||
expect(window.open).toHaveBeenCalledTimes(2);
|
||||
expect(pickerFrame()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment-options {"url": "https://notes.puter.test/doc"}
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { UIModule } = await import('./UI.js');
|
||||
|
||||
// jsdom has no top-layer dialogs.
|
||||
HTMLDialogElement.prototype.showModal = function () {
|
||||
this.open = true;
|
||||
};
|
||||
HTMLDialogElement.prototype.close = function () {
|
||||
this.open = false;
|
||||
};
|
||||
|
||||
const GUI_ORIGIN = 'https://puter.test';
|
||||
const USER = '0b1c9a52-3f0e-4c7a-9a65-2f6d1e8b7c40';
|
||||
|
||||
const frameDialog = () => document.querySelector('dialog.puter-popup-frame');
|
||||
const confirmFrame = () => frameDialog()?.querySelector('iframe') ?? null;
|
||||
const fragment = () => Object.fromEntries(new URLSearchParams(new URL(confirmFrame().src).hash.slice(1)));
|
||||
|
||||
const fromFrame = (data) => window.dispatchEvent(new MessageEvent('message', {
|
||||
data, origin: GUI_ORIGIN, source: confirmFrame().contentWindow,
|
||||
}));
|
||||
|
||||
const makeUI = (env = 'web') => new UIModule(
|
||||
{ env, authToken: 'token-1', APIOrigin: 'https://api.puter.test', appID: 'app-1', util: {} },
|
||||
{ appInstanceID: 'instance-1' },
|
||||
);
|
||||
|
||||
const fakePuter = ({ signedIn = true, guiOrigin = GUI_ORIGIN } = {}) => {
|
||||
globalThis.puter = {
|
||||
defaultGUIOrigin: guiOrigin,
|
||||
whoamiCache_: Promise.resolve({ uuid: USER }),
|
||||
auth: {
|
||||
isSignedIn: () => signedIn,
|
||||
getUser: vi.fn(async () => ({ uuid: USER })),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const PENDING = Symbol('pending');
|
||||
const settled = (promise) => Promise.race([promise, new Promise((r) => setTimeout(() => r(PENDING), 0))]);
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
window.open = vi.fn(() => ({ closed: false }));
|
||||
fakePuter();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete globalThis.puter;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('ui.requestEmailConfirmation on a signed-in first-party page', () => {
|
||||
it('shows the confirmation in a frame over the page and resolves whether the email is confirmed', async () => {
|
||||
const result = makeUI().requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
|
||||
expect(new URL(confirmFrame().src).pathname).toBe('/embed/request-email-confirmation');
|
||||
expect(fragment()).toEqual({ user: USER });
|
||||
// It covers the page, and the window inside draws the scrim.
|
||||
expect(frameDialog().querySelector('.puter-popup-frame-box')).toBeNull();
|
||||
expect(frameDialog().querySelector('.puter-popup-frame-close')).toBeNull();
|
||||
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
expect(frameDialog().open).toBe(true);
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed', confirmed: true });
|
||||
|
||||
await expect(result).resolves.toEqual({ response: true });
|
||||
expect(confirmFrame()).toBeNull();
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves true without a frame when the page knows the email is confirmed', async () => {
|
||||
puter.whoamiCache_ = Promise.resolve({ uuid: USER, email_confirmed: true });
|
||||
const ui = makeUI();
|
||||
const result = ui.requestEmailConfirmation();
|
||||
// Mounted only after the user lookup, so a frame would be in the DOM by now.
|
||||
await expect(result).resolves.toEqual({ response: true });
|
||||
expect(frameDialog()).toBeNull();
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
// The next call looks again rather than reusing the settled one.
|
||||
expect(ui.requestEmailConfirmation()).not.toBe(result);
|
||||
});
|
||||
|
||||
it('resolves true without showing the frame when the GUI finds the email already confirmed', async () => {
|
||||
const result = makeUI().requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed', confirmed: true });
|
||||
|
||||
await expect(result).resolves.toEqual({ response: true });
|
||||
expect(frameDialog()).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves the next call true without a frame once the user has confirmed in one', async () => {
|
||||
const ui = makeUI();
|
||||
const first = ui.requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed', confirmed: true });
|
||||
await expect(first).resolves.toEqual({ response: true });
|
||||
|
||||
await expect(ui.requestEmailConfirmation()).resolves.toEqual({ response: true });
|
||||
expect(frameDialog()).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves false when the user closes it without confirming', async () => {
|
||||
const result = makeUI().requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
// The frame's own close() reports no result.
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(result).resolves.toEqual({ response: false });
|
||||
});
|
||||
|
||||
it('resolves false when Escape on the page dismisses it', async () => {
|
||||
const result = makeUI().requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
frameDialog().dispatchEvent(new Event('cancel', { cancelable: true }));
|
||||
await expect(result).resolves.toEqual({ response: false });
|
||||
expect(confirmFrame()).toBeNull();
|
||||
});
|
||||
|
||||
it('settles a call made while it shows with it, without replacing it', async () => {
|
||||
const ui = makeUI();
|
||||
const first = ui.requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
const frame = confirmFrame();
|
||||
|
||||
const second = ui.requestEmailConfirmation();
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(document.querySelectorAll('dialog.puter-popup-frame')).toHaveLength(1);
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'ready' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'closed' });
|
||||
await expect(second).resolves.toEqual({ response: false });
|
||||
|
||||
// A later call shows a new one.
|
||||
ui.requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
expect(confirmFrame()).not.toBe(frame);
|
||||
});
|
||||
|
||||
it('resolves false when the frame cannot show it', async () => {
|
||||
const result = makeUI().requestEmailConfirmation();
|
||||
await vi.waitFor(() => expect(confirmFrame()).not.toBeNull());
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'loading' });
|
||||
fromFrame({ msg: 'puterPopupFrame', state: 'unavailable' });
|
||||
|
||||
await expect(result).resolves.toEqual({ response: false });
|
||||
expect(confirmFrame()).toBeNull();
|
||||
expect(window.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves false when the page has no user to name', async () => {
|
||||
puter.whoamiCache_ = Promise.resolve(null);
|
||||
puter.auth.getUser = vi.fn(async () => {
|
||||
throw new Error('nope');
|
||||
});
|
||||
await expect(makeUI().requestEmailConfirmation()).resolves.toEqual({ response: false });
|
||||
expect(confirmFrame()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ui.requestEmailConfirmation elsewhere', () => {
|
||||
it('asks the desktop inside an app and resolves its answer', async () => {
|
||||
const post = vi.spyOn(window, 'postMessage').mockImplementation(() => {});
|
||||
const result = makeUI('app').requestEmailConfirmation();
|
||||
|
||||
expect(post).toHaveBeenCalledWith(expect.objectContaining({
|
||||
msg: 'requestEmailConfirmation',
|
||||
env: 'app',
|
||||
appInstanceID: 'instance-1',
|
||||
}), '*');
|
||||
expect(confirmFrame()).toBeNull();
|
||||
|
||||
const { uuid } = post.mock.calls.find(([data]) => data.msg === 'requestEmailConfirmation')[0];
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'requestEmailConfirmationResponded', original_msg_id: uuid, response: true },
|
||||
origin: GUI_ORIGIN,
|
||||
source: window,
|
||||
}));
|
||||
await expect(result).resolves.toMatchObject({ response: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a signed-out first-party page', { signedIn: false }],
|
||||
['a page outside the Puter origin', { guiOrigin: 'https://puter.com' }],
|
||||
])('does not frame on %s', async (_label, options) => {
|
||||
fakePuter(options);
|
||||
const result = makeUI().requestEmailConfirmation();
|
||||
expect(await settled(result)).toBe(PENDING);
|
||||
expect(confirmFrame()).toBeNull();
|
||||
});
|
||||
});
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user