mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76ad6cbc2e | ||
|
|
9251bfa30b | ||
|
|
bf99c3c680 | ||
|
|
72de6e16b2 | ||
|
|
234994d3af | ||
|
|
eef2d089a8 | ||
|
|
711ece5800 | ||
|
|
40ea3686da | ||
|
|
db7ca8382b | ||
|
|
0f2c325598 | ||
|
|
ffcfb85749 | ||
|
|
44bf99f808 | ||
|
|
d392b6857d | ||
|
|
d8c3e01dd9 | ||
|
|
4bc679956f | ||
|
|
b751f75467 | ||
|
|
224b2f2367 | ||
|
|
80bcc4ba14 | ||
|
|
f26201649a | ||
|
|
1550be358d | ||
|
|
8a15f09f48 | ||
|
|
2084587885 | ||
|
|
222ffcfe39 | ||
|
|
7494aa1cbc | ||
|
|
1adca8a794 | ||
|
|
07b19888a4 |
No files matched your search
+1
-1
@@ -40,7 +40,7 @@ The following have already been reviewed and determined **not to be vulnerabilit
|
||||
- **SSRF via `secureFetch`.** Production routes outbound requests through an isolated proxy that has no access to internal/SSRF-sensitive resources.
|
||||
- **Attacks that depend on guessing an `appInstanceID` or app UID.** These are random 128-bit secret values and are not considered guessable.
|
||||
- **Apps invoking drivers, creating workers, or using KV.** Applications are intended to do this; worker permissions are scoped to the owning app. This is by design.
|
||||
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (taskbar items, `/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
|
||||
- **App metadata or app user-count "leaks".** This information is currently public by design. This covers **private apps** too: private apps are an unreleased, admin-only beta for paid listings in the Puter App Center. Their `index_url` and other metadata are not secret, the flag is not user-settable, and no production app relies on it. Reports that a private app's metadata is reachable through a sibling route (`/get-launch-apps`, `index_url` drift on the hosting gate, etc.) are normalization work, not vulnerabilities.
|
||||
- **Worker hot-reload driven by a share recipient.** Sharing a worker's source file with write access is how you let a collaborator change that worker's code and have it deploy live. The redeploy running as the file owner, with the owner's worker credentials, is the intended behavior of that grant — the owner chose to hand out write access to executable code. If you do not want that, do not share the source file with write access.
|
||||
- **Re-claiming a site or worker name its owner deleted.** A hosted site or worker name that its owner deletes is treated as abandoned by that owner. If one of their apps still points at it, whoever claims the name next serves that app's `index_url` and receives what the app is launched with, and a new app on the same origin may share the old one's identity. Guarding app identities against being recycled this way is ongoing hardening, not a security boundary, so new ways to re-claim an abandoned name, or to inherit an app's tokens or data through one, are not eligible.
|
||||
- **Share-mode downgrades that do not cascade.** Demoting a delegate does not retroactively revoke the grants that delegate already issued downstream. Shares are independent grants once issued, not a live-evaluated chain. Revoking the downstream grant is a separate, supported action.
|
||||
|
||||
@@ -259,6 +259,36 @@ 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 }`.
|
||||
|
||||
## Top-up
|
||||
|
||||
`GET /embed/top-up` is the deployment's top-up dialog, where a user with a plan
|
||||
buys add-on credit, served and framed like the upgrade: a transparent GUI page
|
||||
covering the host with no box or close button, allowing `payment` and
|
||||
`otp-credentials`, with Escape left to the dialog. Its fragment names `user`.
|
||||
|
||||
puter.js frames it for the **Add credits** item of `<puter-user-menu>`, which
|
||||
shows only when whoami reports `subscribed: true` and no `team` paying for the
|
||||
account. On a page that can't frame the GUI, the item opens the dashboard with
|
||||
`?topup=` in a new tab instead.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user`, the account
|
||||
has no verification or password change waiting, and the deployment defines
|
||||
`window.UITopUp` with `UITopUp.embeddable === true`. Otherwise it runs:
|
||||
|
||||
```js
|
||||
new UITopUp({ onClose }).open();
|
||||
```
|
||||
|
||||
`open()` resolves once the dialog has loaded the account and shows what it can
|
||||
buy, and `onClose({ toppedUp })` 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', toppedUp }`
|
||||
and the page removes the frame. When the frame can't show the top-up, puter.js
|
||||
opens the dashboard's top-up in a new tab, as it does the upgrade.
|
||||
|
||||
While the top-up shows, a call refused for funds still rejects but opens no
|
||||
usage limit dialog over it, and `requestUpgrade()` frames nothing over it: it
|
||||
resolves `{ upgraded: false }` once the top-up closes.
|
||||
|
||||
## Email confirmation
|
||||
|
||||
`GET /embed/request-email-confirmation` walks a first-party page's user through
|
||||
@@ -292,6 +322,36 @@ 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.
|
||||
|
||||
## Custom domains
|
||||
|
||||
`GET /embed/attach-custom-domain` is the custom domain dialog of
|
||||
`puter.hosting.attach()`, the popup at `/action/attach-custom-domain`, 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 (the same pages as the pickers).
|
||||
|
||||
The frame covers the page with no box or close button, over a transparent GUI
|
||||
page, so the dialog floats over the host with its own scrim as it does on the
|
||||
desktop. The frame allows `clipboard-write`, for the dialog's copy buttons, as
|
||||
well as `otp-credentials`. Escape on the page is left to the dialog, which
|
||||
doesn't close while a request is in flight. Its fragment names `user` (the
|
||||
page's signed-in user), `subdomain` (the site to attach a domain to) and
|
||||
`msg_id`.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user` and the
|
||||
account has no verification or password change waiting. It then runs the
|
||||
popup's action unchanged, with the framing page as the requester the dialog
|
||||
names: it posts `ready` once the dialog is on the page, answers
|
||||
`{ msg: 'customDomainAttached', domain, original_msg_id }` once the dialog has
|
||||
closed and its exit has played, and then posts `closed`. `domain` is the domain the user chose, or
|
||||
null. `attach()` resolves it. A frame that closes without an answer, or a
|
||||
loading scrim the user dismisses, resolves null.
|
||||
|
||||
A call made while the frame shows resolves null without replacing it, as a
|
||||
second call does on the desktop. A frame that is refused, never ready, or
|
||||
`unavailable` falls back to the popup, which can sign in, through a consent
|
||||
dialog when the click has expired.
|
||||
|
||||
## Checks
|
||||
|
||||
Run the GUI component/browser tests (with the SDK bundle built and Playwright
|
||||
@@ -299,7 +359,7 @@ Chromium installed), and the backend route tests:
|
||||
|
||||
```sh
|
||||
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 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/modules/UI.showTopUp.test.js src/puter-js/src/modules/UI.attachCustomDomainFrame.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
|
||||
```
|
||||
+40
-10
@@ -257,8 +257,41 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(body.created_ts).toBeGreaterThan(0);
|
||||
// `directories` is only sent to user actors — confirm it’s present.
|
||||
expect(body.directories).toBeDefined();
|
||||
// taskbar_items is only sent to user actors.
|
||||
expect(body).toHaveProperty('taskbar_items');
|
||||
});
|
||||
|
||||
it('leaves out taskbar items saved on the account', async () => {
|
||||
const user = await seedUser();
|
||||
await server.stores.user.update(user.id as number, {
|
||||
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
|
||||
});
|
||||
const { res, captured } = makeRes();
|
||||
|
||||
await runWithContext(
|
||||
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
|
||||
() => handleWhoami(makeReq(), res),
|
||||
);
|
||||
|
||||
expect(captured.body).not.toHaveProperty('taskbar_items');
|
||||
});
|
||||
|
||||
it('leaves out a desktop background saved on the account', async () => {
|
||||
const user = await seedUser();
|
||||
await server.stores.user.update(user.id as number, {
|
||||
desktop_bg_url: 'https://cdn.test/wallpaper.png',
|
||||
desktop_bg_color: '#000000',
|
||||
desktop_bg_fit: 'cover',
|
||||
});
|
||||
const { res, captured } = makeRes();
|
||||
|
||||
await runWithContext(
|
||||
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
|
||||
() => handleWhoami(makeReq(), res),
|
||||
);
|
||||
|
||||
const body = captured.body as Record<string, unknown>;
|
||||
expect(body).not.toHaveProperty('desktop_bg_url');
|
||||
expect(body).not.toHaveProperty('desktop_bg_color');
|
||||
expect(body).not.toHaveProperty('desktop_bg_fit');
|
||||
});
|
||||
|
||||
it('reports the SMS-to-card fallback only once a send has opened it', async () => {
|
||||
@@ -322,7 +355,7 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(flags.payment_bypass).toBeUndefined();
|
||||
});
|
||||
|
||||
it('strips desktop_bg_*, created_ts and human_readable_age fields for app actors', async () => {
|
||||
it('strips created_ts and human_readable_age fields for app actors', async () => {
|
||||
const user = await seedUser();
|
||||
const { res, captured } = makeRes();
|
||||
|
||||
@@ -340,9 +373,6 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(body.app_name).toBe('app-test-actor');
|
||||
// is_user_token is stripped for app actors.
|
||||
expect(body.is_user_token).toBeUndefined();
|
||||
expect(body.desktop_bg_url).toBeUndefined();
|
||||
expect(body.desktop_bg_color).toBeUndefined();
|
||||
expect(body.desktop_bg_fit).toBeUndefined();
|
||||
expect(body.human_readable_age).toBeUndefined();
|
||||
// Account age, in either form, is not exposed to apps.
|
||||
expect(body.created_ts).toBeUndefined();
|
||||
@@ -432,7 +462,7 @@ describe('whoami extension — handleWhoami', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot add taskbar_items for an app actor, which core omits', async () => {
|
||||
it('cannot add directories for an app actor, which core omits', async () => {
|
||||
const user = await seedUser();
|
||||
const body = await whoamiWithListener(
|
||||
makeActor({
|
||||
@@ -440,11 +470,11 @@ describe('whoami extension — handleWhoami', () => {
|
||||
app: { uid: 'app-test-actor' },
|
||||
}),
|
||||
(_key, event) => {
|
||||
event.details.taskbar_items = [{ name: 'injected' }];
|
||||
event.details.directories = { '/injected': 'uuid' };
|
||||
},
|
||||
);
|
||||
|
||||
expect(body).not.toHaveProperty('taskbar_items');
|
||||
expect(body).not.toHaveProperty('directories');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -525,7 +555,7 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(body.otp_secret).toBeUndefined();
|
||||
expect(body.signup_ip).toBeUndefined();
|
||||
// Not just absent as a key — the values must not appear anywhere
|
||||
// in the payload (nested under metadata, taskbar items, …).
|
||||
// in the payload (nested under metadata, …).
|
||||
const serialized = JSON.stringify(body);
|
||||
expect(serialized).not.toContain('5551234567');
|
||||
expect(serialized).not.toContain('fp_ABC123');
|
||||
|
||||
+2
-16
@@ -1,6 +1,5 @@
|
||||
import { Context } from '@heyputer/backend/src/core';
|
||||
import { extension } from '@heyputer/backend/src/extensions';
|
||||
import { APP_ICON_SIZES } from '@heyputer/backend/src/util/appIcon.js';
|
||||
import {
|
||||
buildUserDetails,
|
||||
scrubSensitive,
|
||||
@@ -54,19 +53,10 @@ export const handleWhoami = async (
|
||||
return;
|
||||
}
|
||||
|
||||
const rawIconSize =
|
||||
typeof req.query?.icon_size === 'string'
|
||||
? Number(req.query.icon_size)
|
||||
: undefined;
|
||||
const iconSize =
|
||||
rawIconSize !== undefined && APP_ICON_SIZES.includes(rawIconSize)
|
||||
? rawIconSize
|
||||
: undefined;
|
||||
|
||||
const details = await buildUserDetails(
|
||||
user,
|
||||
{ config: extension.config, clients, stores, services },
|
||||
{ isUser, iconSize, noIcons: !iconSize },
|
||||
{ isUser },
|
||||
);
|
||||
details.human_readable_age = user.timestamp
|
||||
? timeago.format(new Date(user.timestamp as string))
|
||||
@@ -81,9 +71,6 @@ export const handleWhoami = async (
|
||||
delete details.email;
|
||||
delete details.unconfirmed_email;
|
||||
}
|
||||
delete details.desktop_bg_url;
|
||||
delete details.desktop_bg_color;
|
||||
delete details.desktop_bg_fit;
|
||||
delete details.human_readable_age;
|
||||
delete details.created_ts;
|
||||
delete details.is_user_token;
|
||||
@@ -121,8 +108,7 @@ export const handleWhoami = async (
|
||||
}
|
||||
|
||||
const subscription = details.subscription as
|
||||
| { offering?: Record<string, unknown> }
|
||||
| undefined;
|
||||
{ offering?: Record<string, unknown> } | undefined;
|
||||
if (subscription?.offering) {
|
||||
delete subscription.offering.group;
|
||||
delete subscription.offering.benefits;
|
||||
|
||||
@@ -52,8 +52,8 @@ const APP_READ_LIMIT = {
|
||||
/**
|
||||
* Unauthenticated icon serving; no actor to key on, so the bucket is the
|
||||
* address — and an address is a NAT, a campus or a carrier gateway that can
|
||||
* hold hundreds of desktops. Each desktop boot pulls the taskbar's icons at
|
||||
* once, so a single burst from one network is already thousands of requests.
|
||||
* hold hundreds of desktops. Each dashboard load pulls its app icons at once,
|
||||
* so a single burst from one network is already thousands of requests.
|
||||
* Responses are publicly cacheable and usually a redirect, so the ceiling is
|
||||
* not protecting bandwidth; it is there so a client looping on a broken icon
|
||||
* can't spin unbounded.
|
||||
@@ -523,7 +523,7 @@ export class AppController extends PuterController {
|
||||
};
|
||||
|
||||
// Icons are <img src> targets from the GUI (root) AND resolved via
|
||||
// api_base_url in taskbar payloads. Register on both so either origin
|
||||
// api_base_url in app summaries. Register on both so either origin
|
||||
// works without a cross-subdomain redirect.
|
||||
router.get(
|
||||
'/app-icon/:app_uid',
|
||||
|
||||
@@ -1271,7 +1271,7 @@ describe('AppController app-icon rate limit', () => {
|
||||
it('sizes the icon bucket for a whole network rather than one desktop', () => {
|
||||
// Icons are unauthenticated `<img src>` targets, so the only key is
|
||||
// the address — which one NAT shares across every desktop behind it,
|
||||
// and each boot pulls the taskbar's icons in a burst.
|
||||
// and each dashboard load pulls its app icons in a burst.
|
||||
for (const path of ['/app-icon/:app_uid', '/app-icon/:app_uid/:size']) {
|
||||
const route = router.routes.find(
|
||||
(r) => r.method === 'get' && r.path === path,
|
||||
|
||||
@@ -1416,7 +1416,7 @@ describe('AuthController.handleLogin', () => {
|
||||
is_user_token: true,
|
||||
});
|
||||
expect(body.user.directories).toBeTypeOf('object');
|
||||
expect(Array.isArray(body.user.taskbar_items)).toBe(true);
|
||||
expect(body.user).not.toHaveProperty('taskbar_items');
|
||||
});
|
||||
|
||||
// A deleted row still answering from cache reaches the session INSERT.
|
||||
|
||||
@@ -25,18 +25,13 @@ const ALLOWED_SORT_BY = ['name', 'size', 'modified', 'type'];
|
||||
const ALLOWED_SORT_ORDER = ['asc', 'desc'];
|
||||
|
||||
/**
|
||||
* Desktop/UI preference routes.
|
||||
*
|
||||
* Two categories:
|
||||
*
|
||||
* - User-level: desktop background, taskbar items (UserStore)
|
||||
* - Folder-level: layout, sort_by/sort_order (fsentries table)
|
||||
* Folder view preference routes: layout and sort_by/sort_order, stored on the
|
||||
* folder's fsentries row.
|
||||
*/
|
||||
/**
|
||||
* Desktop preference writes — background, taskbar, layout, sort order. All four
|
||||
* persist to the user row on every call, and the GUI fires them on direct user
|
||||
* action, so a per-minute ceiling well above human speed is enough to catch a
|
||||
* stuck client.
|
||||
* Desktop preference writes — layout, sort order. Each persists on every call,
|
||||
* and the GUI fires them on direct user action, so a per-minute ceiling well
|
||||
* above human speed is enough to catch a stuck client.
|
||||
*/
|
||||
const PREFERENCE_WRITE_LIMIT = {
|
||||
scope: 'desktop-preference',
|
||||
@@ -47,89 +42,6 @@ const PREFERENCE_WRITE_LIMIT = {
|
||||
|
||||
export class DesktopController extends PuterController {
|
||||
registerRoutes(router) {
|
||||
// -- Desktop background --------------------------------------
|
||||
|
||||
router.post(
|
||||
'/set-desktop-bg',
|
||||
{
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
allowFullAccessToken: true,
|
||||
rateLimit: PREFERENCE_WRITE_LIMIT,
|
||||
},
|
||||
async (req, res) => {
|
||||
const { url, color, fit } = req.body ?? {};
|
||||
|
||||
const patch = {};
|
||||
if (url !== undefined) {
|
||||
if (url !== null && typeof url !== 'string') {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'`url` must be a string or null',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
patch.desktop_bg_url = url;
|
||||
}
|
||||
if (color !== undefined) {
|
||||
if (color !== null && typeof color !== 'string') {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'`color` must be a string or null',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
patch.desktop_bg_color = color;
|
||||
}
|
||||
if (fit !== undefined) {
|
||||
if (fit !== null && typeof fit !== 'string') {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'`fit` must be a string or null',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
patch.desktop_bg_fit = fit;
|
||||
}
|
||||
|
||||
if (Object.keys(patch).length === 0) {
|
||||
throw new HttpError(400, 'No fields provided', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
}
|
||||
|
||||
await this.stores.user.update(req.actor.user.id, patch);
|
||||
res.json({});
|
||||
},
|
||||
);
|
||||
|
||||
// -- Taskbar items -------------------------------------------
|
||||
|
||||
router.post(
|
||||
'/update-taskbar-items',
|
||||
{
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
allowFullAccessToken: true,
|
||||
rateLimit: PREFERENCE_WRITE_LIMIT,
|
||||
},
|
||||
async (req, res) => {
|
||||
const { items } = req.body ?? {};
|
||||
if (!Array.isArray(items)) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'Missing or invalid `items` array',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
|
||||
await this.stores.user.update(req.actor.user.id, {
|
||||
taskbar_items: JSON.stringify(items),
|
||||
});
|
||||
res.json({});
|
||||
},
|
||||
);
|
||||
|
||||
// -- Folder layout -------------------------------------------
|
||||
|
||||
router.post(
|
||||
|
||||
@@ -130,147 +130,17 @@ const callRoute = async (
|
||||
});
|
||||
};
|
||||
|
||||
// ── /set-desktop-bg ─────────────────────────────────────────────────
|
||||
|
||||
describe('DesktopController POST /set-desktop-bg', () => {
|
||||
it('persists url/color/fit on the user row', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({
|
||||
body: {
|
||||
url: 'https://cdn.test/wallpaper.png',
|
||||
color: '#000000',
|
||||
fit: 'cover',
|
||||
},
|
||||
actor,
|
||||
}),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({});
|
||||
|
||||
const refreshed = await server.stores.user.getById(userId);
|
||||
expect(refreshed?.desktop_bg_url).toBe(
|
||||
'https://cdn.test/wallpaper.png',
|
||||
);
|
||||
expect(refreshed?.desktop_bg_color).toBe('#000000');
|
||||
expect(refreshed?.desktop_bg_fit).toBe('cover');
|
||||
describe('DesktopController routes', () => {
|
||||
it('has no desktop background route', () => {
|
||||
expect(
|
||||
router.routes.some((r) => r.path === '/set-desktop-bg'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('persists only the supplied fields (partial update)', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: { color: '#ffffff' }, actor }),
|
||||
res,
|
||||
);
|
||||
const refreshed = await server.stores.user.getById(userId);
|
||||
expect(refreshed?.desktop_bg_color).toBe('#ffffff');
|
||||
// Untouched fields remain at their column default.
|
||||
expect(refreshed?.desktop_bg_url).toBeFalsy();
|
||||
expect(refreshed?.desktop_bg_fit).toBeFalsy();
|
||||
});
|
||||
|
||||
it('passes through `null` to clear a field', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
// First populate, then clear.
|
||||
const populate = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({
|
||||
body: { url: 'https://cdn.test/x.png' },
|
||||
actor,
|
||||
}),
|
||||
populate.res,
|
||||
);
|
||||
const before = await server.stores.user.getById(userId);
|
||||
expect(before?.desktop_bg_url).toBe('https://cdn.test/x.png');
|
||||
|
||||
const clear = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: { url: null }, actor }),
|
||||
clear.res,
|
||||
);
|
||||
const after = await server.stores.user.getById(userId);
|
||||
expect(after?.desktop_bg_url).toBeNull();
|
||||
});
|
||||
|
||||
it('throws 400 when url is not a string or null', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: { url: 123 }, actor }),
|
||||
res,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('throws 400 when no fields are provided', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: {}, actor }),
|
||||
res,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── /update-taskbar-items ───────────────────────────────────────────
|
||||
|
||||
describe('DesktopController POST /update-taskbar-items', () => {
|
||||
it('persists items as a JSON-encoded string', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const items = [{ name: 'editor' }, { name: 'browser' }];
|
||||
const { res } = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/update-taskbar-items',
|
||||
makeReq({ body: { items }, actor }),
|
||||
res,
|
||||
);
|
||||
|
||||
const refreshed = await server.stores.user.getById(userId);
|
||||
expect(refreshed?.taskbar_items).toBe(JSON.stringify(items));
|
||||
});
|
||||
|
||||
it('throws 400 when items is missing', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute(
|
||||
'post',
|
||||
'/update-taskbar-items',
|
||||
makeReq({ body: {}, actor }),
|
||||
res,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('throws 400 when items is not an array', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute(
|
||||
'post',
|
||||
'/update-taskbar-items',
|
||||
makeReq({ body: { items: 'oops' }, actor }),
|
||||
res,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
it('has no taskbar items route', () => {
|
||||
expect(
|
||||
router.routes.some((r) => r.path === '/update-taskbar-items'),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -501,6 +501,29 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
expect(body.service.name).toBe('puter-kvstore');
|
||||
});
|
||||
|
||||
it('treats null `args` as no arguments', async () => {
|
||||
const actor = await makeUserActor();
|
||||
await server.stores.permission.setFlatUserPerm(
|
||||
actor.user!.id!,
|
||||
'service:puter-subdomains:ii:puter-subdomains',
|
||||
{
|
||||
permission: 'service:puter-subdomains:ii:puter-subdomains',
|
||||
deleted: false,
|
||||
issuer_user_id: actor.user!.id!,
|
||||
} as never,
|
||||
);
|
||||
|
||||
const res = makeRes();
|
||||
const req = makeReq(
|
||||
{ interface: 'puter-subdomains', method: 'select', args: null },
|
||||
actor,
|
||||
);
|
||||
await runWithContext({ actor }, () =>
|
||||
routes['POST /call'](req, res as unknown as Response, () => {}),
|
||||
);
|
||||
expect((res.body as { success: boolean }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('pipes a stream-shaped result instead of JSON', async () => {
|
||||
// Use an ephemeral driver registered onto the controller's bag.
|
||||
const streamPayload = Buffer.from('hello-world');
|
||||
|
||||
@@ -276,8 +276,10 @@ export class DriverController extends PuterController {
|
||||
interface: ifaceName,
|
||||
method,
|
||||
driver: driverName,
|
||||
args = {},
|
||||
args: rawArgs,
|
||||
} = (req.body ?? {}) as Record<string, unknown>;
|
||||
// Drivers read fields off `args`, so a null one counts as absent.
|
||||
const args = rawArgs ?? {};
|
||||
|
||||
if (!ifaceName || typeof ifaceName !== 'string') {
|
||||
throw new HttpError(400, 'Missing or invalid `interface`', {
|
||||
|
||||
@@ -5111,9 +5111,8 @@ describe('LegacyFSController.updateFsentryThumbnail', () => {
|
||||
// ── GET /get-launch-apps ────────────────────────────────────────────
|
||||
//
|
||||
// `recent` is a launch-metadata producer: it returns `index_url` for
|
||||
// apps the user has opened before. The taskbar happens to launch these
|
||||
// by name (so AppDriver's hosted-backing guard applies), but the field
|
||||
// is served regardless, so the guard is applied here too.
|
||||
// apps the user has opened before. The field is served whoever reads it,
|
||||
// so AppDriver's hosted-backing guard is applied here too.
|
||||
|
||||
describe('LegacyFSController GET /get-launch-apps', () => {
|
||||
const hostedUrl = (sub: string) => `https://${sub}.site.puter.localhost/`;
|
||||
|
||||
@@ -401,11 +401,9 @@ export class LegacyFSController extends PuterController {
|
||||
.filter(Boolean);
|
||||
|
||||
// Don't hand out an index_url whose puter-hosted backing is
|
||||
// gone or reclaimed. The taskbar launches recents by name (so
|
||||
// AppDriver's guard applies), but this list is a
|
||||
// launch-metadata producer like any other — a future consumer
|
||||
// reading index_url straight off it shouldn't inherit a stale
|
||||
// origin.
|
||||
// gone or reclaimed. This list is a launch-metadata producer
|
||||
// like any other — a consumer reading index_url straight off
|
||||
// it shouldn't inherit a stale origin.
|
||||
let backingGoneFlags: boolean[];
|
||||
try {
|
||||
backingGoneFlags =
|
||||
@@ -950,9 +948,7 @@ export class LegacyFSController extends PuterController {
|
||||
// Trash, and `null`/`{}` when restoring. See
|
||||
// `src/gui/src/helpers.js` → `window.move_items`.
|
||||
newMetadata: (body.new_metadata ?? undefined) as
|
||||
| Record<string, unknown>
|
||||
| null
|
||||
| undefined,
|
||||
Record<string, unknown> | null | undefined,
|
||||
});
|
||||
const overwrittenEntry = replacedByMove(overwriteTarget, moved, name);
|
||||
const oldPath = source.path;
|
||||
@@ -1426,8 +1422,7 @@ export class LegacyFSController extends PuterController {
|
||||
}
|
||||
|
||||
type SignedOrEmpty =
|
||||
| (SignedFile & { path?: string })
|
||||
| Record<string, never>;
|
||||
(SignedFile & { path?: string }) | Record<string, never>;
|
||||
const result: { signatures: SignedOrEmpty[]; token?: string } = {
|
||||
signatures: [],
|
||||
};
|
||||
@@ -2054,10 +2049,7 @@ export class LegacyFSController extends PuterController {
|
||||
const subjectRef = body.subject;
|
||||
const appRef = body.app;
|
||||
const mode = (getString(body, 'mode') ?? 'read') as
|
||||
| 'see'
|
||||
| 'list'
|
||||
| 'read'
|
||||
| 'write';
|
||||
'see' | 'list' | 'read' | 'write';
|
||||
if (!subjectRef || !appRef)
|
||||
throw new HttpError(400, '`subject` and `app` are required', {
|
||||
legacyCode: 'bad_request',
|
||||
|
||||
@@ -36,9 +36,9 @@ import type {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade and
|
||||
* top-up dialogs, 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',
|
||||
@@ -46,7 +46,9 @@ export const FRAMED_POPUP_ACTIONS = [
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
] as const;
|
||||
|
||||
/** Longest description/og:description/twitter:description on `/app/<name>`. */
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* 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 { randomUUID } from 'node:crypto';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
setupPuterTestEnv,
|
||||
TEST_USER_CREDENTIALS,
|
||||
type PuterTestEnv,
|
||||
} from '../../testUtil.js';
|
||||
|
||||
/** A PUT body is the file, whatever content type the client labels it with. */
|
||||
describe('PUT stores the body as sent', () => {
|
||||
let env: PuterTestEnv;
|
||||
|
||||
beforeAll(async () => {
|
||||
env = await setupPuterTestEnv();
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await env?.shutdown();
|
||||
});
|
||||
|
||||
const dav = (path: string, init: RequestInit) => {
|
||||
const port = new URL(env.apiOrigin).port;
|
||||
const auth = Buffer.from(
|
||||
`${TEST_USER_CREDENTIALS.username}:${TEST_USER_CREDENTIALS.password}`,
|
||||
).toString('base64');
|
||||
return fetch(`http://dav.puter.localhost:${port}${encodeURI(path)}`, {
|
||||
...init,
|
||||
headers: { Authorization: `Basic ${auth}`, ...init.headers },
|
||||
});
|
||||
};
|
||||
|
||||
it.each([
|
||||
['application/json', '{"name":"report","rows":[1,2,3]}'],
|
||||
// Not JSON at all: the label alone must not get the body rejected.
|
||||
['application/json', 'not json'],
|
||||
['text/plain;actually=json', '{"a":1}'],
|
||||
['application/x-www-form-urlencoded', 'a=1&b=two'],
|
||||
['application/octet-stream', 'plain bytes'],
|
||||
])(
|
||||
'with Content-Type %s',
|
||||
async (contentType, content) => {
|
||||
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
|
||||
const put = await dav(path, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': contentType },
|
||||
body: content,
|
||||
});
|
||||
expect(put.status).toBe(201);
|
||||
|
||||
const get = await dav(path, { method: 'GET' });
|
||||
expect(get.status).toBe(200);
|
||||
expect(await get.text()).toBe(content);
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
it('with a form body over the form parser limit', async () => {
|
||||
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
|
||||
const content = `a=${'x'.repeat(200 * 1024)}`;
|
||||
const put = await dav(path, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: content,
|
||||
});
|
||||
expect(put.status).toBe(201);
|
||||
|
||||
const get = await dav(path, { method: 'GET' });
|
||||
expect(await get.text()).toBe(content);
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -224,7 +224,7 @@ const extractToken = (
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Query string (used by e.g. QR login, asset URLs).
|
||||
// 5. Query string (used by e.g. asset URLs).
|
||||
const queryToken = (req.query as { auth_token?: unknown } | undefined)
|
||||
?.auth_token;
|
||||
if (typeof queryToken === 'string' && queryToken.length > 0) {
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/*
|
||||
* 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 type { Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib';
|
||||
import express, {
|
||||
type ErrorRequestHandler,
|
||||
type RequestHandler,
|
||||
} from 'express';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { SLICE_BYTES } from '../../../util/slicedJson';
|
||||
import { createJsonBodyParser } from './jsonBody';
|
||||
|
||||
const LIMIT = 4 * 1024 * 1024;
|
||||
const TEXT_AS_JSON = 'text/plain;actually=json';
|
||||
|
||||
type Verify = NonNullable<Parameters<typeof express.json>[0]>['verify'];
|
||||
const captureRawBody: Verify = (req, _res, buf) => {
|
||||
(req as { rawBody?: Buffer }).rawBody = buf;
|
||||
};
|
||||
|
||||
/** An app that answers with what its parsers left on the request. */
|
||||
const listen = (parsers: RequestHandler[]): Promise<Server> => {
|
||||
const app = express();
|
||||
app.use(...parsers);
|
||||
app.post('/', (req, res) => {
|
||||
const rawBody = (req as { rawBody?: Buffer }).rawBody;
|
||||
res.json({
|
||||
body: req.body,
|
||||
hasBody: req.body !== undefined,
|
||||
rawBody: rawBody?.toString('base64'),
|
||||
});
|
||||
});
|
||||
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
res.status(err.statusCode ?? 500).json({ type: err.type });
|
||||
};
|
||||
app.use(onError);
|
||||
return new Promise((resolve) => {
|
||||
const server = app.listen(0, '127.0.0.1', () => resolve(server));
|
||||
});
|
||||
};
|
||||
|
||||
describe('createJsonBodyParser', () => {
|
||||
let sliced: Server;
|
||||
let framework: Server;
|
||||
|
||||
beforeAll(async () => {
|
||||
sliced = await listen([
|
||||
createJsonBodyParser({ limit: LIMIT, verify: captureRawBody }),
|
||||
]);
|
||||
// What the server ran before: one parser per content type.
|
||||
framework = await listen([
|
||||
express.json({ limit: LIMIT, verify: captureRawBody }),
|
||||
express.json({
|
||||
limit: LIMIT,
|
||||
type: (req) => req.headers['content-type'] === TEXT_AS_JSON,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
sliced?.close();
|
||||
framework?.close();
|
||||
});
|
||||
|
||||
const post = async (
|
||||
server: Server,
|
||||
body: string | Buffer | undefined,
|
||||
headers: Record<string, string>,
|
||||
) => {
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const response = await fetch(`http://127.0.0.1:${port}/`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body,
|
||||
});
|
||||
return { status: response.status, answer: await response.json() };
|
||||
};
|
||||
|
||||
const large = `${JSON.stringify({
|
||||
text: 'é😀 "quoted" \\ line\n'.repeat(SLICE_BYTES / 8),
|
||||
list: Array.from({ length: 20_000 }, (_, i) => ({
|
||||
i,
|
||||
on: i % 2 === 0,
|
||||
})),
|
||||
}).slice(0, -1)},"__proto__":{"nested":true}}`;
|
||||
|
||||
it.each<[string, string | Buffer | undefined, Record<string, string>]>([
|
||||
['an object', '{"a":1}', { 'Content-Type': 'application/json' }],
|
||||
['an array', '[1,2]', { 'Content-Type': 'application/json' }],
|
||||
[
|
||||
'a body sent as text',
|
||||
'{"interface":"x","auth_token":"t"}',
|
||||
{ 'Content-Type': TEXT_AS_JSON },
|
||||
],
|
||||
['a large body', large, { 'Content-Type': 'application/json' }],
|
||||
['a large body sent as text', large, { 'Content-Type': TEXT_AS_JSON }],
|
||||
[
|
||||
'a charset parameter',
|
||||
large,
|
||||
{ 'Content-Type': 'application/json; charset=UTF-8' },
|
||||
],
|
||||
[
|
||||
'a quoted charset parameter',
|
||||
'{"a":"é"}',
|
||||
{ 'Content-Type': 'application/json;charset="utf-8"' },
|
||||
],
|
||||
[
|
||||
'another parameter',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': 'application/json; profile=x' },
|
||||
],
|
||||
['an empty body', '', { 'Content-Type': 'application/json' }],
|
||||
['no body', undefined, { 'Content-Type': 'application/json' }],
|
||||
[
|
||||
'a byte order mark',
|
||||
`\ufeff${large}`,
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'only a byte order mark',
|
||||
'\ufeff',
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
['only whitespace', ' \n', { 'Content-Type': 'application/json' }],
|
||||
['a bare string', '"text"', { 'Content-Type': 'application/json' }],
|
||||
['a bare number', ' 12', { 'Content-Type': 'application/json' }],
|
||||
['null', 'null', { 'Content-Type': 'application/json' }],
|
||||
['malformed JSON', '{"a":', { 'Content-Type': 'application/json' }],
|
||||
[
|
||||
'malformed large JSON',
|
||||
`${large.slice(0, -1)},]`,
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'a large bare string',
|
||||
JSON.stringify('x'.repeat(4 * SLICE_BYTES)),
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'invalid UTF-8',
|
||||
Buffer.concat([
|
||||
Buffer.from('{"a":"'),
|
||||
Buffer.from([0xff, 0xe2, 0x82]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'a body over the limit',
|
||||
`["${'x'.repeat(LIMIT)}"]`,
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'a gzipped body',
|
||||
gzipSync(large),
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
|
||||
],
|
||||
[
|
||||
'a deflated body',
|
||||
deflateSync(large),
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Encoding': 'deflate',
|
||||
},
|
||||
],
|
||||
[
|
||||
'a brotli body',
|
||||
brotliCompressSync(large),
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'br' },
|
||||
],
|
||||
[
|
||||
'a body that inflates past the limit',
|
||||
gzipSync(`["${'x'.repeat(LIMIT)}"]`),
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
|
||||
],
|
||||
[
|
||||
'an unknown content encoding',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'lzw' },
|
||||
],
|
||||
['plain text', '{"a":1}', { 'Content-Type': 'text/plain' }],
|
||||
[
|
||||
'text with the marker and a charset',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': `${TEXT_AS_JSON}; charset=utf-8` },
|
||||
],
|
||||
[
|
||||
'a JSON-suffixed type',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': 'application/vnd.api+json' },
|
||||
],
|
||||
[
|
||||
'form data',
|
||||
'a=1',
|
||||
{ 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
],
|
||||
['no content type', '{"a":1}', { 'Content-Type': '' }],
|
||||
])('answers %s the way express.json does', async (_name, body, headers) => {
|
||||
const got = await post(sliced, body, headers);
|
||||
const want = await post(framework, body, headers);
|
||||
expect(got).toEqual(want);
|
||||
});
|
||||
|
||||
it('leaves a body in another charset unread', async () => {
|
||||
for (const charset of ['utf-16', 'utf8', 'latin1']) {
|
||||
const { status, answer } = await post(
|
||||
sliced,
|
||||
Buffer.from('{"a":1}', 'utf16le'),
|
||||
{ 'Content-Type': `application/json; charset=${charset}` },
|
||||
);
|
||||
expect(status).toBe(200);
|
||||
expect(answer.hasBody).toBe(false);
|
||||
}
|
||||
// The last charset named is the one that counts.
|
||||
const { answer } = await post(sliced, '{"a":1}', {
|
||||
'Content-Type': 'application/json; charset=utf-8; charset=utf-16',
|
||||
});
|
||||
expect(answer.hasBody).toBe(false);
|
||||
});
|
||||
|
||||
it('parses bodies that arrive together, each to its own result', async () => {
|
||||
const bodies = Array.from({ length: 6 }, (_, n) =>
|
||||
JSON.stringify({ n, pad: 'x'.repeat((n + 1) * SLICE_BYTES) }),
|
||||
);
|
||||
const answers = await Promise.all(
|
||||
bodies.map((body) =>
|
||||
post(sliced, body, { 'Content-Type': 'application/json' }),
|
||||
),
|
||||
);
|
||||
answers.forEach(({ status, answer }, n) => {
|
||||
expect(status).toBe(200);
|
||||
expect(answer.body).toEqual(JSON.parse(bodies[n]!));
|
||||
});
|
||||
// A failed parse hands its turn on like a finished one.
|
||||
const mixed = await Promise.all([
|
||||
post(sliced, `${bodies[5]!},`, {
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
post(sliced, bodies[4], { 'Content-Type': 'application/json' }),
|
||||
post(sliced, bodies[3], { 'Content-Type': 'application/json' }),
|
||||
]);
|
||||
expect(mixed.map(({ status }) => status)).toEqual([400, 200, 200]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* 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 express, { type Request, type RequestHandler } from 'express';
|
||||
import { parseJsonInSlices, SLICE_BYTES } from '../../../util/slicedJson';
|
||||
|
||||
/** What puter.js labels a JSON driver call, to keep it a simple CORS request. */
|
||||
const TEXT_AS_JSON = 'text/plain;actually=json';
|
||||
|
||||
const UTF8_CHARSET = /;\s*charset=("?)utf-8\1\s*(?:;|$)/i;
|
||||
|
||||
/** No charset, or exactly UTF-8. Anything else is left to `express.json`. */
|
||||
const declaresUtf8 = (contentType: string): boolean => {
|
||||
const mentions = contentType.match(/charset/gi)?.length ?? 0;
|
||||
return mentions === 0 || (mentions === 1 && UTF8_CHARSET.test(contentType));
|
||||
};
|
||||
|
||||
const isUtf8Json = (req: Request): boolean => {
|
||||
const contentType = req.headers['content-type'];
|
||||
if (contentType === TEXT_AS_JSON) return true;
|
||||
return (
|
||||
typeof contentType === 'string' &&
|
||||
Boolean(req.is('application/json')) &&
|
||||
declaresUtf8(contentType)
|
||||
);
|
||||
};
|
||||
|
||||
/** The error `express.json` raises, which the error handler answers with a 400. */
|
||||
const parseFailed = (message: string): Error =>
|
||||
Object.assign(new SyntaxError(message), {
|
||||
status: 400,
|
||||
statusCode: 400,
|
||||
expose: true,
|
||||
type: 'entity.parse.failed',
|
||||
});
|
||||
|
||||
const waiting: Array<() => void> = [];
|
||||
let parsing = false;
|
||||
|
||||
/**
|
||||
* Bodies too large for one `JSON.parse` call parse one at a time, so a single
|
||||
* tree is under construction however many arrive together.
|
||||
*/
|
||||
const parseInTurn = async (body: Buffer): Promise<unknown> => {
|
||||
if (body.length <= SLICE_BYTES) return parseJsonInSlices(body);
|
||||
if (parsing) await new Promise<void>((resolve) => waiting.push(resolve));
|
||||
parsing = true;
|
||||
try {
|
||||
return await parseJsonInSlices(body);
|
||||
} finally {
|
||||
// Handing over keeps `parsing` set, so a new arrival can't cut in.
|
||||
const next = waiting.shift();
|
||||
if (next) next();
|
||||
else parsing = false;
|
||||
}
|
||||
};
|
||||
|
||||
interface JsonBodyOptions {
|
||||
limit: number;
|
||||
verify?: NonNullable<Parameters<typeof express.raw>[0]>['verify'];
|
||||
}
|
||||
|
||||
/**
|
||||
* `express.json` for UTF-8 bodies, with the parse done in slices so a large
|
||||
* body can't hold the event loop. Reading, limits, decompression and `verify`
|
||||
* are the framework's; the result and the errors match `express.json`.
|
||||
*/
|
||||
export const createJsonBodyParser = ({
|
||||
limit,
|
||||
verify,
|
||||
}: JsonBodyOptions): RequestHandler => {
|
||||
const read = express.raw({
|
||||
limit,
|
||||
verify,
|
||||
type: (req) => isUtf8Json(req as Request),
|
||||
});
|
||||
|
||||
return (req, res, next) => {
|
||||
read(req, res, async (err?: unknown) => {
|
||||
// Not a Buffer: the reader skipped this request.
|
||||
if (err || !Buffer.isBuffer(req.body)) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
let body: Buffer = req.body;
|
||||
req.body = undefined;
|
||||
// The framework's decoder drops a byte order mark.
|
||||
if (body[0] === 0xef && body[1] === 0xbb && body[2] === 0xbf) {
|
||||
body = body.subarray(3);
|
||||
}
|
||||
if (body.length === 0) {
|
||||
req.body = {};
|
||||
next();
|
||||
return;
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = await parseInTurn(body);
|
||||
} catch (e) {
|
||||
next(parseFailed((e as Error).message));
|
||||
return;
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null) {
|
||||
next(parseFailed('JSON body must be an object or an array'));
|
||||
return;
|
||||
}
|
||||
req.body = parsed;
|
||||
next();
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* 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 { request, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { setImmediate as nextTurn } from 'node:timers/promises';
|
||||
import express, {
|
||||
type ErrorRequestHandler,
|
||||
type RequestHandler,
|
||||
} from 'express';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createJsonBodyParser } from './jsonBody';
|
||||
import {
|
||||
createLargeJsonBodyParser,
|
||||
DEFAULT_JSON_LIMIT_BYTES,
|
||||
} from './largeJsonBody';
|
||||
|
||||
const MiB = 1024 * 1024;
|
||||
const TOKEN = 'valid-token';
|
||||
const PAD = 'x'.repeat(DEFAULT_JSON_LIMIT_BYTES);
|
||||
|
||||
/** Stands in for the auth probe: one token is valid, wherever it is sent. */
|
||||
const authProbe: RequestHandler = (req, _res, next) => {
|
||||
const token =
|
||||
(req.body as { auth_token?: string } | undefined)?.auth_token ??
|
||||
req.headers.authorization;
|
||||
if (!req.actor && token === TOKEN) {
|
||||
req.actor = { user: { uuid: 'u1' } } as typeof req.actor;
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
describe('a JSON body over the default limit', () => {
|
||||
let server: Server;
|
||||
|
||||
beforeAll(async () => {
|
||||
const app = express();
|
||||
app.post(
|
||||
'/call',
|
||||
createLargeJsonBodyParser({
|
||||
authProbe,
|
||||
limitBytes: 128 * MiB,
|
||||
budgetBytes: 256 * MiB,
|
||||
perUserBytes: 128 * MiB,
|
||||
}),
|
||||
);
|
||||
app.use(createJsonBodyParser({ limit: DEFAULT_JSON_LIMIT_BYTES }));
|
||||
app.use(authProbe);
|
||||
app.post('/call', (req, res) => {
|
||||
const body = req.body as { auth_token?: string; pad: string };
|
||||
res.json({
|
||||
user: req.actor?.user.uuid ?? null,
|
||||
token: body.auth_token ?? null,
|
||||
padLength: body.pad.length,
|
||||
});
|
||||
});
|
||||
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
res.status(err.statusCode ?? 500).json({});
|
||||
};
|
||||
app.use(onError);
|
||||
await new Promise<void>((resolve) => {
|
||||
server = app.listen(0, '127.0.0.1', resolve);
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server?.close();
|
||||
});
|
||||
|
||||
/** Sends `chunks` one write at a time, so the server sees them apart. */
|
||||
const post = (chunks: string[], headers: Record<string, string> = {}) =>
|
||||
new Promise<{ status: number; answer: Record<string, unknown> }>(
|
||||
(resolve, reject) => {
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const req = request(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
path: '/call',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'text/plain;actually=json',
|
||||
'Content-Length': chunks.reduce(
|
||||
(total, chunk) =>
|
||||
total + Buffer.byteLength(chunk),
|
||||
0,
|
||||
),
|
||||
...headers,
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
const parts: Buffer[] = [];
|
||||
res.on('data', (part: Buffer) => parts.push(part));
|
||||
res.on('end', () =>
|
||||
resolve({
|
||||
status: res.statusCode!,
|
||||
answer: JSON.parse(
|
||||
Buffer.concat(parts).toString(),
|
||||
),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
void (async () => {
|
||||
for (const chunk of chunks) {
|
||||
req.write(chunk);
|
||||
await nextTurn();
|
||||
}
|
||||
req.end();
|
||||
})();
|
||||
},
|
||||
);
|
||||
|
||||
it('is accepted when it opens with a valid auth_token', async () => {
|
||||
const { status, answer } = await post([
|
||||
`{"auth_token":"${TOKEN}","pad":"${PAD}"}`,
|
||||
]);
|
||||
expect(status).toBe(200);
|
||||
expect(answer).toEqual({
|
||||
user: 'u1',
|
||||
token: TOKEN,
|
||||
padLength: PAD.length,
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
it('is accepted when the token arrives in pieces, with spacing', async () => {
|
||||
const opening = ` {\n "auth_token" : "${TOKEN}" ,`;
|
||||
const { status, answer } = await post([...opening, `"pad":"${PAD}"}`]);
|
||||
expect(status).toBe(200);
|
||||
expect(answer.user).toBe('u1');
|
||||
}, 60_000);
|
||||
|
||||
it('is accepted with a header credential, as before', async () => {
|
||||
const { status, answer } = await post([`{"pad":"${PAD}"}`], {
|
||||
Authorization: TOKEN,
|
||||
});
|
||||
expect(status).toBe(200);
|
||||
expect(answer).toEqual({
|
||||
user: 'u1',
|
||||
token: null,
|
||||
padLength: PAD.length,
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
it.each([
|
||||
[
|
||||
'its token comes after other fields',
|
||||
`{"pad":"${PAD}","auth_token":"${TOKEN}"}`,
|
||||
],
|
||||
['its token is not valid', `{"auth_token":"expired","pad":"${PAD}"}`],
|
||||
['it has no token', `{"pad":"${PAD}"}`],
|
||||
[
|
||||
'a later field replaces the token it opens with',
|
||||
`{"auth_token":"${TOKEN}","pad":"${PAD}","auth_token":"other"}`,
|
||||
],
|
||||
[
|
||||
'the token it opens with is nested',
|
||||
`{"args":{"auth_token":"${TOKEN}"},"pad":"${PAD}"}`,
|
||||
],
|
||||
])(
|
||||
'is refused with 413 when %s',
|
||||
async (_name, body) => {
|
||||
expect((await post([body])).status).toBe(413);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { Readable } from 'node:stream';
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { isHttpError } from '../HttpError';
|
||||
@@ -35,7 +36,7 @@ const makeReq = (
|
||||
user: string | null = 'u1',
|
||||
body?: unknown,
|
||||
) =>
|
||||
({
|
||||
Object.assign(Readable.from([]), {
|
||||
complete: true,
|
||||
body,
|
||||
headers: {
|
||||
|
||||
@@ -17,13 +17,54 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import express, { type Request, type RequestHandler } from 'express';
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
import { actorUid } from '../../actor';
|
||||
import { HttpError } from '../HttpError';
|
||||
import { createJsonBodyParser } from './jsonBody';
|
||||
|
||||
/** The global JSON parser's limit, which applies before auth. */
|
||||
export const DEFAULT_JSON_LIMIT_BYTES = 50 * 1024 * 1024;
|
||||
|
||||
/** How much of a body is read to find a token it opens with. */
|
||||
const LEADING_TOKEN_BYTES = 8 * 1024;
|
||||
const LEADING_TOKEN =
|
||||
/^[ \t\n\r]*\{[ \t\n\r]*"auth_token"[ \t\n\r]*:[ \t\n\r]*"([^"\\]+)"/;
|
||||
|
||||
/**
|
||||
* The first `bytes` of the body, put back for the parser to read. Empty when
|
||||
* the body ends or fails before that many arrive.
|
||||
*/
|
||||
const peekBody = (req: Request, bytes: number): Promise<Buffer> =>
|
||||
new Promise((resolve) => {
|
||||
const settle = (head: Buffer | null) => {
|
||||
req.off('readable', onReadable);
|
||||
req.off('end', onGone);
|
||||
req.off('close', onGone);
|
||||
req.off('error', onGone);
|
||||
if (head) req.unshift(head);
|
||||
resolve(head ?? Buffer.alloc(0));
|
||||
};
|
||||
const onReadable = () => {
|
||||
// Null until `bytes` are buffered.
|
||||
const head = req.read(bytes) as Buffer | null;
|
||||
if (head) settle(head);
|
||||
};
|
||||
const onGone = () => settle(null);
|
||||
req.on('readable', onReadable);
|
||||
req.on('end', onGone);
|
||||
req.on('close', onGone);
|
||||
req.on('error', onGone);
|
||||
});
|
||||
|
||||
/**
|
||||
* The `auth_token` a JSON body opens with, which puter.js sends first so it can
|
||||
* be read ahead of the body.
|
||||
*/
|
||||
const leadingBodyToken = async (req: Request): Promise<string | undefined> => {
|
||||
const head = await peekBody(req, LEADING_TOKEN_BYTES);
|
||||
return LEADING_TOKEN.exec(head.toString('latin1'))?.[1];
|
||||
};
|
||||
|
||||
interface LargeJsonBodyOptions {
|
||||
/** The global auth probe; it skips requests that already carry an actor. */
|
||||
authProbe: RequestHandler;
|
||||
@@ -38,9 +79,9 @@ interface LargeJsonBodyOptions {
|
||||
|
||||
/**
|
||||
* Parses JSON bodies over the default limit, up to `limitBytes`, once the
|
||||
* caller's header or cookie credential resolves. Unauthenticated requests and
|
||||
* requests without a Content-Length fall through to the global parser and its
|
||||
* limit.
|
||||
* caller's credential resolves: a header, a cookie, or an `auth_token` the body
|
||||
* opens with. Unauthenticated requests and requests without a Content-Length
|
||||
* fall through to the global parser and its limit.
|
||||
*
|
||||
* The parsed body lives as long as the request, so a body's bytes count against
|
||||
* both budgets until its response closes. Over the user's budget gets a 429,
|
||||
@@ -53,82 +94,91 @@ export const createLargeJsonBodyParser = ({
|
||||
perUserBytes,
|
||||
accepts,
|
||||
}: LargeJsonBodyOptions): RequestHandler => {
|
||||
const json = express.json({ limit: limitBytes });
|
||||
const textAsJson = express.json({
|
||||
limit: limitBytes,
|
||||
type: (req) =>
|
||||
req.headers['content-type'] === 'text/plain;actually=json',
|
||||
});
|
||||
const json = createJsonBodyParser({ limit: limitBytes });
|
||||
let inFlightBytes = 0;
|
||||
const inFlightByUser = new Map<string, number>();
|
||||
|
||||
return (req, res, next) => {
|
||||
const probe = (req: Request, res: Response) =>
|
||||
new Promise<void>((resolve) => {
|
||||
void authProbe(req, res, () => resolve());
|
||||
});
|
||||
|
||||
return async (req, res, next) => {
|
||||
const declared = Number(req.headers['content-length']);
|
||||
if (!(declared > DEFAULT_JSON_LIMIT_BYTES && declared <= limitBytes)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
void authProbe(req, res, () => {
|
||||
// `res.closed`: the client left during the probe, so `close` has
|
||||
// already fired and would never release a charge.
|
||||
if (!req.actor || res.closed) {
|
||||
next();
|
||||
await probe(req, res);
|
||||
let bodyToken: string | undefined;
|
||||
if (!req.actor && !res.closed) {
|
||||
bodyToken = await leadingBodyToken(req);
|
||||
if (bodyToken) {
|
||||
// Where the probe looks for a body token.
|
||||
req.body = { auth_token: bodyToken };
|
||||
await probe(req, res);
|
||||
req.body = undefined;
|
||||
}
|
||||
}
|
||||
// `res.closed`: the client left during the probe, so `close` has
|
||||
// already fired and would never release a charge.
|
||||
if (!req.actor || res.closed) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const user = req.actor.user.uuid ?? actorUid(req.actor);
|
||||
const userBytes = inFlightByUser.get(user) ?? 0;
|
||||
if (userBytes + declared > perUserBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
next(
|
||||
new HttpError(
|
||||
429,
|
||||
'Too many large requests in progress for this account',
|
||||
{ legacyCode: 'too_many_requests' },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (inFlightBytes + declared > budgetBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
next(
|
||||
new HttpError(503, 'Too many large requests in progress', {
|
||||
code: 'large_body_capacity',
|
||||
// Load shedding, not a fault: record it, don't page.
|
||||
alarmSeverity: 'info',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
inFlightBytes += declared;
|
||||
inFlightByUser.set(user, userBytes + declared);
|
||||
res.once('close', () => {
|
||||
inFlightBytes -= declared;
|
||||
const left = (inFlightByUser.get(user) ?? 0) - declared;
|
||||
if (left > 0) inFlightByUser.set(user, left);
|
||||
else inFlightByUser.delete(user);
|
||||
});
|
||||
json(req, res, (err?: unknown) => {
|
||||
if (err) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
const user = req.actor.user.uuid ?? actorUid(req.actor);
|
||||
const userBytes = inFlightByUser.get(user) ?? 0;
|
||||
if (userBytes + declared > perUserBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
// The caller was resolved from the token the body opens with,
|
||||
// so the parsed body has to name the same one.
|
||||
const tokenMoved =
|
||||
bodyToken !== undefined &&
|
||||
(req.body as { auth_token?: unknown } | undefined)
|
||||
?.auth_token !== bodyToken;
|
||||
if (tokenMoved || (accepts && !accepts(req))) {
|
||||
// The same answer the default limit gives.
|
||||
next(
|
||||
new HttpError(
|
||||
429,
|
||||
'Too many large requests in progress for this account',
|
||||
{ legacyCode: 'too_many_requests' },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (inFlightBytes + declared > budgetBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
next(
|
||||
new HttpError(503, 'Too many large requests in progress', {
|
||||
code: 'large_body_capacity',
|
||||
// Load shedding, not a fault: record it, don't page.
|
||||
alarmSeverity: 'info',
|
||||
new HttpError(413, 'request entity too large', {
|
||||
legacyCode: 'client_bad_request',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
inFlightBytes += declared;
|
||||
inFlightByUser.set(user, userBytes + declared);
|
||||
res.once('close', () => {
|
||||
inFlightBytes -= declared;
|
||||
const left = (inFlightByUser.get(user) ?? 0) - declared;
|
||||
if (left > 0) inFlightByUser.set(user, left);
|
||||
else inFlightByUser.delete(user);
|
||||
});
|
||||
json(req, res, (err?: unknown) => {
|
||||
if (err) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
textAsJson(req, res, (err?: unknown) => {
|
||||
if (err) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
if (accepts && !accepts(req)) {
|
||||
// The same answer the default limit gives.
|
||||
next(
|
||||
new HttpError(413, 'request entity too large', {
|
||||
legacyCode: 'client_bad_request',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
});
|
||||
next();
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -355,6 +355,17 @@ describe('ChatCompletionDriver.complete auth and model resolution', () => {
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('rejects a model that is not a string with 400', async () => {
|
||||
await expect(
|
||||
withTestActor(() =>
|
||||
driver.complete({
|
||||
messages: [{ role: 'user', content: 'hi' }],
|
||||
model: { id: 'gpt' },
|
||||
} as unknown as ICompleteArguments),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('routes by alias when a provider exposes one (puterId is auto-aliased on the bucket)', async () => {
|
||||
// Inject a model that carries a `puterId` so we can verify the
|
||||
// alias bucket resolves back to the canonical id. Spy on
|
||||
|
||||
@@ -79,6 +79,7 @@ import type {
|
||||
} from './types.js';
|
||||
import { normalize_tools_object } from './utils/FunctionCalling.js';
|
||||
import {
|
||||
requestedServiceSpeed,
|
||||
selectServiceSpeed,
|
||||
lowerServiceSpeed,
|
||||
isServiceSpeedUnavailable,
|
||||
@@ -909,18 +910,16 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
attemptProvider: IChatProvider,
|
||||
baseModel: IChatModel,
|
||||
) => {
|
||||
let requestedSpeed = requestedServiceSpeed(
|
||||
args,
|
||||
baseModel.provider,
|
||||
);
|
||||
const offers =
|
||||
args.serviceSpeed !== undefined &&
|
||||
args.serviceSpeed !== 'standard'
|
||||
requestedSpeed !== undefined && requestedSpeed !== 'standard'
|
||||
? ((await attemptProvider.serviceSpeedModels?.(
|
||||
baseModel,
|
||||
)) ?? {})
|
||||
: {};
|
||||
let requestedSpeed =
|
||||
args.serviceSpeed ??
|
||||
(baseModel.provider === 'claude' && args.speed === 'fast'
|
||||
? 'fast'
|
||||
: undefined);
|
||||
for (;;) {
|
||||
const selection = selectServiceSpeed(
|
||||
baseModel,
|
||||
@@ -2130,7 +2129,9 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
}
|
||||
|
||||
#resolveModel(modelId: string, provider?: string): IChatModel | null {
|
||||
const models = this.#modelIdMap[normalizeModelKey(modelId ?? '')];
|
||||
// `model` comes straight from the caller and may not be a string.
|
||||
if (typeof modelId !== 'string') return null;
|
||||
const models = this.#modelIdMap[normalizeModelKey(modelId)];
|
||||
if (!models || models.length === 0) return null;
|
||||
// An explicitly requested provider is honoured even if its route is
|
||||
// marked — the caller asked for that one, not for the cheapest hop.
|
||||
|
||||
@@ -44,7 +44,9 @@ import {
|
||||
type MockInstance,
|
||||
} from 'vitest';
|
||||
|
||||
import { SYSTEM_ACTOR } from '../../../../core/actor.js';
|
||||
import { SYSTEM_ACTOR, type Actor } from '../../../../core/actor.js';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { ChatCompletionDriver } from '../../ChatCompletionDriver.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import { PuterServer } from '../../../../server.js';
|
||||
import { setupTestServer } from '../../../../testUtil.js';
|
||||
@@ -1580,3 +1582,117 @@ describe('OpenAiResponsesChatProvider.complete error mapping', () => {
|
||||
expect(recordSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChatCompletionDriver OpenAI billing', () => {
|
||||
const makeBillingUser = async () => {
|
||||
const user = await server.stores.user.create({
|
||||
username: `billing-${uuidv4().slice(0, 8)}`,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email: null,
|
||||
free_storage: 1000000,
|
||||
requires_email_confirmation: false,
|
||||
});
|
||||
return { user: { ...user, email_confirmed: true } } as Actor;
|
||||
};
|
||||
const makeBillingDriver = async () => {
|
||||
const driver = new ChatCompletionDriver(
|
||||
{
|
||||
providers: {
|
||||
ollama: { enabled: false },
|
||||
'openai-completion': { apiKey: 'test-key' },
|
||||
},
|
||||
} as never,
|
||||
server.clients,
|
||||
server.stores,
|
||||
server.services,
|
||||
);
|
||||
await driver.onServerStart();
|
||||
return driver;
|
||||
};
|
||||
it('meters an empty Responses completion before returning its error', async () => {
|
||||
const actor = await makeBillingUser();
|
||||
const driver = await makeBillingDriver();
|
||||
const before = await server.services.metering.getRemainingUsage(actor);
|
||||
responsesCreateMock.mockResolvedValueOnce({
|
||||
status: 'incomplete',
|
||||
incomplete_details: { reason: 'max_output_tokens' },
|
||||
output: [],
|
||||
output_text: '',
|
||||
usage: {
|
||||
input_tokens: 1200,
|
||||
output_tokens: 2000,
|
||||
output_tokens_details: { reasoning_tokens: 2000 },
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
withTestActor(
|
||||
() =>
|
||||
driver.complete({
|
||||
model: 'gpt-5.4-mini',
|
||||
provider: 'openai-responses',
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
max_tokens: 1,
|
||||
fallback: false,
|
||||
}),
|
||||
actor,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
expect(responsesCreateMock).toHaveBeenCalledTimes(1);
|
||||
expect(recordSpy).toHaveBeenCalledTimes(1);
|
||||
expect(recordSpy.mock.calls[0][0]).toMatchObject({
|
||||
prompt_tokens: 1200,
|
||||
completion_tokens: 2000,
|
||||
});
|
||||
await Promise.all(recordSpy.mock.results.map((result) => result.value));
|
||||
expect(
|
||||
await server.services.metering.getRemainingUsage(actor),
|
||||
).toBeLessThan(before);
|
||||
});
|
||||
it('prices a raw priority tier with the same rate card as fast service', async () => {
|
||||
const actor = await makeBillingUser();
|
||||
const driver = await makeBillingDriver();
|
||||
const charges: number[] = [];
|
||||
for (const extra of [
|
||||
{},
|
||||
{ service_tier: 'priority' },
|
||||
{ serviceSpeed: 'fast' },
|
||||
]) {
|
||||
responsesCreateMock.mockResolvedValueOnce({
|
||||
output: [],
|
||||
output_text: 'hi',
|
||||
service_tier: Object.keys(extra).length
|
||||
? 'priority'
|
||||
: 'default',
|
||||
usage: { input_tokens: 100, output_tokens: 100 },
|
||||
});
|
||||
const before =
|
||||
await server.services.metering.getRemainingUsage(actor);
|
||||
await withTestActor(
|
||||
() =>
|
||||
driver.complete({
|
||||
model: 'gpt-6.1-terra',
|
||||
provider: 'openai-responses',
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
max_tokens: 100,
|
||||
fallback: false,
|
||||
...extra,
|
||||
} as never),
|
||||
actor,
|
||||
);
|
||||
await Promise.all(
|
||||
recordSpy.mock.results.map((result) => result.value),
|
||||
);
|
||||
charges.push(
|
||||
before -
|
||||
(await server.services.metering.getRemainingUsage(actor)),
|
||||
);
|
||||
}
|
||||
expect(responsesCreateMock.mock.calls[1][0].service_tier).toBe(
|
||||
'priority',
|
||||
);
|
||||
expect(charges[0]).toBeGreaterThan(0);
|
||||
expect(charges[1]).toBe(charges[2]);
|
||||
expect(charges[2]).toBe(charges[0] * 2);
|
||||
});
|
||||
});
|
||||
@@ -1122,16 +1122,6 @@ export const handle_completion_output_responses_api = async ({
|
||||
// Inline-compaction artifact, if the upstream compacted this turn.
|
||||
const compactionItem = output.find((item) => item?.type === 'compaction');
|
||||
|
||||
const is_empty = completion.output_text.trim() === '';
|
||||
if (is_empty && responseToolCalls.length < 1 && !compactionItem) {
|
||||
// GPT refuses to generate an empty response if you ask it to,
|
||||
// so this will probably only happen on an error condition.
|
||||
// A compaction-only output is legitimate, so don't reject it.
|
||||
throw new HttpError(400, 'an empty response was generated', {
|
||||
legacyCode: 'bad_response',
|
||||
});
|
||||
}
|
||||
|
||||
// Reasoning models return `reasoning` output items; their human-readable
|
||||
// text only exists when the caller requested summaries via
|
||||
// `reasoning: { summary: ... }` (raw chain-of-thought is never returned).
|
||||
@@ -1234,6 +1224,14 @@ export const handle_completion_output_responses_api = async ({
|
||||
if (usageDetails) ret.usageDetails = usageDetails;
|
||||
}
|
||||
|
||||
// Empty output can still include paid reasoning and input tokens.
|
||||
const isEmpty = completion.output_text.trim() === '';
|
||||
if (isEmpty && responseToolCalls.length < 1 && !compactionItem) {
|
||||
throw new HttpError(400, 'an empty response was generated', {
|
||||
legacyCode: 'bad_response',
|
||||
});
|
||||
}
|
||||
|
||||
const mod_text = completion.output_text;
|
||||
if (moderate && mod_text !== null) {
|
||||
await applyModeration(moderate, mod_text);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from './OpenAIUtil.js';
|
||||
import type { IChatModel, ServiceSpeed } from '../types.js';
|
||||
import {
|
||||
requestedServiceSpeed,
|
||||
selectServiceSpeed,
|
||||
servedServiceSpeed,
|
||||
serviceSpeedBillingModel,
|
||||
@@ -83,6 +84,31 @@ describe('service speed selection', () => {
|
||||
expect(selected.model).toBe(entry);
|
||||
expect(selected.args).toBe(args);
|
||||
});
|
||||
it.each([
|
||||
[{ service_tier: 'priority' }, 'openai-responses', 'fast'],
|
||||
[{ service_tier: 'ultrafast' }, 'openai-responses', 'ultrafast'],
|
||||
[{ service_tier: 'auto' }, 'mistral', 'fast'],
|
||||
[{ speed: 'fast' }, 'claude', 'fast'],
|
||||
[{ service_tier: 'auto' }, 'openai-responses', undefined],
|
||||
[{ service_tier: 'flex' }, 'openai-responses', undefined],
|
||||
[{ speed: 'fast' }, 'openai-responses', undefined],
|
||||
[{ serviceSpeed: 'standard', service_tier: 'priority' }, 'openai-responses', 'standard'],
|
||||
] as const)('reads %j on %s as speed %s', (args, provider, speed) => {
|
||||
expect(requestedServiceSpeed(args, provider)).toBe(speed);
|
||||
});
|
||||
it('prices a native priority tier like fast service', () => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
const args = { ...request(), service_tier: 'priority' as const };
|
||||
const selected = selectServiceSpeed(
|
||||
entry,
|
||||
{ ...args, serviceSpeed: requestedServiceSpeed(args, entry.provider) },
|
||||
noVariant,
|
||||
);
|
||||
const explicit = selectServiceSpeed(entry, request('fast'), noVariant);
|
||||
expect(selected.speed).toBe('fast');
|
||||
expect(selected.model).toEqual(explicit.model);
|
||||
expect(selected.args.service_tier).toBe('priority');
|
||||
});
|
||||
it.each([
|
||||
'deepseek',
|
||||
'zai',
|
||||
@@ -248,6 +274,33 @@ describe('served speed billing', () => {
|
||||
expect(recorded).toEqual([result.costs]);
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
['fast', 2],
|
||||
['ultrafast', 6],
|
||||
] as const)(
|
||||
'bills a served %s tier at its catalog rate without a selection snapshot',
|
||||
(speed, multiplier) => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
entry.pricingOverrides = [
|
||||
{
|
||||
minPromptTokens: 100,
|
||||
costs: { prompt_tokens: 400, completion_tokens: 1500 },
|
||||
},
|
||||
];
|
||||
const billed = serviceSpeedBillingModel(entry, speed);
|
||||
expect(billed.costs.prompt_tokens).toBe(200 * multiplier);
|
||||
expect(billed.pricingOverrides?.[0]?.costs.prompt_tokens).toBe(
|
||||
400 * multiplier,
|
||||
);
|
||||
expect(serviceSpeedBillingModel(entry, 'standard')).toBe(entry);
|
||||
},
|
||||
);
|
||||
it('bills a served premium tier as standard when the catalog has no rate for it', () => {
|
||||
const entry = model('groq', 'some-model');
|
||||
expect(serviceSpeedBillingModel(entry, 'fast').costs).toEqual(
|
||||
entry.costs,
|
||||
);
|
||||
});
|
||||
it('restores standard scheduled and long-context rates after a downgrade', () => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
entry.pricingOverrides = [
|
||||
|
||||
@@ -59,6 +59,26 @@ export interface ServiceSpeedSelection {
|
||||
speed: ServiceSpeed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The speed a request asks for. Native premium tier parameters count as the
|
||||
* matching `serviceSpeed`, so they are priced like it; `serviceSpeed` wins.
|
||||
*/
|
||||
export const requestedServiceSpeed = (
|
||||
args: Pick<ICompleteArguments, 'serviceSpeed' | 'service_tier' | 'speed'>,
|
||||
provider: string | undefined,
|
||||
): ServiceSpeed | undefined => {
|
||||
if (args.serviceSpeed !== undefined) return args.serviceSpeed;
|
||||
if (args.service_tier === 'ultrafast') return 'ultrafast';
|
||||
if (
|
||||
args.service_tier === 'priority' ||
|
||||
(provider === 'claude' && args.speed === 'fast') ||
|
||||
// Mistral's `auto` tier is its priority tier.
|
||||
(provider === 'mistral' && args.service_tier === 'auto')
|
||||
)
|
||||
return 'fast';
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Select only an equivalent model from the same provider's loaded catalog. */
|
||||
export const selectServiceSpeed = (
|
||||
model: IChatModel,
|
||||
@@ -201,16 +221,27 @@ export const servedServiceSpeed = (
|
||||
: 'standard';
|
||||
};
|
||||
|
||||
/**
|
||||
* The model priced at the speed the provider served. Without a selection
|
||||
* snapshot the catalog's rates for that speed apply, so a premium tier reached
|
||||
* some other way is never billed as standard.
|
||||
*/
|
||||
export const serviceSpeedBillingModel = (
|
||||
model: IChatModel,
|
||||
speed: ServiceSpeed,
|
||||
): IChatModel => {
|
||||
const pricing = model.serviceSpeedPricing;
|
||||
if (!pricing || pricing.speed === speed) return model;
|
||||
const pricing = model.serviceSpeedPricing ?? {
|
||||
speed: 'standard',
|
||||
standardCosts: model.costs,
|
||||
standardOverrides: model.pricingOverrides,
|
||||
fastCosts: serviceSpeedCosts(model, 'fast'),
|
||||
ultrafastCosts: serviceSpeedCosts(model, 'ultrafast'),
|
||||
};
|
||||
if (pricing.speed === speed) return model;
|
||||
const costs =
|
||||
speed === 'fast'
|
||||
? (pricing.fastCosts ?? pricing.standardCosts)
|
||||
: pricing.standardCosts;
|
||||
(speed === 'ultrafast' ? pricing.ultrafastCosts : undefined) ??
|
||||
(speed !== 'standard' ? pricing.fastCosts : undefined) ??
|
||||
pricing.standardCosts;
|
||||
return {
|
||||
...model,
|
||||
costs,
|
||||
|
||||
@@ -190,6 +190,39 @@ describe('VoiceChangerDriver.convert argument validation', () => {
|
||||
withActor(actor, () => driver.convert({ audio: undefined })),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an unpriced', 'eleven_multilingual_sts_v1'],
|
||||
['a malformed', 'eleven_english_sts_v2&x=1'],
|
||||
])(
|
||||
'rejects %s model before loading audio or calling ElevenLabs',
|
||||
async (_label, model) => {
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
withActor(actor, () =>
|
||||
driver.convert({
|
||||
audio: 'https://audio.example/sample.wav',
|
||||
model,
|
||||
}),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
legacyCode: 'field_invalid',
|
||||
fields: {
|
||||
key: 'model',
|
||||
expected: [
|
||||
'eleven_multilingual_sts_v2',
|
||||
'eleven_english_sts_v2',
|
||||
],
|
||||
got: model,
|
||||
},
|
||||
});
|
||||
expect(webFetchMock).not.toHaveBeenCalled();
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(admitSpy).not.toHaveBeenCalled();
|
||||
expect(incrementUsageSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// ── Credit gate ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -51,6 +51,10 @@ const MAX_AUDIO_FILE_SIZE = 25 * 1024 * 1024;
|
||||
// Covers the upload as well as the conversion.
|
||||
const CONVERT_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
const SUPPORTED_MODELS = Object.keys(VOICE_CHANGER_COSTS).map(
|
||||
(key) => key.split(':')[1]!,
|
||||
);
|
||||
|
||||
const VOICE_CHANGER_CATALOG: ProviderCatalog = {
|
||||
label: 'Speech-to-speech',
|
||||
ids: ['elevenlabs'],
|
||||
@@ -165,14 +169,6 @@ export class VoiceChangerDriver extends PuterDriver {
|
||||
});
|
||||
}
|
||||
|
||||
const loaded = await loadFileInput(
|
||||
this.stores,
|
||||
this.services.fs,
|
||||
actor,
|
||||
args.audio,
|
||||
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
|
||||
);
|
||||
|
||||
const modelId =
|
||||
args.model_id || args.model || elevenlabs.defaultModelId;
|
||||
const voiceId =
|
||||
@@ -184,21 +180,41 @@ export class VoiceChangerDriver extends PuterDriver {
|
||||
throw new HttpError(400, '`voice` is required', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
// `voiceId` lands in the request URL path; `modelId` lands in a
|
||||
// multipart field. Both are forwarded to ElevenLabs with our
|
||||
// long-lived API key, so anything other than a strict alphanumeric
|
||||
// shape lets a caller steer the request at a different endpoint or
|
||||
// inject parameters. ElevenLabs voice/model IDs are always
|
||||
// `[A-Za-z0-9_-]+` in practice.
|
||||
const ID_REGEX = /^[A-Za-z0-9_-]+$/;
|
||||
if (!ID_REGEX.test(voiceId))
|
||||
// `voiceId` lands in the request URL path, which carries our API key,
|
||||
// so anything outside ElevenLabs' `[A-Za-z0-9_-]+` id shape could
|
||||
// steer the request at a different endpoint.
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(voiceId))
|
||||
throw new HttpError(400, '`voice` must be alphanumeric', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
if (!ID_REGEX.test(modelId))
|
||||
throw new HttpError(400, '`model` must be alphanumeric', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
|
||||
// Gate on the cost table: an id we can't price is one we can't bill
|
||||
// for, and ElevenLabs bills us for it either way. This also keeps
|
||||
// anything but a known id out of the multipart `model_id` field.
|
||||
const usageKey = `elevenlabs:${modelId}:second`;
|
||||
if (!Object.hasOwn(VOICE_CHANGER_COSTS, usageKey)) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
`Invalid model: ${modelId}. Expected: ${SUPPORTED_MODELS.join(', ')}`,
|
||||
{
|
||||
legacyCode: 'field_invalid',
|
||||
fields: {
|
||||
key: 'model',
|
||||
expected: SUPPORTED_MODELS,
|
||||
got: modelId,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey]!;
|
||||
|
||||
const loaded = await loadFileInput(
|
||||
this.stores,
|
||||
this.services.fs,
|
||||
actor,
|
||||
args.audio,
|
||||
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
|
||||
);
|
||||
|
||||
// The hold estimates seconds from the input at 128 kbps: compact audio
|
||||
// is under-held rather than refused. Usage is metered from the length
|
||||
@@ -207,8 +223,6 @@ export class VoiceChangerDriver extends PuterDriver {
|
||||
1,
|
||||
Math.ceil(loaded.buffer.byteLength / 16000),
|
||||
);
|
||||
const usageKey = `elevenlabs:${modelId}:second`;
|
||||
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey] ?? 0;
|
||||
const estimatedCost = ucentsPerSecond * estimatedSeconds;
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
postGeminiJson,
|
||||
geminiTokenCount as tokenCount,
|
||||
} from '../../../util/geminiRest.js';
|
||||
import { decodeStrictBase64 } from '../../../../util/mediaSniff.js';
|
||||
import { decodeStrictBase64InSlices } from '../../../../util/mediaSniff.js';
|
||||
import { isUpstreamTimeoutError } from '../../../util/upstreamErrors.js';
|
||||
import { SAMPLE_AUDIO_URL } from '../../../util/testMode.js';
|
||||
import type {
|
||||
@@ -456,7 +456,8 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
},
|
||||
);
|
||||
}
|
||||
const { body, contentType } = this.#decodeAudio(audio);
|
||||
const { body, contentType } =
|
||||
await this.#decodeAudio(audio);
|
||||
|
||||
outputTokens = usageTokens(
|
||||
usage?.output_tokens_by_modality,
|
||||
@@ -474,7 +475,7 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
dataType: 'stream',
|
||||
content_type: contentType,
|
||||
chunked: true,
|
||||
stream: Readable.from(body),
|
||||
stream: Readable.from(body, { objectMode: false }),
|
||||
};
|
||||
} finally {
|
||||
// Every outcome pays once for the counts it reports.
|
||||
@@ -519,13 +520,15 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
}
|
||||
|
||||
/** WAV passes through byte for byte; raw PCM is wrapped in a WAV header. */
|
||||
#decodeAudio(audio: InteractionContent): {
|
||||
body: Buffer;
|
||||
async #decodeAudio(audio: InteractionContent): Promise<{
|
||||
body: Buffer[];
|
||||
contentType: string;
|
||||
} {
|
||||
}> {
|
||||
const { data, mime_type: mimeType } = audio;
|
||||
const bytes =
|
||||
typeof data === 'string' ? decodeStrictBase64(data) : null;
|
||||
typeof data === 'string'
|
||||
? await decodeStrictBase64InSlices(data)
|
||||
: null;
|
||||
if (!bytes || typeof mimeType !== 'string') {
|
||||
throw upstreamFailure('Gemini TTS returned invalid audio data');
|
||||
}
|
||||
@@ -541,7 +544,7 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
) {
|
||||
throw upstreamFailure('Gemini TTS returned invalid audio data');
|
||||
}
|
||||
return { body: bytes, contentType: 'audio/wav' };
|
||||
return { body: [bytes], contentType: 'audio/wav' };
|
||||
}
|
||||
if (PCM_MIME_TYPES.has(essence) && bytes.length > 0) {
|
||||
const rate = Number(
|
||||
@@ -551,8 +554,9 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
Number.isSafeInteger(rate) && rate > 0
|
||||
? rate
|
||||
: DEFAULT_PCM_SAMPLE_RATE;
|
||||
// Sent ahead of the samples, which are never copied behind it.
|
||||
return {
|
||||
body: this.#wrapPcmInWav(bytes, sampleRate, 1, 16),
|
||||
body: [this.#wavHeader(bytes.length, sampleRate, 1, 16), bytes],
|
||||
contentType: 'audio/wav',
|
||||
};
|
||||
}
|
||||
@@ -560,17 +564,15 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
}
|
||||
|
||||
/** Wrap raw PCM samples in a WAV container so browsers can play it. */
|
||||
#wrapPcmInWav(
|
||||
pcm: Buffer,
|
||||
#wavHeader(
|
||||
dataSize: number,
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
bitsPerSample: number,
|
||||
): Buffer {
|
||||
const byteRate = (sampleRate * channels * bitsPerSample) / 8;
|
||||
const blockAlign = (channels * bitsPerSample) / 8;
|
||||
const dataSize = pcm.length;
|
||||
const headerSize = 44;
|
||||
const buffer = Buffer.alloc(headerSize + dataSize);
|
||||
const buffer = Buffer.alloc(44);
|
||||
|
||||
// RIFF header
|
||||
buffer.write('RIFF', 0);
|
||||
@@ -590,7 +592,6 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
// data sub-chunk
|
||||
buffer.write('data', 36);
|
||||
buffer.writeUInt32LE(dataSize, 40);
|
||||
pcm.copy(buffer, headerSize);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import { insufficientCreditsError } from '../../../../services/metering/enforcem
|
||||
import type { UsageInput } from '../../../../services/metering/types.js';
|
||||
import { normalizeRawBase64ImageString } from '../../../../util/appIcon.js';
|
||||
import {
|
||||
decodeStrictBase64,
|
||||
decodeStrictBase64InSlices,
|
||||
sniffImageMime,
|
||||
sniffVideoMime,
|
||||
} from '../../../../util/mediaSniff.js';
|
||||
@@ -405,7 +405,7 @@ export class GeminiVideoProvider extends VideoProvider {
|
||||
'Gemini video generation did not complete the request',
|
||||
);
|
||||
}
|
||||
const video = this.#readVideo(videoBlock);
|
||||
const video = await this.#readVideo(videoBlock);
|
||||
if (!billed) {
|
||||
throw geminiUpstreamFailure(
|
||||
'Gemini video generation returned unusable usage',
|
||||
@@ -722,7 +722,7 @@ export class GeminiVideoProvider extends VideoProvider {
|
||||
}
|
||||
|
||||
/** The base64 MP4 held by the video block. */
|
||||
#readVideo(video: InteractionContent | undefined): string {
|
||||
async #readVideo(video: InteractionContent | undefined): Promise<string> {
|
||||
if (!video) {
|
||||
throw new HttpError(400, 'Gemini did not return a video', {
|
||||
legacyCode: 'upstream_bad_request',
|
||||
@@ -731,7 +731,7 @@ export class GeminiVideoProvider extends VideoProvider {
|
||||
}
|
||||
const bytes =
|
||||
video.mime_type === 'video/mp4' && typeof video.data === 'string'
|
||||
? decodeStrictBase64(video.data)
|
||||
? await decodeStrictBase64InSlices(video.data)
|
||||
: null;
|
||||
if (!bytes || sniffVideoMime(bytes) !== 'video/mp4') {
|
||||
throw geminiUpstreamFailure(
|
||||
|
||||
@@ -330,14 +330,11 @@ export class AppDriver extends PuterDriver {
|
||||
}
|
||||
|
||||
/**
|
||||
* Paged app listing. Unlike `/query/app`, which answers only for apps named
|
||||
* by the caller and so must not confirm ones it may not see, this is the
|
||||
* listing surface a launcher reads: `protected` apps are filtered by the
|
||||
* permission check below, and everything else is listable by design. Narrow
|
||||
* it with `predicate: ['user-can-edit']` to the caller's own.
|
||||
* Paged listing of the caller's own apps. Apps owned by anyone else are
|
||||
* reachable only by name or uid, through `read` and `/query/app`.
|
||||
*/
|
||||
async select(args = {}) {
|
||||
const { predicate, params = {} } = args;
|
||||
const { params = {} } = args;
|
||||
const actor = requireContextActor();
|
||||
this.#requireUserOrAppActor(actor);
|
||||
|
||||
@@ -353,16 +350,12 @@ export class AppDriver extends PuterDriver {
|
||||
const includeTotal = args.includeTotal === true;
|
||||
const paginated = hasCursor || offset !== undefined || includeTotal;
|
||||
|
||||
const filters = {};
|
||||
// predicate: ['user-can-edit'] → scope to owner
|
||||
const ownerScoped =
|
||||
Array.isArray(predicate) && predicate[0] === 'user-can-edit';
|
||||
if (ownerScoped) {
|
||||
filters.ownerUserId = actor.user.id;
|
||||
}
|
||||
// Always the caller's own. `predicate: ['user-can-edit']` asks for the
|
||||
// same thing and is accepted for older clients.
|
||||
const ownerUserId = actor.user.id;
|
||||
|
||||
let apps = await this.appStore.list({
|
||||
...filters,
|
||||
ownerUserId,
|
||||
limit: paginated ? limit + 1 : limit,
|
||||
offset,
|
||||
afterId: payload?.id !== undefined ? Number(payload.id) : undefined,
|
||||
@@ -371,23 +364,18 @@ export class AppDriver extends PuterDriver {
|
||||
let cursor;
|
||||
if (paginated && apps.length > limit) {
|
||||
apps = apps.slice(0, limit);
|
||||
// The cursor tracks the last fetched row, not the last visible
|
||||
// one, so rows hidden by the permission filter below aren't
|
||||
// re-scanned on the next page.
|
||||
cursor = sealCursor(
|
||||
{ id: Number(apps[apps.length - 1].id) },
|
||||
this.config.jwt_secret_v2,
|
||||
);
|
||||
}
|
||||
|
||||
// Protected apps are filtered by one batched grant check; stats and
|
||||
// the shared views are each one batched lookup across the page.
|
||||
const visible = await this.services.app.filterReadable(apps, actor);
|
||||
// Stats and the shared views are each one batched lookup per page.
|
||||
const [statsByUid, views] = await Promise.all([
|
||||
this.appStore.getAppsStats(visible.map((a) => a.uid)),
|
||||
this.services.app.views(visible, actor),
|
||||
this.appStore.getAppsStats(apps.map((a) => a.uid)),
|
||||
this.services.app.views(apps, actor),
|
||||
]);
|
||||
const items = visible.map((app, i) =>
|
||||
const items = apps.map((app, i) =>
|
||||
toAppReadView(app, views[i], {
|
||||
viewer: actor.user,
|
||||
stats: statsByUid.get(app.uid),
|
||||
@@ -396,14 +384,9 @@ export class AppDriver extends PuterDriver {
|
||||
);
|
||||
if (!paginated) return items;
|
||||
|
||||
let total;
|
||||
if (includeTotal) {
|
||||
total = ownerScoped
|
||||
? await this.appStore.count({ ownerUserId: actor.user.id })
|
||||
: await this.appStore.count({
|
||||
visibleToUserId: actor.user?.id ?? null,
|
||||
});
|
||||
}
|
||||
const total = includeTotal
|
||||
? await this.appStore.count({ ownerUserId })
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
items,
|
||||
|
||||
@@ -509,7 +509,7 @@ describe('AppDriver.read', () => {
|
||||
// ── select ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('AppDriver.select', () => {
|
||||
it('returns visible apps including those owned by other users', async () => {
|
||||
it("returns only the caller's apps when no predicate is sent", async () => {
|
||||
const a = await makeUser();
|
||||
const b = await makeUser();
|
||||
const aName = uniqueName('a');
|
||||
@@ -538,7 +538,7 @@ describe('AppDriver.select', () => {
|
||||
)) as Array<Record<string, unknown>>;
|
||||
const names = result.map((r) => r.name);
|
||||
expect(names).toContain(aName);
|
||||
expect(names).toContain(bName);
|
||||
expect(names).not.toContain(bName);
|
||||
});
|
||||
|
||||
it('predicate `user-can-edit` filters to actor-owned apps only', async () => {
|
||||
@@ -1670,11 +1670,10 @@ describe('AppDriver.select pagination', () => {
|
||||
expect(page.total).toBe(names.length);
|
||||
});
|
||||
|
||||
it("hides other users' protected apps from paginated catalog listings", async () => {
|
||||
it("pages through only the caller's apps, protected ones included", async () => {
|
||||
const a = await makeApps(3);
|
||||
const [visible1, hidden, visible2] = a.names;
|
||||
const created = await withActor(a.actor, () =>
|
||||
driver.read({ id: { name: hidden } }),
|
||||
driver.read({ id: { name: a.names[1] } }),
|
||||
);
|
||||
const row = await server.stores.app.getByUid(
|
||||
(created as Record<string, unknown>).uid as string,
|
||||
@@ -1685,20 +1684,29 @@ describe('AppDriver.select pagination', () => {
|
||||
);
|
||||
await server.stores.app.invalidateByUid(row!.uid as string);
|
||||
|
||||
const b = await makeUser();
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null | undefined = null;
|
||||
do {
|
||||
const page = (await withActor(b.actor, () =>
|
||||
driver.select({ limit: 50, cursor }),
|
||||
)) as { items: Array<{ name: string }>; cursor?: string };
|
||||
seen.push(...page.items.map((r) => r.name));
|
||||
cursor = page.cursor;
|
||||
} while (cursor);
|
||||
const listAll = async (actor: Actor) => {
|
||||
const seen: string[] = [];
|
||||
let total: number | undefined;
|
||||
let cursor: string | null | undefined = null;
|
||||
do {
|
||||
const page = (await withActor(actor, () =>
|
||||
driver.select({ limit: 2, cursor, includeTotal: true }),
|
||||
)) as {
|
||||
items: Array<{ name: string }>;
|
||||
cursor?: string;
|
||||
total?: number;
|
||||
};
|
||||
seen.push(...page.items.map((r) => r.name));
|
||||
total ??= page.total;
|
||||
cursor = page.cursor;
|
||||
} while (cursor);
|
||||
return { seen, total };
|
||||
};
|
||||
|
||||
expect(seen).toContain(visible1);
|
||||
expect(seen).toContain(visible2);
|
||||
expect(seen).not.toContain(hidden);
|
||||
expect(await listAll(a.actor)).toEqual({ seen: a.names, total: 3 });
|
||||
|
||||
const b = await makeUser();
|
||||
expect(await listAll(b.actor)).toEqual({ seen: [], total: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2517,22 +2525,6 @@ describe('AppDriver.select query-count regression', () => {
|
||||
// -- select / read parity --
|
||||
|
||||
describe('AppDriver.select / read parity', () => {
|
||||
const findViaBroadSelect = async (
|
||||
actor: Actor,
|
||||
uid: string,
|
||||
): Promise<Record<string, unknown> | undefined> => {
|
||||
let cursor: string | null | undefined = null;
|
||||
do {
|
||||
const page = (await withActor(actor, () =>
|
||||
driver.select({ limit: 50, cursor }),
|
||||
)) as { items: Array<Record<string, unknown>>; cursor?: string };
|
||||
const found = page.items.find((r) => r.uid === uid);
|
||||
if (found) return found;
|
||||
cursor = page.cursor;
|
||||
} while (cursor);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
it('every select item (minus stats) deep-equals the corresponding read', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const names: string[] = [];
|
||||
@@ -2640,7 +2632,7 @@ describe('AppDriver.select / read parity', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('dangling hosted app via select: owner keeps index_url, others do not', async () => {
|
||||
it('dangling hosted app: owner keeps index_url in select, others do not in read', async () => {
|
||||
const owner = await makeUser();
|
||||
const other = await makeUser();
|
||||
const sub = uniqueName('qcdangsel');
|
||||
@@ -2672,13 +2664,12 @@ describe('AppDriver.select / read parity', () => {
|
||||
?.reason,
|
||||
).toBe('hosted_backing_unavailable');
|
||||
|
||||
const otherItem = await findViaBroadSelect(
|
||||
other.actor,
|
||||
created.uid as string,
|
||||
);
|
||||
expect(otherItem?.index_url).toBeUndefined();
|
||||
const otherItem = (await withActor(other.actor, () =>
|
||||
driver.read({ uid: created.uid }),
|
||||
)) as Record<string, unknown>;
|
||||
expect(otherItem.index_url).toBeUndefined();
|
||||
expect(
|
||||
(otherItem?.privateAccess as { hasAccess?: boolean } | undefined)
|
||||
(otherItem.privateAccess as { hasAccess?: boolean } | undefined)
|
||||
?.hasAccess,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { HttpError } from '../../core/http/HttpError.js';
|
||||
import { parseJsonInSlices } from '../../util/slicedJson.js';
|
||||
import { readBoundedBody } from './fileInput.js';
|
||||
import { upstreamFetch } from './upstreamErrors.js';
|
||||
|
||||
@@ -39,8 +40,8 @@ export const geminiUpstreamFailure = (message: string): HttpError =>
|
||||
/**
|
||||
* POSTs `body` to a Gemini REST `path` and parses the JSON object it answers
|
||||
* with. `timeoutMs` covers the body read, and a reply over `maxBytes` fails as
|
||||
* an upstream error unless `tooLarge` supplies another. `T` is the documented reply shape; callers check every
|
||||
* field before use.
|
||||
* an upstream error unless `tooLarge` supplies another. `T` is the documented
|
||||
* reply shape; callers check every field before use.
|
||||
*/
|
||||
export async function postGeminiJson<T extends object>(
|
||||
apiKey: string,
|
||||
@@ -87,7 +88,8 @@ export async function postGeminiJson<T extends object>(
|
||||
const raw = await readBoundedBody(response, maxBytes, tooLarge);
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(raw.toString('utf8'));
|
||||
// Media replies run to tens of megabytes of base64.
|
||||
parsed = await parseJsonInSlices(raw);
|
||||
} catch {
|
||||
// Handled with the non-object case below.
|
||||
}
|
||||
|
||||
@@ -414,7 +414,9 @@ describe('PuterServer host header validation', () => {
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
])('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) =>
|
||||
@@ -447,7 +449,7 @@ describe('PuterServer host header validation', () => {
|
||||
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'])(
|
||||
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Top-Up', '/embed/top-up/', '/embed/Request-Email-Confirmation'])(
|
||||
'lets a first-party page frame only the exact spelling of %s',
|
||||
async (spelling) => {
|
||||
const res = await request(spelling, {
|
||||
@@ -792,6 +794,26 @@ describe('PuterServer request parsing', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('parses a chat call above 50 MiB whose body opens with its token', async () => {
|
||||
const fields = `"interface":"puter-chat-completion","method":"no-such-method","pad":"${'x'.repeat(51 * MiB)}"`;
|
||||
const asText = { 'content-type': 'text/plain;actually=json' };
|
||||
const first = await postJson(
|
||||
'/drivers/call',
|
||||
`{"auth_token":"${token}",${fields}}`,
|
||||
asText,
|
||||
);
|
||||
expect(first.status).toBe(404);
|
||||
expect(first.body).toContain('no-such-method');
|
||||
|
||||
// A token after other fields can't be read ahead of the body.
|
||||
const last = await postJson(
|
||||
'/drivers/call',
|
||||
`{${fields},"auth_token":"${token}"}`,
|
||||
asText,
|
||||
);
|
||||
expect(last.status).toBe(413);
|
||||
});
|
||||
|
||||
it('keeps the default JSON limit for other drivers', async () => {
|
||||
const payload = JSON.stringify({
|
||||
interface: 'puter-kvstore',
|
||||
|
||||
+30
-11
@@ -36,6 +36,7 @@ import { createAuthProbe } from './core/http/middleware/authProbe';
|
||||
import { createRequestContextMiddleware } from './core/http/middleware/requestContext';
|
||||
import { createFingerprintMiddleware } from './core/http/middleware/fingerprint';
|
||||
import { createErrorHandler } from './core/http/middleware/errorHandler';
|
||||
import { createJsonBodyParser } from './core/http/middleware/jsonBody';
|
||||
import {
|
||||
createLargeJsonBodyParser,
|
||||
DEFAULT_JSON_LIMIT_BYTES,
|
||||
@@ -144,6 +145,8 @@ const LARGE_JSON_ROUTES = [
|
||||
const LARGE_JSON_LIMIT_BYTES = 128 * 1024 * 1024;
|
||||
/** Two max-size bodies per process. */
|
||||
const LARGE_JSON_BUDGET_BYTES = 2 * LARGE_JSON_LIMIT_BYTES;
|
||||
/** These parse in one go, so they stay small enough for that to be quick. */
|
||||
const NON_UTF8_JSON_LIMIT_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Through `/drivers/call`, only chat takes a large body; other drivers keep the
|
||||
@@ -575,26 +578,42 @@ export class PuterServer {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A WebDAV body is the file being stored, whatever content type the
|
||||
// client labels it with, so the controller reads it off the stream.
|
||||
const exceptDav =
|
||||
(parser: RequestHandler): RequestHandler =>
|
||||
(req, res, next) => {
|
||||
if (activeSubdomain(req) === 'dav') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
return parser(req, res, next);
|
||||
};
|
||||
this.#app.use(
|
||||
express.json({
|
||||
limit: DEFAULT_JSON_LIMIT_BYTES,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
exceptDav(
|
||||
createJsonBodyParser({
|
||||
limit: DEFAULT_JSON_LIMIT_BYTES,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// JSON in another charset, which the parser above leaves alone.
|
||||
this.#app.use(
|
||||
express.json({
|
||||
limit: DEFAULT_JSON_LIMIT_BYTES,
|
||||
type: (req) =>
|
||||
req.headers['content-type'] === 'text/plain;actually=json',
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
exceptDav(
|
||||
express.json({
|
||||
limit: NON_UTF8_JSON_LIMIT_BYTES,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// Form-encoded bodies (e.g. `/down` from the GUI's iframe-triggered
|
||||
// download form). Needs to run before the auth probe so
|
||||
// `req.body.auth_token` is populated for urlencoded POSTs the same
|
||||
// way it is for JSON POSTs. Small cap — this parser is only here to
|
||||
// cover the auth_token / anti_csrf field shape, not file uploads.
|
||||
this.#app.use(express.urlencoded({ extended: true, limit: '100kb' }));
|
||||
this.#app.use(
|
||||
exceptDav(express.urlencoded({ extended: true, limit: '100kb' })),
|
||||
);
|
||||
|
||||
// -- Auth probe ----------------------------------------------
|
||||
if (authProbe) {
|
||||
|
||||
@@ -31,24 +31,13 @@ export const RECOMMENDED_APP_NAMES = [
|
||||
'spreadsheet',
|
||||
'presentation',
|
||||
'whiteboard',
|
||||
'notes',
|
||||
'pdf-editor',
|
||||
'contacts',
|
||||
'calendar',
|
||||
'meetings',
|
||||
'teamchat',
|
||||
'email',
|
||||
'dev-center',
|
||||
'cap-table',
|
||||
'invoices',
|
||||
'crm',
|
||||
'signatures',
|
||||
'projects',
|
||||
'point-of-sale',
|
||||
'inventory',
|
||||
'hiring',
|
||||
'time-tracking',
|
||||
'shift-planner',
|
||||
'equipment',
|
||||
'chess',
|
||||
'checkers',
|
||||
'backgammon',
|
||||
|
||||
@@ -2864,7 +2864,7 @@ export class AuthService extends PuterService {
|
||||
|
||||
#actorUserFromRow(user: UserRow) {
|
||||
// Strip the password hash; pass everything else through so callers
|
||||
// can read metadata, desktop_bg_*, otp_enabled, etc. without
|
||||
// can read metadata, otp_enabled, etc. without
|
||||
// re-fetching the user. Mirrors what /whoami exposes off of UserRow.
|
||||
const { password: _password, ...rest } = user;
|
||||
return {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isTokenForAnotherUser } from '../../../gui/src/helpers/tokenUser.js';
|
||||
import { TokenService } from './TokenService.js';
|
||||
|
||||
const V2_SECRET = 'test-v2-secret';
|
||||
@@ -384,3 +385,21 @@ describe('TokenService payload key handling', () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('session token read by the desktop', () => {
|
||||
// The desktop reads the user out of a token another tab stored, to tell
|
||||
// an account switch from a renewed token for the same account.
|
||||
it('names its user in the form the desktop decodes', () => {
|
||||
const svc = createTokenService();
|
||||
const userUid = '5d4adce0-a381-4982-9c02-6e2540026238';
|
||||
const otherUid = 'a1b2c3d4-0000-4000-8000-00000000beef';
|
||||
const token = svc.sign('auth', {
|
||||
type: 'gui',
|
||||
version: '2',
|
||||
user_uid: userUid,
|
||||
});
|
||||
|
||||
expect(isTokenForAnotherUser(token, { uuid: userUid })).toBe(false);
|
||||
expect(isTokenForAnotherUser(token, { uuid: otherUid })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,7 @@ export type TokenType = 'session' | 'gui' | 'app-under-user' | 'access-token';
|
||||
|
||||
/**
|
||||
* Browser session token. `'session'` is the HTTP-only-cookie flavor, `'gui'`
|
||||
* the same shape served in a response body (e.g. QR login).
|
||||
* the same shape served in a response body (e.g. the login response).
|
||||
*/
|
||||
export interface SessionTokenPayload extends TokenPayloadBase {
|
||||
type: 'session' | 'gui';
|
||||
@@ -109,9 +109,7 @@ export interface AccessTokenPayload extends TokenPayloadBase {
|
||||
}
|
||||
|
||||
export type AnyTokenPayload =
|
||||
| SessionTokenPayload
|
||||
| AppUnderUserTokenPayload
|
||||
| AccessTokenPayload;
|
||||
SessionTokenPayload | AppUnderUserTokenPayload | AccessTokenPayload;
|
||||
|
||||
// -- Session row (from `sessions` table) ----------------------------
|
||||
|
||||
|
||||
@@ -647,6 +647,22 @@ describe('FSService overwrite and dedupe resolution', () => {
|
||||
expect(await readBack(second)).toBe('second');
|
||||
});
|
||||
|
||||
it('leaves one readable file when two overwrites create the same path at once', async () => {
|
||||
const path = `${user.home}/Documents/raced.txt`;
|
||||
const written = await Promise.all([
|
||||
writeFile(user, path, 'short', { overwrite: true }),
|
||||
writeFile(user, path, 'a much longer body', { overwrite: true }),
|
||||
]);
|
||||
|
||||
// Both started before the row existed, so each uploaded under its own
|
||||
// key; the row has to end up describing bytes that are really there.
|
||||
expect(written[0].uuid).toBe(written[1].uuid);
|
||||
const stored = (await entryAt(user, '/Documents/raced.txt'))!;
|
||||
const body = await readBack(stored);
|
||||
expect(['short', 'a much longer body']).toContain(body);
|
||||
expect(stored.size).toBe(Buffer.byteLength(body));
|
||||
});
|
||||
|
||||
it('dedupes into an unused " (n)" name, skipping names already taken', async () => {
|
||||
await writeFile(user, `${user.home}/Documents/d.txt`, 'a');
|
||||
await writeFile(user, `${user.home}/Documents/d (1).txt`, 'a');
|
||||
|
||||
@@ -2073,10 +2073,7 @@ export class FSService extends PuterService {
|
||||
);
|
||||
});
|
||||
|
||||
const fsEntries = await this.stores.fsEntry.batchCreateEntries(
|
||||
createInputs,
|
||||
true,
|
||||
);
|
||||
const fsEntries = await this.#createUploadedEntries(createInputs);
|
||||
return preparedBatch.items.map((item, index) => {
|
||||
const fsEntry = fsEntries[index];
|
||||
if (!fsEntry) {
|
||||
@@ -3001,30 +2998,97 @@ export class FSService extends PuterService {
|
||||
legacyCode: 'conflict',
|
||||
});
|
||||
}
|
||||
await this.#moveObjectOntoKey(
|
||||
session.objectKey,
|
||||
liveKey,
|
||||
{ bucket, region, size },
|
||||
session.contentType,
|
||||
);
|
||||
}
|
||||
|
||||
async #moveObjectOntoKey(
|
||||
fromKey: string,
|
||||
toKey: string,
|
||||
at: { bucket: string; region: string; size: number },
|
||||
contentType?: string | null,
|
||||
): Promise<void> {
|
||||
await this.stores.s3Object.copyObjectOfAnySize(
|
||||
{
|
||||
sourceBucket: bucket,
|
||||
sourceKey: session.objectKey,
|
||||
destinationBucket: bucket,
|
||||
destinationKey: liveKey,
|
||||
contentType: session.contentType,
|
||||
sourceBucket: at.bucket,
|
||||
sourceKey: fromKey,
|
||||
destinationBucket: at.bucket,
|
||||
destinationKey: toKey,
|
||||
...(contentType ? { contentType } : {}),
|
||||
metadataDirective: 'REPLACE',
|
||||
},
|
||||
region,
|
||||
size,
|
||||
at.region,
|
||||
at.size,
|
||||
);
|
||||
try {
|
||||
await this.stores.s3Object.deleteObject(
|
||||
bucket,
|
||||
session.objectKey,
|
||||
region,
|
||||
at.bucket,
|
||||
fromKey,
|
||||
at.region,
|
||||
);
|
||||
} catch (e) {
|
||||
// The live object is already right; the staged one is only litter.
|
||||
console.warn('[fs] staged overwrite left behind:', e);
|
||||
// The destination is already right; the source is only litter.
|
||||
console.warn('[fs] moved object left behind:', e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the rows for objects already uploaded. A row another writer
|
||||
* created first keeps its uuid, so those bytes move onto that key.
|
||||
*/
|
||||
async #createUploadedEntries(
|
||||
inputs: FSEntryCreateInput[],
|
||||
): Promise<FSEntry[]> {
|
||||
const entries = await this.stores.fsEntry.batchCreateEntries(
|
||||
inputs,
|
||||
true,
|
||||
);
|
||||
const raced = inputs.flatMap((input, index) => {
|
||||
const liveKey = entries[index]?.uuid;
|
||||
return liveKey && liveKey !== input.uuid
|
||||
? [{ input, index, liveKey }]
|
||||
: [];
|
||||
});
|
||||
if (raced.length === 0) return entries;
|
||||
|
||||
await Promise.all(
|
||||
raced.map(({ input, liveKey }) =>
|
||||
this.#moveObjectOntoKey(
|
||||
input.uuid,
|
||||
liveKey,
|
||||
{
|
||||
bucket: this.stores.s3Object.resolveBucket(
|
||||
input.bucket,
|
||||
),
|
||||
region: this.stores.s3Object.resolveRegion(
|
||||
input.bucketRegion,
|
||||
),
|
||||
size: input.size,
|
||||
},
|
||||
input.contentType,
|
||||
),
|
||||
),
|
||||
);
|
||||
const adopted = await this.stores.fsEntry.batchCreateEntries(
|
||||
raced.map(({ input, liveKey }) => ({ ...input, uuid: liveKey })),
|
||||
true,
|
||||
);
|
||||
raced.forEach(({ index, liveKey }, i) => {
|
||||
const entry = adopted[i];
|
||||
if (entry?.uuid !== liveKey) {
|
||||
throw new HttpError(409, 'Write target changed mid-write', {
|
||||
legacyCode: 'conflict',
|
||||
});
|
||||
}
|
||||
entries[index] = entry;
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
async completeUrlWrite(
|
||||
userId: number,
|
||||
completeWriteRequest: CompleteWriteRequest,
|
||||
@@ -3581,10 +3645,10 @@ export class FSService extends PuterService {
|
||||
: uploadBody.contentHashSha256;
|
||||
|
||||
const createInput = this.#toCreateInput(normalizedInput, objectKey);
|
||||
const fsEntry = await this.stores.fsEntry.createEntry(
|
||||
createInput,
|
||||
normalizedInput.createMissingParents,
|
||||
);
|
||||
const [fsEntry] = await this.#createUploadedEntries([createInput]);
|
||||
if (!fsEntry) {
|
||||
throw new Error('Failed to create entry');
|
||||
}
|
||||
|
||||
this.#emitFsEvent(
|
||||
existingEntry ? 'fs.write.file' : 'fs.create.file',
|
||||
@@ -3682,17 +3746,18 @@ export class FSService extends PuterService {
|
||||
updates.filter(isValid),
|
||||
);
|
||||
let next = 0;
|
||||
return updates.map((update): PromiseSettledResult<FSEntry> =>
|
||||
isValid(update)
|
||||
? stored[next++]
|
||||
: {
|
||||
status: 'rejected',
|
||||
reason: new HttpError(
|
||||
400,
|
||||
'Invalid file entry identifier for thumbnail update',
|
||||
{ legacyCode: 'bad_request' },
|
||||
),
|
||||
},
|
||||
return updates.map(
|
||||
(update): PromiseSettledResult<FSEntry> =>
|
||||
isValid(update)
|
||||
? stored[next++]
|
||||
: {
|
||||
status: 'rejected',
|
||||
reason: new HttpError(
|
||||
400,
|
||||
'Invalid file entry identifier for thumbnail update',
|
||||
{ legacyCode: 'bad_request' },
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -517,8 +517,6 @@ export class PuterHomepageService extends PuterService {
|
||||
<meta name="theme-color" content="#ffffff">
|
||||
${bundled ? `<link rel="stylesheet" href="${guiCss}">` : ''}
|
||||
|
||||
<link rel="preload" as="image" href="https://puter-assets.b-cdn.net/wallpaper.webp">
|
||||
|
||||
<script>
|
||||
if ( ! window.service_script ) {
|
||||
window.service_script_api_promise = (() => {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { Writable } from 'node:stream';
|
||||
import v8 from 'node:v8';
|
||||
import type { Request, Response } from 'express';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
@@ -229,6 +230,37 @@ describe('ProfileService', () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
// V8 stops optimizing regexps once a process holds enough compiled code,
|
||||
// as long-running servers do, and an unoptimized one overflows on this.
|
||||
it('answers a picture of several megabytes with 413', () => {
|
||||
const picture = `data:image/png;base64,${'A'.repeat(6 * 1024 * 1024)}`;
|
||||
v8.setFlagsFromString('--no-regexp-optimization');
|
||||
try {
|
||||
expect(() => service.validatePatch({ picture })).toThrow(
|
||||
expect.objectContaining({
|
||||
statusCode: 413,
|
||||
code: 'profile_picture_too_large',
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
v8.setFlagsFromString('--regexp-optimization');
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts a picture of the largest size, with or without padding', () => {
|
||||
const prefix = 'data:image/png;base64,';
|
||||
const full = `${prefix}${'A'.repeat(PROFILE_PICTURE_MAX_BYTES - prefix.length)}`;
|
||||
expect(service.validatePatch({ picture: full })).toEqual({
|
||||
picture: full,
|
||||
});
|
||||
expect(service.validatePatch({ picture: `${prefix}QQ` })).toEqual({
|
||||
picture: `${prefix}QQ`,
|
||||
});
|
||||
expect(() => service.validatePatch({ picture: `${full}A` })).toThrow(
|
||||
expect.objectContaining({ code: 'profile_picture_too_large' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps what validates from a legacy profile and names the rest', () => {
|
||||
expect(
|
||||
service.normalizeLegacyProfile({
|
||||
|
||||
@@ -83,6 +83,14 @@ const validateField = (field: ProfileField, value: unknown): string | null => {
|
||||
);
|
||||
}
|
||||
if (field === 'picture') {
|
||||
// Sized before the pattern runs, which fails outright on megabytes of
|
||||
// text. Only ASCII passes the pattern, so the length is the byte count.
|
||||
if (value.length > PROFILE_PICTURE_MAX_BYTES) {
|
||||
throw new HttpError(413, 'picture is too large', {
|
||||
code: 'profile_picture_too_large',
|
||||
fields: { field, maxBytes: PROFILE_PICTURE_MAX_BYTES },
|
||||
});
|
||||
}
|
||||
if (!PICTURE_DATA_URL.test(value)) {
|
||||
throw invalid(
|
||||
field,
|
||||
@@ -90,12 +98,6 @@ const validateField = (field: ProfileField, value: unknown): string | null => {
|
||||
'profile_picture_invalid',
|
||||
);
|
||||
}
|
||||
if (Buffer.byteLength(value) > PROFILE_PICTURE_MAX_BYTES) {
|
||||
throw new HttpError(413, 'picture is too large', {
|
||||
code: 'profile_picture_too_large',
|
||||
fields: { field, maxBytes: PROFILE_PICTURE_MAX_BYTES },
|
||||
});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const maxLength =
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
PuterStore,
|
||||
} from '../types';
|
||||
import { HttpError } from '../../core/http/HttpError.js';
|
||||
import { runWithConcurrencyLimit } from '../../util/concurrency.js';
|
||||
import { isUniqueViolation } from '../../util/dbError.js';
|
||||
import {
|
||||
validateUrl,
|
||||
@@ -89,6 +90,8 @@ const STATS_CACHE_TTL_SECONDS = 30 * 60;
|
||||
// `app-` + a UUID. ClickHouse's `app_opens.app_uid` is FixedString(40) and
|
||||
// fails the whole query on a longer value.
|
||||
const APP_UID_MAX_BYTES = 40;
|
||||
// ClickHouse caps the size of one query parameter, and the uid list is one.
|
||||
const CLICKHOUSE_UIDS_PER_QUERY = 1000;
|
||||
|
||||
// Period helpers for detailed/grouped stats. Ported from v1
|
||||
// AppInformationService — queries go straight to ClickHouse/MySQL on demand
|
||||
@@ -686,12 +689,7 @@ export class AppStore extends PuterStore {
|
||||
return apps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count apps matching the same equality filters as `list`.
|
||||
* `visibleToUserId` counts the public catalog for one caller —
|
||||
* non-protected apps plus their own; apps visible only via explicit
|
||||
* permission grants are not included.
|
||||
*/
|
||||
/** Count apps matching the same equality filters as `list`. */
|
||||
async count(filters = {}) {
|
||||
const where = [];
|
||||
const params = [];
|
||||
@@ -704,12 +702,6 @@ export class AppStore extends PuterStore {
|
||||
where.push('`app_owner` = ?');
|
||||
params.push(filters.appOwner);
|
||||
}
|
||||
if (filters.visibleToUserId !== undefined) {
|
||||
where.push(
|
||||
'(`protected` IS NULL OR `protected` = false OR `owner_user_id` = ?)',
|
||||
);
|
||||
params.push(filters.visibleToUserId);
|
||||
}
|
||||
|
||||
const whereClause = where.length ? `WHERE ${where.join(' AND ')}` : '';
|
||||
const rows = await this.clients.db.read(
|
||||
@@ -1738,20 +1730,30 @@ export class AppStore extends PuterStore {
|
||||
|
||||
const clickhouse = this.clients.clickhouse;
|
||||
if (clickhouse) {
|
||||
const res = await clickhouse.query({
|
||||
query: `
|
||||
SELECT app_uid,
|
||||
uniqExact((user_id, intDiv(ts, ${APP_OPEN_COUNT_PERIOD_SECONDS}))) AS open_count,
|
||||
count(DISTINCT user_id) AS user_count
|
||||
FROM app_opens
|
||||
WHERE app_uid IN {uids:Array(String)}
|
||||
GROUP BY app_uid
|
||||
`,
|
||||
query_params: { uids: uids.map((u) => String(u)) },
|
||||
format: 'JSONEachRow',
|
||||
});
|
||||
const rows = await res.json();
|
||||
for (const row of rows) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < uids.length; i += CLICKHOUSE_UIDS_PER_QUERY) {
|
||||
chunks.push(uids.slice(i, i + CLICKHOUSE_UIDS_PER_QUERY));
|
||||
}
|
||||
const results = await runWithConcurrencyLimit(
|
||||
chunks,
|
||||
4,
|
||||
async (chunk) => {
|
||||
const res = await clickhouse.query({
|
||||
query: `
|
||||
SELECT app_uid,
|
||||
uniqExact((user_id, intDiv(ts, ${APP_OPEN_COUNT_PERIOD_SECONDS}))) AS open_count,
|
||||
count(DISTINCT user_id) AS user_count
|
||||
FROM app_opens
|
||||
WHERE app_uid IN {uids:Array(String)}
|
||||
GROUP BY app_uid
|
||||
`,
|
||||
query_params: { uids: chunk.map((u) => String(u)) },
|
||||
format: 'JSONEachRow',
|
||||
});
|
||||
return res.json();
|
||||
},
|
||||
);
|
||||
for (const row of results.flat()) {
|
||||
out.set(row.app_uid, {
|
||||
open_count: parseInt(row.open_count, 10) || 0,
|
||||
user_count: parseInt(row.user_count, 10) || 0,
|
||||
|
||||
@@ -200,6 +200,37 @@ describe('AppStore app stats (cache-on-read)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('splits a long uid list across ClickHouse queries', async () => {
|
||||
const uids = Array.from({ length: 2500 }, () => freshUid());
|
||||
const queried = [];
|
||||
|
||||
server.clients.clickhouse = {
|
||||
query: async ({ query_params }) => {
|
||||
queried.push(query_params.uids.length);
|
||||
return {
|
||||
json: async () =>
|
||||
query_params.uids.map((u) => ({
|
||||
app_uid: u,
|
||||
open_count: '2',
|
||||
user_count: '1',
|
||||
})),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const stats = await appStore.getAppsStats(uids);
|
||||
expect(queried.sort((a, b) => b - a)).toEqual([1000, 1000, 500]);
|
||||
expect(stats.size).toBe(2500);
|
||||
expect(stats.get(uids[2499])).toMatchObject({
|
||||
open_count: 2,
|
||||
user_count: 1,
|
||||
});
|
||||
} finally {
|
||||
delete server.clients.clickhouse;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps ids longer than an app uid out of the ClickHouse query', async () => {
|
||||
const uid = freshUid();
|
||||
const longId = `iap-${'a'.repeat(36)}-extra`;
|
||||
@@ -1292,31 +1323,14 @@ describe('AppStore CRUD and cache invalidation', () => {
|
||||
).toBe('Bumped');
|
||||
});
|
||||
|
||||
it('counts apps by owner, creator and per-caller visibility', async () => {
|
||||
it('counts apps by owner and creator', async () => {
|
||||
const countOwner = 4600;
|
||||
const viewer = 4601;
|
||||
const open = await createApp({}, { ownerUserId: countOwner });
|
||||
await createApp({}, { ownerUserId: countOwner, appOwner: open.id });
|
||||
const hidden = await createApp({}, { ownerUserId: countOwner });
|
||||
await db.write('UPDATE `apps` SET `protected` = 1 WHERE `id` = ?', [
|
||||
hidden.id,
|
||||
]);
|
||||
await createApp({}, { ownerUserId: countOwner });
|
||||
|
||||
expect(await appStore.count({ ownerUserId: countOwner })).toBe(3);
|
||||
expect(await appStore.count({ appOwner: open.id })).toBe(1);
|
||||
|
||||
// The protected app is invisible to a stranger but visible to its
|
||||
// owner.
|
||||
const strangerView = await appStore.count({
|
||||
ownerUserId: countOwner,
|
||||
visibleToUserId: viewer,
|
||||
});
|
||||
expect(strangerView).toBe(2);
|
||||
const ownerView = await appStore.count({
|
||||
ownerUserId: countOwner,
|
||||
visibleToUserId: countOwner,
|
||||
});
|
||||
expect(ownerView).toBe(3);
|
||||
});
|
||||
|
||||
// -- filetype association batch + recent opens ----------------------
|
||||
|
||||
@@ -444,7 +444,7 @@ describe('FSEntryStore cache invalidation', () => {
|
||||
store.batchCreateEntries([
|
||||
{
|
||||
userId: user.userId,
|
||||
uuid: uuidv4(),
|
||||
uuid: file.uuid,
|
||||
path: file.path,
|
||||
size: 7,
|
||||
overwrite: true,
|
||||
@@ -1185,7 +1185,7 @@ describe('FSEntryStore entry creation', () => {
|
||||
const [updated] = await store.batchCreateEntries([
|
||||
{
|
||||
userId: user.userId,
|
||||
uuid: uuidv4(),
|
||||
uuid: original.uuid,
|
||||
path: `${user.home}/Documents/ow.txt`,
|
||||
size: 42,
|
||||
overwrite: true,
|
||||
@@ -1204,6 +1204,33 @@ describe('FSEntryStore entry creation', () => {
|
||||
expect(updated?.thumbnail).toBe('data:image/png;base64,AA');
|
||||
});
|
||||
|
||||
it('leaves the row alone when an overwrite brings a different object key', async () => {
|
||||
const user = await makeUser();
|
||||
const original = await createFile(
|
||||
user,
|
||||
`${user.home}/Documents/otherkey.txt`,
|
||||
{ size: 1 },
|
||||
);
|
||||
|
||||
// The bytes for this write sit under a key the row doesn't name, so
|
||||
// repointing bucket or size would describe an object that isn't there.
|
||||
const returned = await createFile(user, original.path, {
|
||||
size: 42,
|
||||
overwrite: true,
|
||||
bucket: 'elsewhere',
|
||||
bucketRegion: 'eu-central-1',
|
||||
});
|
||||
|
||||
expect(returned.uuid).toBe(original.uuid);
|
||||
await expect(
|
||||
store.getEntryByPath(original.path),
|
||||
).resolves.toMatchObject({
|
||||
uuid: original.uuid,
|
||||
size: 1,
|
||||
bucket: 'puter-local',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses to clobber an existing entry without overwrite, or a directory with it', async () => {
|
||||
const user = await makeUser();
|
||||
await createFile(user, `${user.home}/Documents/keep.txt`);
|
||||
@@ -1227,7 +1254,10 @@ describe('FSEntryStore entry creation', () => {
|
||||
|
||||
it('propagates the underlying failure when an overwrite update fails', async () => {
|
||||
const user = await makeUser();
|
||||
await createFile(user, `${user.home}/Documents/upfail.txt`);
|
||||
const existing = await createFile(
|
||||
user,
|
||||
`${user.home}/Documents/upfail.txt`,
|
||||
);
|
||||
|
||||
const db = server.clients.db;
|
||||
const originalWrite = (Object.getPrototypeOf(db) as typeof db).write;
|
||||
@@ -1243,6 +1273,7 @@ describe('FSEntryStore entry creation', () => {
|
||||
await expect(
|
||||
createFile(user, `${user.home}/Documents/upfail.txt`, {
|
||||
overwrite: true,
|
||||
uuid: existing.uuid,
|
||||
}),
|
||||
).rejects.toThrow('update rejected');
|
||||
|
||||
@@ -3801,7 +3832,7 @@ describe('FSEntryStore lost-insert recovery', () => {
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('updates the race winner in place when overwrite was requested', async () => {
|
||||
it('hands back the race winner untouched when overwrite was requested', async () => {
|
||||
const user = await makeUser();
|
||||
const uuid = uuidv4();
|
||||
const spy = loseInsertRace(uuid, () =>
|
||||
@@ -3827,13 +3858,14 @@ describe('FSEntryStore lost-insert recovery', () => {
|
||||
]);
|
||||
spy.mockRestore();
|
||||
|
||||
// The winner's row survived; our payload was written onto it.
|
||||
// Our object is under `uuid`, not the winner's key, so the winner's
|
||||
// row is returned as it stands for the caller to move the bytes onto.
|
||||
expect(entry?.uuid).not.toBe(uuid);
|
||||
expect(entry?.size).toBe(77);
|
||||
expect(entry?.thumbnail).toBe('thumb');
|
||||
expect(entry?.size).not.toBe(77);
|
||||
expect(entry?.thumbnail).not.toBe('thumb');
|
||||
await expect(
|
||||
store.getEntryByPath(`${user.home}/Documents/recovered.txt`),
|
||||
).resolves.toMatchObject({ size: 77, uuid: entry?.uuid });
|
||||
).resolves.toMatchObject({ size: entry?.size, uuid: entry?.uuid });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1941,6 +1941,11 @@ export class FSEntryStore extends PuterStore {
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* An overwrite whose `uuid` is not the existing row's leaves that row
|
||||
* untouched and returns it: the caller's object is under another key, so
|
||||
* the row can't describe it until the caller moves the bytes.
|
||||
*/
|
||||
async batchCreateEntries(
|
||||
entries: FSEntryCreateInput[],
|
||||
createPaths = true,
|
||||
@@ -2074,6 +2079,10 @@ export class FSEntryStore extends PuterStore {
|
||||
{ legacyCode: 'cannot_overwrite_a_directory' },
|
||||
);
|
||||
}
|
||||
if (existingEntry.uuid !== entry.input.uuid) {
|
||||
updatedResultsByIndex.set(entry.index, existingEntry);
|
||||
continue;
|
||||
}
|
||||
|
||||
const updatedEntry = {
|
||||
...existingEntry,
|
||||
@@ -2398,6 +2407,10 @@ export class FSEntryStore extends PuterStore {
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (existing.uuid !== entry.input.uuid) {
|
||||
updatedResultsByIndex.set(entry.index, existing);
|
||||
continue;
|
||||
}
|
||||
|
||||
const updatedEntry: FSEntry = {
|
||||
...existing,
|
||||
|
||||
@@ -159,8 +159,8 @@ export interface AppSummaryOptions {
|
||||
|
||||
/**
|
||||
* The summary the desktop launches from directly, without re-reading the app
|
||||
* (suggested, recommended, recent and taskbar apps), so every launch-relevant
|
||||
* flag belongs here.
|
||||
* (suggested, recommended and recent apps), so every launch-relevant flag
|
||||
* belongs here.
|
||||
*/
|
||||
export function toAppSummary(
|
||||
app: AppRow,
|
||||
|
||||
@@ -18,7 +18,10 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeStrictBase64 } from './mediaSniff.ts';
|
||||
import {
|
||||
decodeStrictBase64,
|
||||
decodeStrictBase64InSlices,
|
||||
} from './mediaSniff.ts';
|
||||
|
||||
describe('decodeStrictBase64', () => {
|
||||
it.each([
|
||||
@@ -50,3 +53,52 @@ describe('decodeStrictBase64', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('decodeStrictBase64InSlices', () => {
|
||||
// Several slices, with a last one that is partial and padded.
|
||||
const bytes = Buffer.alloc(5 * 1024 * 1024 + 2);
|
||||
for (let i = 0; i < bytes.length; i += 4099) bytes[i] = i % 251;
|
||||
const valid = bytes.toString('base64');
|
||||
|
||||
it('decodes a multi-MB payload to the same bytes', async () => {
|
||||
expect(valid.endsWith('==')).toBe(true);
|
||||
expect((await decodeStrictBase64InSlices(valid))?.equals(bytes)).toBe(
|
||||
true,
|
||||
);
|
||||
const short = Buffer.from('abcd').toString('base64');
|
||||
expect(await decodeStrictBase64InSlices(short)).toEqual(
|
||||
Buffer.from('abcd'),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['empty input', ''],
|
||||
['unpadded input', valid.slice(0, -2)],
|
||||
[
|
||||
'a character outside the alphabet in the first slice',
|
||||
`*${valid.slice(1)}`,
|
||||
],
|
||||
[
|
||||
'a character outside the alphabet in the last slice',
|
||||
`${valid.slice(0, -5)}*${valid.slice(-4)}`,
|
||||
],
|
||||
[
|
||||
'the URL-safe alphabet',
|
||||
`${valid.slice(0, 3_000_000)}-${valid.slice(3_000_001)}`,
|
||||
],
|
||||
[
|
||||
'a non-ASCII character',
|
||||
`${valid.slice(0, 3_000_000)}ī${valid.slice(3_000_001)}`,
|
||||
],
|
||||
[
|
||||
'padding where a slice ends',
|
||||
`${valid.slice(0, 1024 * 1024 - 1)}=${valid.slice(1024 * 1024)}`,
|
||||
],
|
||||
[
|
||||
'padding inside a slice',
|
||||
`${valid.slice(0, 2_000_002)}==${valid.slice(2_000_004)}`,
|
||||
],
|
||||
])('rejects %s', async (_label, value) => {
|
||||
expect(await decodeStrictBase64InSlices(value)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,8 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { setImmediate as nextTurn } from 'node:timers/promises';
|
||||
|
||||
// Identify uploaded media by its bytes. A caller-supplied MIME type or file
|
||||
// extension is never trusted.
|
||||
|
||||
@@ -69,6 +71,33 @@ export function decodeStrictBase64(value: string): Buffer | null {
|
||||
return bytes.length === (value.length / 4) * 3 - padding ? bytes : null;
|
||||
}
|
||||
|
||||
/** Base64 characters decoded per turn; a multiple of four. */
|
||||
const BASE64_SLICE_CHARS = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* `decodeStrictBase64` for payloads of many megabytes: decodes a slice per turn
|
||||
* of the event loop, so the whole string never holds it.
|
||||
*/
|
||||
export async function decodeStrictBase64InSlices(
|
||||
value: string,
|
||||
): Promise<Buffer | null> {
|
||||
if (value.length <= BASE64_SLICE_CHARS) return decodeStrictBase64(value);
|
||||
if (value.length % 4 !== 0) return null;
|
||||
const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
|
||||
const bytes = Buffer.allocUnsafe((value.length / 4) * 3 - padding);
|
||||
let written = 0;
|
||||
for (let at = 0; at < value.length; at += BASE64_SLICE_CHARS) {
|
||||
const slice = decodeStrictBase64(
|
||||
value.slice(at, at + BASE64_SLICE_CHARS),
|
||||
);
|
||||
// Padding inside the string leaves a slice short, and the total with it.
|
||||
if (!slice || written + slice.length > bytes.length) return null;
|
||||
written += slice.copy(bytes, written);
|
||||
await nextTurn();
|
||||
}
|
||||
return written === bytes.length ? bytes : null;
|
||||
}
|
||||
|
||||
function looksLikeSvg(bytes: Buffer): boolean {
|
||||
let head = bytes.subarray(0, SVG_SNIFF_WINDOW).toString('utf8');
|
||||
if (head.charCodeAt(0) === 0xfeff) head = head.slice(1);
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
/*
|
||||
* 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 { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
MAX_DEPTH,
|
||||
parseJsonInSlices,
|
||||
SLICE_BYTES,
|
||||
STRING_PIECE_BYTES,
|
||||
} from './slicedJson.js';
|
||||
|
||||
type Outcome = { value: unknown } | { error: string };
|
||||
|
||||
const native = (body: Buffer): Outcome => {
|
||||
try {
|
||||
return { value: JSON.parse(body.toString('utf8')) };
|
||||
} catch (e) {
|
||||
return { error: (e as Error).name };
|
||||
}
|
||||
};
|
||||
|
||||
const sliced = async (body: Buffer): Promise<Outcome> => {
|
||||
try {
|
||||
return { value: await parseJsonInSlices(body) };
|
||||
} catch (e) {
|
||||
return { error: (e as Error).name };
|
||||
}
|
||||
};
|
||||
|
||||
/** Key order, own `__proto__` keys and lone surrogates all show in the text. */
|
||||
const shown = (outcome: Outcome): string =>
|
||||
'error' in outcome ? outcome.error : JSON.stringify(outcome.value);
|
||||
|
||||
const expectSameAsNative = async (body: Buffer | string): Promise<void> => {
|
||||
const buffer = typeof body === 'string' ? Buffer.from(body) : body;
|
||||
expect(shown(await sliced(buffer))).toBe(shown(native(buffer)));
|
||||
};
|
||||
|
||||
/** Whitespace that pushes `text` onto the sliced path without changing it. */
|
||||
const padded = (text: string): string => `${' '.repeat(SLICE_BYTES)}${text}`;
|
||||
|
||||
// mulberry32: the cases must be the same on every run.
|
||||
const seeded = (seed: number) => () => {
|
||||
seed = (seed + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
|
||||
const STRING_PARTS = [
|
||||
'a',
|
||||
'word ',
|
||||
'"',
|
||||
'\\',
|
||||
'\\\\"',
|
||||
'\n',
|
||||
'\u0001',
|
||||
'é',
|
||||
'日本',
|
||||
'😀',
|
||||
'\ud83d',
|
||||
'\u2028',
|
||||
'/',
|
||||
'\\u00e9',
|
||||
];
|
||||
const KEYS = ['id', 'name', '__proto__', '7', '3', 'constructor', 'a b', ''];
|
||||
// No key holds a backslash: with one in a key seen earlier, some V8 versions
|
||||
// misread a later escaped key, in `JSON.parse` itself.
|
||||
const KEY_PARTS = STRING_PARTS.filter((part) => !part.includes('\\'));
|
||||
const SCALARS = [
|
||||
'0',
|
||||
'-0',
|
||||
'1.5e300',
|
||||
'-12.25',
|
||||
'1e-7',
|
||||
'9007199254740993',
|
||||
'true',
|
||||
'false',
|
||||
'null',
|
||||
];
|
||||
const GAPS = ['', '', '', ' ', '\n\t', '\r\n '];
|
||||
|
||||
/** A random JSON document, written as text so spacing and escapes vary. */
|
||||
const randomDocument = (
|
||||
random: () => number,
|
||||
targetBytes: number,
|
||||
{ plainKeys = false } = {},
|
||||
): string => {
|
||||
const pick = <T>(items: readonly T[]): T =>
|
||||
items[Math.floor(random() * items.length)]!;
|
||||
const gap = () => pick(GAPS);
|
||||
const string = (maxParts: number, from = STRING_PARTS): string => {
|
||||
let text = '';
|
||||
const parts = Math.floor(random() * maxParts);
|
||||
for (let i = 0; i < parts; i++) text += pick(from);
|
||||
return JSON.stringify(text);
|
||||
};
|
||||
let written = 0;
|
||||
const value = (depth: number): string => {
|
||||
const roll = random();
|
||||
let text: string;
|
||||
if (depth > 0 && roll < 0.25) {
|
||||
const count = Math.floor(random() * 12);
|
||||
const items: string[] = [];
|
||||
for (let i = 0; i < count; i++) items.push(value(depth - 1));
|
||||
text = `[${gap()}${items.join(`${gap()},${gap()}`)}${gap()}]`;
|
||||
} else if (depth > 0 && roll < 0.5) {
|
||||
const count = Math.floor(random() * 12);
|
||||
const members: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const key =
|
||||
plainKeys || random() < 0.7
|
||||
? JSON.stringify(pick(KEYS))
|
||||
: string(6, KEY_PARTS);
|
||||
members.push(`${key}${gap()}:${gap()}${value(depth - 1)}`);
|
||||
}
|
||||
text = `{${gap()}${members.join(`${gap()},${gap()}`)}${gap()}}`;
|
||||
} else if (roll < 0.75) {
|
||||
// Now and then one long enough to be read in pieces.
|
||||
text = string(random() < 0.002 ? 3 * SLICE_BYTES : 20);
|
||||
} else {
|
||||
text = pick(SCALARS);
|
||||
}
|
||||
written += text.length;
|
||||
return text;
|
||||
};
|
||||
const items: string[] = [];
|
||||
while (written < targetBytes) items.push(value(6));
|
||||
return random() < 0.5
|
||||
? `[${items.join(',')}]`
|
||||
: `{${items.map((item, i) => `"k${i % 50}":${item}`).join(',')}}`;
|
||||
};
|
||||
|
||||
describe('parseJsonInSlices', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('parses what JSON.parse parses, the same way', async () => {
|
||||
const random = seeded(1);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const size = SLICE_BYTES * (1 + Math.floor(random() * 12));
|
||||
await expectSameAsNative(randomDocument(random, size));
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('parses the same when every clock read ends the turn', async () => {
|
||||
let now = 0;
|
||||
vi.spyOn(performance, 'now').mockImplementation(() => (now += 1000));
|
||||
const random = seeded(3);
|
||||
for (let i = 0; i < 30; i++) {
|
||||
await expectSameAsNative(randomDocument(random, 6 * SLICE_BYTES));
|
||||
}
|
||||
// Strings long enough for a turn to end inside them.
|
||||
await expectSameAsNative(
|
||||
`["${'ab\\n'.repeat(SLICE_BYTES)}",{"k":"${'\\\\'.repeat(SLICE_BYTES)}"},${'1234567890'.repeat(SLICE_BYTES / 2)}]`,
|
||||
);
|
||||
}, 60_000);
|
||||
|
||||
it('rejects what JSON.parse rejects', async () => {
|
||||
const random = seeded(2);
|
||||
const replacements = Buffer.from('[]{},:"\\ 0a\néx-.e');
|
||||
for (let i = 0; i < 40; i++) {
|
||||
// Plain keys, so no edit can leave a backslash in one.
|
||||
const valid = Buffer.from(
|
||||
randomDocument(random, 2 * SLICE_BYTES, { plainKeys: true }),
|
||||
);
|
||||
for (let edit = 0; edit < 12; edit++) {
|
||||
const body = Buffer.from(valid);
|
||||
const at = Math.floor(random() * body.length);
|
||||
const roll = random();
|
||||
if (roll < 0.4) {
|
||||
body[at] =
|
||||
replacements[
|
||||
Math.floor(random() * replacements.length)
|
||||
]!;
|
||||
await expectSameAsNative(body);
|
||||
} else if (roll < 0.7) {
|
||||
await expectSameAsNative(
|
||||
Buffer.concat([
|
||||
body.subarray(0, at),
|
||||
body.subarray(at + 1),
|
||||
]),
|
||||
);
|
||||
} else {
|
||||
await expectSameAsNative(body.subarray(0, at));
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it.each([
|
||||
['an empty body', ''],
|
||||
['only whitespace', ' \n '],
|
||||
['two values', '[1] [2]'],
|
||||
['a trailing comma in an array', '[1,2,]'],
|
||||
['a trailing comma in an object', '{"a":1,}'],
|
||||
['a leading comma', '[,1]'],
|
||||
['a doubled comma', '[1,,2]'],
|
||||
['a missing colon', '{"a" 1}'],
|
||||
['a missing value', '{"a":}'],
|
||||
['a bare key', '{a:1}'],
|
||||
['a colon in an array', '[1:2]'],
|
||||
['mismatched brackets', '[1}'],
|
||||
['an extra close', '[1]]'],
|
||||
['an unterminated string', '["abc'],
|
||||
['an unterminated array', '[1,2'],
|
||||
['a byte order mark', '\ufeff[1]'],
|
||||
['a comment', '[1/* x */]'],
|
||||
['a bad literal', '[tru]'],
|
||||
['a bad number', '[01]'],
|
||||
['a bad escape', '["\\x"]'],
|
||||
['a raw control character in a string', '["a\tb"]'],
|
||||
['a wide space between values', '[1,\u00a02]'],
|
||||
])('rejects %s', async (_name, text) => {
|
||||
await expectSameAsNative(text);
|
||||
// Short input takes the native path, so check the sliced one too.
|
||||
await expectSameAsNative(padded(text));
|
||||
await expectSameAsNative(
|
||||
`[${'1,'.repeat(SLICE_BYTES)}${text},${'2,'.repeat(SLICE_BYTES)}3]`,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a string longer than one piece, wherever a piece ends', async () => {
|
||||
const units = [
|
||||
'\\u00e9',
|
||||
'\\n',
|
||||
'\\\\',
|
||||
'\\"',
|
||||
'é',
|
||||
'日',
|
||||
'😀',
|
||||
'\\ud83d\\ude00',
|
||||
];
|
||||
for (const unit of units) {
|
||||
for (let shift = 0; shift < 9; shift++) {
|
||||
const lead = 'a'.repeat(STRING_PIECE_BYTES - 12 + shift);
|
||||
const text = `{"text":"${lead}${unit.repeat(8)}${lead}","n":1}`;
|
||||
await expectSameAsNative(text);
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('reads long runs of escapes and stray UTF-8 bytes', async () => {
|
||||
const length = STRING_PIECE_BYTES + SLICE_BYTES;
|
||||
await expectSameAsNative(`["${'\\\\'.repeat(length)}"]`);
|
||||
await expectSameAsNative(`["${'\\"'.repeat(length)}"]`);
|
||||
await expectSameAsNative(`["${'\\'.repeat(2 * length + 1)}"]`);
|
||||
await expectSameAsNative(
|
||||
Buffer.concat([
|
||||
Buffer.from('["'),
|
||||
Buffer.alloc(2 * length, 0x80),
|
||||
Buffer.from([0xe2, 0x82]),
|
||||
Buffer.from('"]'),
|
||||
]),
|
||||
);
|
||||
}, 60_000);
|
||||
|
||||
it('reads a long key', async () => {
|
||||
const key = 'k'.repeat(2 * SLICE_BYTES);
|
||||
await expectSameAsNative(`{"a":1,"${key}":{"b":[2]},"${key}x":"v"}`);
|
||||
await expectSameAsNative(`{"${key}\\n":2,"z":3}`);
|
||||
});
|
||||
|
||||
it('reads long gaps of whitespace', async () => {
|
||||
const gap = ' '.repeat(2 * SLICE_BYTES);
|
||||
await expectSameAsNative(
|
||||
`${gap}{${gap}"a"${gap}:${gap}1${gap},${gap}"b":[${gap}2${gap},3${gap}]${gap}}${gap}`,
|
||||
);
|
||||
await expectSameAsNative(`[1,${gap}2${gap}]`);
|
||||
});
|
||||
|
||||
it('reads a scalar or a string at the top level', async () => {
|
||||
await expectSameAsNative(padded('12.5'));
|
||||
await expectSameAsNative(padded('null'));
|
||||
await expectSameAsNative(`"${'x'.repeat(4 * SLICE_BYTES)}"`);
|
||||
});
|
||||
|
||||
it('keeps the last of a repeated key, in its first position', async () => {
|
||||
const filler = `"f":"${'x'.repeat(SLICE_BYTES)}"`;
|
||||
await expectSameAsNative(`{"a":1,"b":2,${filler},"a":3,"7":4,"3":5}`);
|
||||
const value = (await parseJsonInSlices(
|
||||
Buffer.from(`{"a":1,"b":2,${filler},"a":3}`),
|
||||
)) as Record<string, unknown>;
|
||||
expect(Object.keys(value)).toEqual(['a', 'b', 'f']);
|
||||
expect(value.a).toBe(3);
|
||||
});
|
||||
|
||||
it('keeps __proto__ as a plain own property', async () => {
|
||||
const filler = `"f":"${'x'.repeat(SLICE_BYTES)}"`;
|
||||
const bodies = [
|
||||
// In a batch of members, as a container of its own, and alone.
|
||||
`{${filler},"__proto__":{"polluted":true},"z":1}`,
|
||||
`{"__proto__":{"polluted":true,${filler}}}`,
|
||||
`{"__proto__":"${'y'.repeat(2 * SLICE_BYTES)}"}`,
|
||||
];
|
||||
for (const body of bodies) {
|
||||
const value = (await parseJsonInSlices(
|
||||
Buffer.from(body),
|
||||
)) as Record<string, unknown>;
|
||||
expect(Object.getPrototypeOf(value)).toBe(Object.prototype);
|
||||
expect(Object.hasOwn(value, '__proto__')).toBe(true);
|
||||
expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the sign of negative zero', async () => {
|
||||
const value = (await parseJsonInSlices(
|
||||
Buffer.from(`[${'0,'.repeat(SLICE_BYTES)}-0]`),
|
||||
)) as number[];
|
||||
expect(Object.is(value.at(-1), -0)).toBe(true);
|
||||
});
|
||||
|
||||
it('reads nesting up to the depth limit and refuses more', async () => {
|
||||
const nested = (depth: number) =>
|
||||
padded(`${'['.repeat(depth)}${']'.repeat(depth)}`);
|
||||
// The root is not a level of nesting.
|
||||
let value = await parseJsonInSlices(Buffer.from(nested(MAX_DEPTH)));
|
||||
let depth = 0;
|
||||
while (Array.isArray(value)) {
|
||||
depth++;
|
||||
value = value[0];
|
||||
}
|
||||
expect(depth).toBe(MAX_DEPTH);
|
||||
|
||||
await expect(
|
||||
parseJsonInSlices(Buffer.from(nested(MAX_DEPTH + 1))),
|
||||
).rejects.toThrow(SyntaxError);
|
||||
});
|
||||
|
||||
it('reads members spread thinly across many levels', async () => {
|
||||
// No level holds a slice of members, but together they hold many.
|
||||
const members = '1,'.repeat(SLICE_BYTES / 8);
|
||||
const depth = 200;
|
||||
await expectSameAsNative(
|
||||
`${`[${members}`.repeat(depth)}0${']'.repeat(depth)}`,
|
||||
);
|
||||
await expectSameAsNative(
|
||||
`${`{"a":[${members}0],"b":`.repeat(depth)}0${'}'.repeat(depth)}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the event loop run while it parses', async () => {
|
||||
// Dense input: the slowest kind to parse for its size.
|
||||
const body = Buffer.from(`[${'[],'.repeat(1_000_000)}[]]`);
|
||||
let turns = 0;
|
||||
let running = true;
|
||||
const tick = () => {
|
||||
turns++;
|
||||
if (running) setImmediate(tick);
|
||||
};
|
||||
setImmediate(tick);
|
||||
const value = (await parseJsonInSlices(body)) as unknown[];
|
||||
running = false;
|
||||
expect(value).toHaveLength(1_000_001);
|
||||
expect(turns).toBeGreaterThan(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,581 @@
|
||||
/*
|
||||
* 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 { setImmediate as nextTurn } from 'node:timers/promises';
|
||||
|
||||
/**
|
||||
* Text handed to one native `JSON.parse` call stays within a few multiples of
|
||||
* this, which bounds how long the call can run. Shorter input parses whole.
|
||||
*/
|
||||
export const SLICE_BYTES = 32 * 1024;
|
||||
/** Bytes of a long string decoded per turn. */
|
||||
export const STRING_PIECE_BYTES = 512 * 1024;
|
||||
/** Deeper nesting is refused. No mainstream serializer writes this deep. */
|
||||
export const MAX_DEPTH = 10_000;
|
||||
/** How long a parse runs before the event loop gets a turn. */
|
||||
const TURN_BUDGET_MS = 3;
|
||||
/** Bytes scanned between clock reads. */
|
||||
const CLOCK_INTERVAL_BYTES = 16 * 1024;
|
||||
/** Bytes of a string scanned one at a time before a native search takes over. */
|
||||
const BYTEWISE_BYTES = 64;
|
||||
/** Rounds of a string scan between clock reads. */
|
||||
const CLOCK_INTERVAL_ROUNDS = 64;
|
||||
|
||||
const QUOTE = 0x22;
|
||||
const BACKSLASH = 0x5c;
|
||||
|
||||
// Byte classes. Anything unlisted is part of a number or literal.
|
||||
const C_SCALAR = 0;
|
||||
const C_SPACE = 1;
|
||||
const C_QUOTE = 2;
|
||||
const C_OPEN_ARRAY = 3;
|
||||
const C_OPEN_OBJECT = 4;
|
||||
const C_CLOSE_ARRAY = 5;
|
||||
const C_CLOSE_OBJECT = 6;
|
||||
const C_COMMA = 7;
|
||||
const C_COLON = 8;
|
||||
const BYTE_CLASS = new Uint8Array(256);
|
||||
for (const byte of [0x20, 0x09, 0x0a, 0x0d]) BYTE_CLASS[byte] = C_SPACE;
|
||||
BYTE_CLASS[QUOTE] = C_QUOTE;
|
||||
BYTE_CLASS[0x5b] = C_OPEN_ARRAY;
|
||||
BYTE_CLASS[0x7b] = C_OPEN_OBJECT;
|
||||
BYTE_CLASS[0x5d] = C_CLOSE_ARRAY;
|
||||
BYTE_CLASS[0x7d] = C_CLOSE_OBJECT;
|
||||
BYTE_CLASS[0x2c] = C_COMMA;
|
||||
BYTE_CLASS[0x3a] = C_COLON;
|
||||
|
||||
const ROOT = 0;
|
||||
const ARRAY = 1;
|
||||
const OBJECT = 2;
|
||||
|
||||
/** Just opened: a member or the close. */
|
||||
const S_FIRST = 0;
|
||||
/** After a comma: a member. */
|
||||
const S_MEMBER = 1;
|
||||
/** After an object key. */
|
||||
const S_COLON = 2;
|
||||
/** After a colon, and the root before its value. */
|
||||
const S_VALUE = 3;
|
||||
/** After a value: a comma or the close. The root is done. */
|
||||
const S_AFTER = 4;
|
||||
|
||||
const DONE = 0;
|
||||
const TURN = 1;
|
||||
const LONG_STRING = 2;
|
||||
|
||||
/**
|
||||
* One open container, or the root. Members are scanned, not parsed: `pending`
|
||||
* marks text handed to `JSON.parse` once enough of it has built up, and a
|
||||
* container too large for one call gets its `out` filled a batch at a time.
|
||||
*/
|
||||
class Frame {
|
||||
kind = ROOT;
|
||||
state = S_VALUE;
|
||||
/** Offset of the opening bracket. */
|
||||
start = 0;
|
||||
/** The container under construction, once it is known to be large. */
|
||||
out: unknown[] | Record<string, unknown> | null = null;
|
||||
/** Where the members not yet parsed start, or -1. */
|
||||
pending = -1;
|
||||
/** Where the last complete member ended. */
|
||||
lastEnd = -1;
|
||||
/** Bounds of the member being scanned. */
|
||||
memberStart = -1;
|
||||
keyStart = -1;
|
||||
keyEnd = -1;
|
||||
valueStart = -1;
|
||||
/** The current member's key, when the member is parsed apart from `pending`. */
|
||||
ownKey: string | null = null;
|
||||
/** Bytes of the parent's `pending` waiting behind this container. */
|
||||
backlog = 0;
|
||||
|
||||
open(kind: number, start: number): void {
|
||||
this.kind = kind;
|
||||
this.state = kind === ROOT ? S_VALUE : S_FIRST;
|
||||
this.start = start;
|
||||
this.out = null;
|
||||
this.pending = -1;
|
||||
this.lastEnd = -1;
|
||||
this.memberStart = -1;
|
||||
this.keyStart = -1;
|
||||
this.keyEnd = -1;
|
||||
this.valueStart = -1;
|
||||
this.ownKey = null;
|
||||
this.backlog = 0;
|
||||
}
|
||||
}
|
||||
|
||||
const unexpected = (at: number): SyntaxError =>
|
||||
new SyntaxError(`Unexpected token in JSON at position ${at}`);
|
||||
|
||||
/** `JSON.parse` keeps `__proto__` as an own property; assignment would not. */
|
||||
const setOwn = (
|
||||
target: Record<string, unknown>,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (key === '__proto__') {
|
||||
Object.defineProperty(target, key, {
|
||||
value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
} else {
|
||||
target[key] = value;
|
||||
}
|
||||
};
|
||||
|
||||
class SlicedJsonParser {
|
||||
result: unknown;
|
||||
/** Bounds of the string `run` stopped at, quotes included. */
|
||||
longStart = -1;
|
||||
longEnd = -1;
|
||||
|
||||
readonly #body: Buffer;
|
||||
readonly #end: number;
|
||||
#pos = 0;
|
||||
#frames = [new Frame()];
|
||||
#depth = 0;
|
||||
/** Frames below this depth have an `out`; the root counts as one. */
|
||||
#filling = 1;
|
||||
/** Bytes of `pending` in frames below the top one. */
|
||||
#backlog = 0;
|
||||
#inScalar = false;
|
||||
/** The string being scanned, and where its scan resumes. */
|
||||
#stringStart = -1;
|
||||
#stringPos = 0;
|
||||
/** Next quote and backslash at or after the last search origin. */
|
||||
#quoteAt = -1;
|
||||
#backslashAt = -1;
|
||||
#longIsKey = false;
|
||||
|
||||
constructor(body: Buffer) {
|
||||
this.#body = body;
|
||||
this.#end = body.length;
|
||||
}
|
||||
|
||||
/** Scans until the input ends, `deadline` passes, or a long string starts. */
|
||||
run(deadline: number): number {
|
||||
const body = this.#body;
|
||||
const end = this.#end;
|
||||
let i = this.#pos;
|
||||
let frame = this.#frames[this.#depth]!;
|
||||
let clockAt = i + CLOCK_INTERVAL_BYTES;
|
||||
|
||||
for (;;) {
|
||||
if (this.#stringStart !== -1) {
|
||||
const close = this.#stringEnd(deadline);
|
||||
if (close === -1) return TURN;
|
||||
const start = this.#stringStart;
|
||||
this.#stringStart = -1;
|
||||
i = close + 1;
|
||||
if (this.#string(frame, start, close)) {
|
||||
this.#pos = i;
|
||||
return LONG_STRING;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (i >= clockAt) {
|
||||
clockAt = i + CLOCK_INTERVAL_BYTES;
|
||||
if (performance.now() >= deadline) {
|
||||
this.#pos = i;
|
||||
return TURN;
|
||||
}
|
||||
}
|
||||
if (i >= end) break;
|
||||
|
||||
const byteClass = BYTE_CLASS[body[i]!]!;
|
||||
if (byteClass === C_SCALAR) {
|
||||
if (!this.#inScalar) {
|
||||
this.#valueStart(frame, i);
|
||||
this.#inScalar = true;
|
||||
}
|
||||
const stop = Math.min(end, clockAt);
|
||||
i++;
|
||||
while (i < stop && BYTE_CLASS[body[i]!] === C_SCALAR) i++;
|
||||
continue;
|
||||
}
|
||||
if (this.#inScalar) {
|
||||
this.#inScalar = false;
|
||||
this.#valueEnd(frame, i);
|
||||
}
|
||||
|
||||
switch (byteClass) {
|
||||
case C_SPACE: {
|
||||
const stop = Math.min(end, clockAt);
|
||||
i++;
|
||||
while (i < stop && BYTE_CLASS[body[i]!] === C_SPACE) i++;
|
||||
break;
|
||||
}
|
||||
case C_QUOTE:
|
||||
this.#stringStart = i;
|
||||
this.#stringPos = i + 1;
|
||||
break;
|
||||
case C_OPEN_ARRAY:
|
||||
case C_OPEN_OBJECT: {
|
||||
this.#valueStart(frame, i);
|
||||
if (this.#depth === MAX_DEPTH) {
|
||||
throw new SyntaxError('JSON is nested too deeply');
|
||||
}
|
||||
const parent = frame;
|
||||
// Members before this one wait until it closes or grows.
|
||||
const before =
|
||||
parent.pending !== -1 &&
|
||||
parent.pending !== parent.memberStart
|
||||
? parent.lastEnd - parent.pending
|
||||
: 0;
|
||||
this.#depth++;
|
||||
frame = this.#frames[this.#depth] ??= new Frame();
|
||||
frame.open(byteClass === C_OPEN_ARRAY ? ARRAY : OBJECT, i);
|
||||
frame.backlog = before;
|
||||
this.#backlog += before;
|
||||
// Parsed now, so deep nesting can't save it all up.
|
||||
if (this.#backlog >= SLICE_BYTES) this.#fill();
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
case C_CLOSE_ARRAY:
|
||||
case C_CLOSE_OBJECT: {
|
||||
if (
|
||||
frame.kind !==
|
||||
(byteClass === C_CLOSE_ARRAY ? ARRAY : OBJECT) ||
|
||||
(frame.state !== S_FIRST && frame.state !== S_AFTER)
|
||||
) {
|
||||
throw unexpected(i);
|
||||
}
|
||||
let filled = this.#depth < this.#filling;
|
||||
if (!filled && i + 1 - frame.start > SLICE_BYTES) {
|
||||
this.#fill();
|
||||
filled = true;
|
||||
}
|
||||
if (filled) {
|
||||
if (frame.pending !== -1) {
|
||||
this.#parsePending(frame);
|
||||
}
|
||||
frame.out = null;
|
||||
this.#filling = this.#depth;
|
||||
}
|
||||
this.#backlog -= frame.backlog;
|
||||
this.#depth--;
|
||||
frame = this.#frames[this.#depth]!;
|
||||
i++;
|
||||
if (filled) {
|
||||
frame.state = S_AFTER;
|
||||
frame.lastEnd = i;
|
||||
} else {
|
||||
this.#valueEnd(frame, i);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case C_COMMA:
|
||||
if (frame.kind === ROOT || frame.state !== S_AFTER) {
|
||||
throw unexpected(i);
|
||||
}
|
||||
frame.state = S_MEMBER;
|
||||
i++;
|
||||
break;
|
||||
default:
|
||||
if (frame.kind !== OBJECT || frame.state !== S_COLON) {
|
||||
throw unexpected(i);
|
||||
}
|
||||
frame.state = S_VALUE;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.#inScalar) {
|
||||
this.#inScalar = false;
|
||||
this.#valueEnd(frame, end);
|
||||
}
|
||||
if (this.#depth !== 0 || frame.state !== S_AFTER) {
|
||||
throw new SyntaxError('Unexpected end of JSON input');
|
||||
}
|
||||
if (frame.pending !== -1) this.#parsePending(frame);
|
||||
return DONE;
|
||||
}
|
||||
|
||||
/** Supplies the string `run` stopped at. */
|
||||
resolveLongString(value: string): void {
|
||||
const frame = this.#frames[this.#depth]!;
|
||||
if (this.#longIsKey) {
|
||||
frame.ownKey = value;
|
||||
return;
|
||||
}
|
||||
this.#attach(frame, frame.ownKey, value);
|
||||
frame.ownKey = null;
|
||||
frame.lastEnd = this.longEnd + 1;
|
||||
frame.state = S_AFTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset of the quote closing the string being scanned, or -1 when
|
||||
* `deadline` passed first.
|
||||
*/
|
||||
#stringEnd(deadline: number): number {
|
||||
const body = this.#body;
|
||||
const end = this.#end;
|
||||
let at = this.#stringPos;
|
||||
|
||||
for (let round = 1; ; round++) {
|
||||
// Bytewise through a short string or a stretch of escapes.
|
||||
const near = Math.min(at + BYTEWISE_BYTES, end);
|
||||
while (at < near) {
|
||||
const byte = body[at]!;
|
||||
if (byte === QUOTE) return at;
|
||||
at += byte === BACKSLASH ? 2 : 1;
|
||||
}
|
||||
if (at >= end) throw new SyntaxError('Unterminated string in JSON');
|
||||
|
||||
// Then a native search across text that holds neither.
|
||||
if (this.#quoteAt < at) {
|
||||
this.#quoteAt = body.indexOf(QUOTE, at);
|
||||
if (this.#quoteAt === -1) {
|
||||
throw new SyntaxError('Unterminated string in JSON');
|
||||
}
|
||||
}
|
||||
if (this.#backslashAt < at) {
|
||||
const found = body.indexOf(BACKSLASH, at);
|
||||
this.#backslashAt = found === -1 ? end : found;
|
||||
}
|
||||
if (this.#backslashAt > this.#quoteAt) return this.#quoteAt;
|
||||
at = this.#backslashAt;
|
||||
|
||||
if (round % CLOCK_INTERVAL_ROUNDS === 0) {
|
||||
if (performance.now() >= deadline) {
|
||||
this.#stringPos = at;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles a scanned string; true when `run` must stop for a long one. */
|
||||
#string(frame: Frame, start: number, close: number): boolean {
|
||||
const long = close - start > SLICE_BYTES;
|
||||
if (
|
||||
frame.kind === OBJECT &&
|
||||
(frame.state === S_FIRST || frame.state === S_MEMBER)
|
||||
) {
|
||||
this.#memberStart(frame, start);
|
||||
frame.keyStart = start;
|
||||
frame.keyEnd = close;
|
||||
frame.state = S_COLON;
|
||||
if (!long) return false;
|
||||
this.#detachMember(frame);
|
||||
this.#longIsKey = true;
|
||||
} else {
|
||||
this.#valueStart(frame, start);
|
||||
if (!long) {
|
||||
this.#valueEnd(frame, close + 1);
|
||||
return false;
|
||||
}
|
||||
if (frame.ownKey === null) {
|
||||
this.#detachMember(frame);
|
||||
if (frame.kind === OBJECT) frame.ownKey = this.#key(frame);
|
||||
}
|
||||
this.#longIsKey = false;
|
||||
}
|
||||
this.longStart = start;
|
||||
this.longEnd = close;
|
||||
return true;
|
||||
}
|
||||
|
||||
#memberStart(frame: Frame, at: number): void {
|
||||
if (frame.pending !== -1 && at - frame.pending >= SLICE_BYTES) {
|
||||
this.#fill();
|
||||
this.#parsePending(frame);
|
||||
}
|
||||
frame.memberStart = at;
|
||||
if (frame.pending === -1) frame.pending = at;
|
||||
}
|
||||
|
||||
#valueStart(frame: Frame, at: number): void {
|
||||
if (frame.kind === OBJECT) {
|
||||
if (frame.state !== S_VALUE) throw unexpected(at);
|
||||
// A long gap after the key would reach `JSON.parse` with it.
|
||||
if (frame.ownKey === null && at - frame.memberStart > SLICE_BYTES) {
|
||||
this.#detachMember(frame);
|
||||
frame.ownKey = this.#key(frame);
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
frame.kind === ROOT
|
||||
? frame.state !== S_VALUE
|
||||
: frame.state > S_MEMBER
|
||||
) {
|
||||
throw unexpected(at);
|
||||
}
|
||||
this.#memberStart(frame, at);
|
||||
}
|
||||
frame.valueStart = at;
|
||||
}
|
||||
|
||||
#valueEnd(frame: Frame, at: number): void {
|
||||
frame.lastEnd = at;
|
||||
frame.state = S_AFTER;
|
||||
if (frame.ownKey !== null) {
|
||||
this.#attach(
|
||||
frame,
|
||||
frame.ownKey,
|
||||
JSON.parse(this.#text(frame.valueStart, at)),
|
||||
);
|
||||
frame.ownKey = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes the current member out of `pending`; its value is attached alone. */
|
||||
#detachMember(frame: Frame): void {
|
||||
this.#fill();
|
||||
if (frame.pending !== -1 && frame.pending !== frame.memberStart) {
|
||||
this.#parsePending(frame);
|
||||
}
|
||||
frame.pending = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives every open container an `out`, attached to its parent after the
|
||||
* members that precede it.
|
||||
*/
|
||||
#fill(): void {
|
||||
const frames = this.#frames;
|
||||
for (let level = this.#filling; level <= this.#depth; level++) {
|
||||
const parent = frames[level - 1]!;
|
||||
const child = frames[level]!;
|
||||
if (
|
||||
parent.pending !== -1 &&
|
||||
parent.pending !== parent.memberStart
|
||||
) {
|
||||
this.#parsePending(parent);
|
||||
}
|
||||
parent.pending = -1;
|
||||
const key =
|
||||
parent.kind === OBJECT
|
||||
? (parent.ownKey ?? this.#key(parent))
|
||||
: null;
|
||||
parent.ownKey = null;
|
||||
child.out = child.kind === ARRAY ? [] : {};
|
||||
child.backlog = 0;
|
||||
this.#attach(parent, key, child.out);
|
||||
}
|
||||
this.#filling = this.#depth + 1;
|
||||
this.#backlog = 0;
|
||||
}
|
||||
|
||||
/** Parses the complete members in `pending` into the frame's container. */
|
||||
#parsePending(frame: Frame): void {
|
||||
const text = this.#text(frame.pending, frame.lastEnd);
|
||||
frame.pending = -1;
|
||||
if (frame.kind === ROOT) {
|
||||
this.result = JSON.parse(text);
|
||||
} else if (frame.kind === ARRAY) {
|
||||
const out = frame.out as unknown[];
|
||||
const items = JSON.parse(`[${text}]`) as unknown[];
|
||||
for (let k = 0; k < items.length; k++) out.push(items[k]);
|
||||
} else {
|
||||
const out = frame.out as Record<string, unknown>;
|
||||
const members = JSON.parse(`{${text}}`) as Record<string, unknown>;
|
||||
for (const key of Object.keys(members)) {
|
||||
setOwn(out, key, members[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#attach(frame: Frame, key: string | null, value: unknown): void {
|
||||
if (frame.kind === ROOT) this.result = value;
|
||||
else if (frame.kind === ARRAY) (frame.out as unknown[]).push(value);
|
||||
else setOwn(frame.out as Record<string, unknown>, key!, value);
|
||||
}
|
||||
|
||||
#key(frame: Frame): string {
|
||||
return JSON.parse(
|
||||
this.#text(frame.keyStart, frame.keyEnd + 1),
|
||||
) as string;
|
||||
}
|
||||
|
||||
#text(from: number, to: number): string {
|
||||
return this.#body.toString('utf8', from, to);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a string's content can be cut at or before `target` without splitting
|
||||
* an escape or a UTF-8 sequence. `from` starts a character or an escape.
|
||||
*/
|
||||
const pieceEnd = (body: Buffer, from: number, target: number): number => {
|
||||
// Far enough back that a `\uXXXX` reaching `target` starts after it.
|
||||
let at = Math.max(from, target - 8);
|
||||
// An odd run of backslashes before `at` means `at` is an escaped byte.
|
||||
let run = 0;
|
||||
while (at - run > from && body[at - run - 1] === BACKSLASH) run++;
|
||||
at -= run % 2;
|
||||
for (;;) {
|
||||
const length =
|
||||
body[at] !== BACKSLASH ? 1 : body[at + 1] === 0x75 ? 6 : 2;
|
||||
if (at + length > target) break;
|
||||
at += length;
|
||||
}
|
||||
// A sequence has at most three continuation bytes; more are stray.
|
||||
for (let back = 0; back < 3 && (body[at]! & 0xc0) === 0x80; back++) at--;
|
||||
return at;
|
||||
};
|
||||
|
||||
/** The string literal at `[start, close]`, decoded a piece per turn. */
|
||||
const readLongString = async (
|
||||
body: Buffer,
|
||||
start: number,
|
||||
close: number,
|
||||
): Promise<string> => {
|
||||
const pieces: string[] = [];
|
||||
let at = start + 1;
|
||||
while (at < close) {
|
||||
const end =
|
||||
close - at <= STRING_PIECE_BYTES
|
||||
? close
|
||||
: pieceEnd(body, at, at + STRING_PIECE_BYTES);
|
||||
pieces.push(
|
||||
JSON.parse(`"${body.toString('utf8', at, end)}"`) as string,
|
||||
);
|
||||
at = end;
|
||||
await nextTurn();
|
||||
}
|
||||
return pieces.join('');
|
||||
};
|
||||
|
||||
/**
|
||||
* `JSON.parse` of UTF-8 `body`, done in slices with the event loop running
|
||||
* between them, so no input holds it for long. Throws a `SyntaxError` for
|
||||
* malformed JSON, and for nesting deeper than `MAX_DEPTH`.
|
||||
*/
|
||||
export async function parseJsonInSlices(body: Buffer): Promise<unknown> {
|
||||
if (body.length <= SLICE_BYTES) return JSON.parse(body.toString('utf8'));
|
||||
|
||||
const parser = new SlicedJsonParser(body);
|
||||
for (;;) {
|
||||
const signal = parser.run(performance.now() + TURN_BUDGET_MS);
|
||||
if (signal === DONE) return parser.result;
|
||||
if (signal === LONG_STRING) {
|
||||
parser.resolveLongString(
|
||||
await readLongString(body, parser.longStart, parser.longEnd),
|
||||
);
|
||||
} else {
|
||||
await nextTurn();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,271 +0,0 @@
|
||||
/**
|
||||
* 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 { v4 as uuidv4 } from 'uuid';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { PuterServer } from '../server.ts';
|
||||
import { setupTestServer } from '../testUtil.ts';
|
||||
import { getTaskbarItems } from './taskbarItems.ts';
|
||||
|
||||
describe('getTaskbarItems', () => {
|
||||
let server: PuterServer;
|
||||
let deps: Parameters<typeof getTaskbarItems>[1];
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await setupTestServer();
|
||||
deps = {
|
||||
clients: server.clients,
|
||||
stores: server.stores,
|
||||
apiBaseUrl: 'https://api.puter.com',
|
||||
config: { static_hosting_domain: 'puter.site' },
|
||||
} as unknown as Parameters<typeof getTaskbarItems>[1];
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.shutdown();
|
||||
});
|
||||
|
||||
const makeUser = async (taskbarItems?: unknown) => {
|
||||
const username = `tb-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const created = await server.stores.user.create({
|
||||
username,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email: `${username}@test.local`,
|
||||
} as never);
|
||||
if (taskbarItems !== undefined) {
|
||||
await server.stores.user.update(created.id, {
|
||||
taskbar_items:
|
||||
typeof taskbarItems === 'string'
|
||||
? taskbarItems
|
||||
: JSON.stringify(taskbarItems),
|
||||
});
|
||||
}
|
||||
return (await server.stores.user.getById(created.id))!;
|
||||
};
|
||||
|
||||
const makeApp = async (ownerUserId: number, overrides = {}) => {
|
||||
const name = `tb-app-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return server.stores.app.create(
|
||||
{
|
||||
name,
|
||||
title: `Title ${name}`,
|
||||
index_url: `https://${name}.example.com/`,
|
||||
description: 'a test app',
|
||||
...overrides,
|
||||
},
|
||||
{ ownerUserId },
|
||||
);
|
||||
};
|
||||
|
||||
it('seeds the default taskbar for a user that has none, and persists it', async () => {
|
||||
const user = await makeUser();
|
||||
expect(user.taskbar_items).toBeFalsy();
|
||||
|
||||
await getTaskbarItems(user as never, deps);
|
||||
|
||||
const [row] = await server.clients.db.read(
|
||||
'SELECT `taskbar_items` FROM `user` WHERE `id` = ?',
|
||||
[user.id],
|
||||
);
|
||||
const stored = JSON.parse(String(row.taskbar_items));
|
||||
expect(stored.map((e: { name: string }) => e.name)).toContain(
|
||||
'app-center',
|
||||
);
|
||||
// The cached row must not keep serving the pre-seed value.
|
||||
expect(
|
||||
(await server.stores.user.getById(user.id))?.taskbar_items,
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('resolves entries by name, uid and id', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const byName = await makeApp(owner.id);
|
||||
const byUid = await makeApp(owner.id);
|
||||
const byId = await makeApp(owner.id);
|
||||
|
||||
const user = await makeUser([
|
||||
{ name: byName.name, type: 'app' },
|
||||
{ uid: byUid.uid, type: 'app' },
|
||||
{ id: byId.id, type: 'app' },
|
||||
]);
|
||||
|
||||
const items = await getTaskbarItems(user as never, deps);
|
||||
expect(items.map((i) => i.uid)).toEqual([
|
||||
byName.uid,
|
||||
byUid.uid,
|
||||
byId.uid,
|
||||
]);
|
||||
expect(items[0]).toMatchObject({
|
||||
uuid: byName.uid,
|
||||
name: byName.name,
|
||||
title: byName.title,
|
||||
godmode: false,
|
||||
maximize_on_start: false,
|
||||
description: 'a test app',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves the whole taskbar with one batched lookup per key, not one per entry', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const apps = await Promise.all([0, 1, 2].map(() => makeApp(owner.id)));
|
||||
const byUid = await makeApp(owner.id);
|
||||
const user = await makeUser([
|
||||
...apps.map((app) => ({ name: app.name, type: 'app' })),
|
||||
{ uid: byUid.uid, type: 'app' },
|
||||
]);
|
||||
const appStore = server.stores.app;
|
||||
const spies = {
|
||||
getByName: vi.spyOn(appStore, 'getByName'),
|
||||
getByUid: vi.spyOn(appStore, 'getByUid'),
|
||||
getById: vi.spyOn(appStore, 'getById'),
|
||||
getByNames: vi.spyOn(appStore, 'getByNames'),
|
||||
getByUids: vi.spyOn(appStore, 'getByUids'),
|
||||
};
|
||||
try {
|
||||
const items = await getTaskbarItems(user as never, deps);
|
||||
|
||||
expect(items.map((i) => i.uid)).toEqual([
|
||||
...apps.map((app) => app.uid),
|
||||
byUid.uid,
|
||||
]);
|
||||
expect(spies.getByName).not.toHaveBeenCalled();
|
||||
expect(spies.getByUid).not.toHaveBeenCalled();
|
||||
expect(spies.getById).not.toHaveBeenCalled();
|
||||
expect(spies.getByNames).toHaveBeenCalledTimes(1);
|
||||
expect(spies.getByUids).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
for (const spy of Object.values(spies)) spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('skips non-app entries, the explorer pin, and unresolvable apps', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const app = await makeApp(owner.id);
|
||||
const user = await makeUser([
|
||||
{ name: 'explorer', type: 'app' },
|
||||
{ name: 'nothing-here', type: 'app' },
|
||||
{ name: app.name, type: 'separator' },
|
||||
{ type: 'app' },
|
||||
{ name: app.name, type: 'app' },
|
||||
]);
|
||||
|
||||
const items = await getTaskbarItems(user as never, deps);
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].name).toBe(app.name);
|
||||
});
|
||||
|
||||
it('falls back to an empty taskbar when the stored JSON is corrupt', async () => {
|
||||
const user = await makeUser('{not json');
|
||||
expect(await getTaskbarItems(user as never, deps)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts an already-parsed taskbar array on the user row', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const app = await makeApp(owner.id);
|
||||
const user = await makeUser([]);
|
||||
|
||||
const items = await getTaskbarItems(
|
||||
{ ...user, taskbar_items: [{ name: app.name, type: 'app' }] },
|
||||
deps,
|
||||
);
|
||||
expect(items.map((i) => i.name)).toEqual([app.name]);
|
||||
});
|
||||
|
||||
it('builds a sized icon URL by default and drops the icon on request', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const app = await makeApp(owner.id);
|
||||
const user = await makeUser([{ name: app.name, type: 'app' }]);
|
||||
|
||||
const withIcon = await getTaskbarItems(user as never, deps, {
|
||||
iconSize: 64,
|
||||
});
|
||||
expect(withIcon[0].icon).toBe(
|
||||
`https://api.puter.com/app-icon/${app.uid}/64`,
|
||||
);
|
||||
|
||||
const withoutIcon = await getTaskbarItems(user as never, deps, {
|
||||
noIcons: true,
|
||||
});
|
||||
expect('icon' in withoutIcon[0]).toBe(false);
|
||||
});
|
||||
|
||||
it('pairs the icon URL with the direct subdomain URL when one exists', async () => {
|
||||
const owner = await makeUser([]);
|
||||
// An http(s) icon column is what the resize pipeline leaves behind, so
|
||||
// the sized PNG is on the subdomain.
|
||||
const app = await makeApp(owner.id, {
|
||||
icon: 'https://api.puter.com/app-icon/x',
|
||||
});
|
||||
const user = await makeUser([{ name: app.name, type: 'app' }]);
|
||||
|
||||
const items = await getTaskbarItems(user as never, deps, {
|
||||
iconSize: 64,
|
||||
});
|
||||
expect(items[0].icon).toBe(
|
||||
`https://api.puter.com/app-icon/${app.uid}/64`,
|
||||
);
|
||||
expect(items[0].iconCdnUrl).toBe(
|
||||
`https://puter-app-icons.puter.site/${app.uid}-64.png`,
|
||||
);
|
||||
});
|
||||
|
||||
it('reports no subdomain URL for an app whose icon was never generated', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const app = await makeApp(owner.id);
|
||||
const user = await makeUser([{ name: app.name, type: 'app' }]);
|
||||
|
||||
const items = await getTaskbarItems(user as never, deps, {
|
||||
iconSize: 64,
|
||||
});
|
||||
expect(items[0].iconCdnUrl).toBeNull();
|
||||
});
|
||||
|
||||
it('falls back to the raw icon column when no API base URL is configured', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const app = await makeApp(owner.id, {
|
||||
icon: 'https://cdn.example.com/i.png',
|
||||
});
|
||||
const user = await makeUser([{ name: app.name, type: 'app' }]);
|
||||
|
||||
const items = await getTaskbarItems(
|
||||
user as never,
|
||||
{
|
||||
...deps,
|
||||
apiBaseUrl: undefined,
|
||||
} as never,
|
||||
);
|
||||
expect(items[0].icon).toBe('https://cdn.example.com/i.png');
|
||||
});
|
||||
|
||||
it('reports null for an app with no icon and no API base URL', async () => {
|
||||
const owner = await makeUser([]);
|
||||
const app = await makeApp(owner.id);
|
||||
const user = await makeUser([{ name: app.name, type: 'app' }]);
|
||||
|
||||
const items = await getTaskbarItems(
|
||||
user as never,
|
||||
{
|
||||
...deps,
|
||||
apiBaseUrl: undefined,
|
||||
} as never,
|
||||
);
|
||||
expect(items[0].icon).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,134 +0,0 @@
|
||||
/*
|
||||
* 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 type { AppIconHostConfig } from './appIcon.js';
|
||||
import { toAppSummary, type AppRow } from './appView.js';
|
||||
|
||||
interface TaskbarEntry {
|
||||
name?: string;
|
||||
id?: number;
|
||||
uid?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
interface TaskbarOptions {
|
||||
iconSize?: number;
|
||||
noIcons?: boolean;
|
||||
}
|
||||
|
||||
interface TaskbarDeps {
|
||||
apiBaseUrl?: string;
|
||||
config?: AppIconHostConfig;
|
||||
stores: {
|
||||
app: {
|
||||
getByNames: (names: string[]) => Promise<Map<string, AppRow>>;
|
||||
getByUids: (uids: string[]) => Promise<Map<string, AppRow>>;
|
||||
getByIds: (ids: number[]) => Promise<Map<number, AppRow>>;
|
||||
};
|
||||
user: {
|
||||
update: (
|
||||
id: number,
|
||||
patch: Record<string, unknown>,
|
||||
) => Promise<unknown>;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const DEFAULT_TASKBAR_ITEMS: TaskbarEntry[] = [
|
||||
{ name: 'app-center', type: 'app' },
|
||||
{ name: 'builder', type: 'app' },
|
||||
{ name: 'dev-center', type: 'app' },
|
||||
{ name: 'editor', type: 'app' },
|
||||
{ name: 'code', type: 'app' },
|
||||
{ name: 'camera', type: 'app' },
|
||||
{ name: 'recorder', type: 'app' },
|
||||
{ name: 'browser', type: 'app' },
|
||||
];
|
||||
|
||||
export async function getTaskbarItems(
|
||||
user: Record<string, unknown>,
|
||||
deps: TaskbarDeps,
|
||||
options: TaskbarOptions = {},
|
||||
): Promise<Array<Record<string, unknown>>> {
|
||||
let raw: TaskbarEntry[];
|
||||
|
||||
if (!user.taskbar_items) {
|
||||
raw = DEFAULT_TASKBAR_ITEMS;
|
||||
await deps.stores.user.update(user.id as number, {
|
||||
taskbar_items: JSON.stringify(raw),
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
raw =
|
||||
typeof user.taskbar_items === 'string'
|
||||
? JSON.parse(user.taskbar_items as string)
|
||||
: (user.taskbar_items as TaskbarEntry[]);
|
||||
} catch {
|
||||
raw = [];
|
||||
}
|
||||
}
|
||||
|
||||
const entries = raw.filter(
|
||||
(entry) => entry.type === 'app' && entry.name !== 'explorer',
|
||||
);
|
||||
const [byName, byUid, byId] = await Promise.all([
|
||||
deps.stores.app.getByNames(
|
||||
entries.flatMap((entry) => (entry.name ? [entry.name] : [])),
|
||||
),
|
||||
deps.stores.app.getByUids(
|
||||
entries.flatMap((entry) =>
|
||||
!entry.name && entry.uid ? [entry.uid] : [],
|
||||
),
|
||||
),
|
||||
deps.stores.app.getByIds(
|
||||
entries.flatMap((entry) =>
|
||||
!entry.name && !entry.uid && entry.id ? [entry.id] : [],
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
const items: Array<Record<string, unknown>> = [];
|
||||
for (const entry of entries) {
|
||||
const app = entry.name
|
||||
? byName.get(entry.name)
|
||||
: entry.uid
|
||||
? byUid.get(entry.uid)
|
||||
: entry.id
|
||||
? byId.get(entry.id)
|
||||
: undefined;
|
||||
if (!app) continue;
|
||||
|
||||
const item: Record<string, unknown> = {
|
||||
uid: app.uid,
|
||||
...toAppSummary(app, {
|
||||
apiBaseUrl: deps.apiBaseUrl,
|
||||
config: deps.config,
|
||||
iconSize: options.iconSize,
|
||||
}),
|
||||
description: app.description,
|
||||
};
|
||||
if (options.noIcons) {
|
||||
delete item.icon;
|
||||
delete item.iconCdnUrl;
|
||||
}
|
||||
items.push(item);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
@@ -85,7 +85,17 @@ describe('buildUserDetails', () => {
|
||||
[`/${user.username}/Desktop`]: user.desktop_uuid,
|
||||
[`/${user.username}/Trash`]: user.trash_uuid,
|
||||
});
|
||||
expect(Array.isArray(details.taskbar_items)).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves out taskbar items saved on the account', async () => {
|
||||
const user = {
|
||||
...(await makeUser()),
|
||||
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
|
||||
};
|
||||
const details = await buildUserDetails(user, deps(), {
|
||||
isUser: true,
|
||||
});
|
||||
expect(details).not.toHaveProperty('taskbar_items');
|
||||
});
|
||||
|
||||
it('leaves the desktop-only parts out for an app actor', async () => {
|
||||
@@ -93,7 +103,6 @@ describe('buildUserDetails', () => {
|
||||
const details = await buildUserDetails(user, deps(), {
|
||||
isUser: false,
|
||||
});
|
||||
expect(details).not.toHaveProperty('taskbar_items');
|
||||
expect(details).not.toHaveProperty('directories');
|
||||
expect(details.card_fallback_available).toBe(false);
|
||||
});
|
||||
@@ -124,7 +133,7 @@ describe('buildUserDetails lookups', () => {
|
||||
return keys.slice(keys.indexOf('hasDevAccountAccess') + 1);
|
||||
};
|
||||
|
||||
it('reads the linked provider, taskbar and seat together, listed in a fixed order', async () => {
|
||||
it('reads the linked provider and seat together, listed in a fixed order', async () => {
|
||||
const user = {
|
||||
...(await makeUser()),
|
||||
password: null,
|
||||
@@ -162,7 +171,6 @@ describe('buildUserDetails lookups', () => {
|
||||
);
|
||||
expect(tailKeys(details)).toEqual([
|
||||
'oidc_revalidate_url',
|
||||
'taskbar_items',
|
||||
'directories',
|
||||
'team',
|
||||
'last_activity_ts',
|
||||
@@ -177,7 +185,6 @@ describe('buildUserDetails lookups', () => {
|
||||
const user = {
|
||||
...(await makeUser()),
|
||||
password: null,
|
||||
taskbar_items: JSON.stringify([{ type: 'app', name: 'editor' }]),
|
||||
last_activity_ts: '2026-01-02 03:04:05',
|
||||
};
|
||||
const events: string[] = [];
|
||||
@@ -199,15 +206,6 @@ describe('buildUserDetails lookups', () => {
|
||||
},
|
||||
},
|
||||
stores: Object.assign(Object.create(d.stores), {
|
||||
app: {
|
||||
getByNames: () =>
|
||||
timed(events, 'taskbar', 20, () => {
|
||||
throw new Error('taskbar down');
|
||||
}),
|
||||
getByUids: async () => new Map(),
|
||||
getByIds: async () => new Map(),
|
||||
},
|
||||
// Fails first, but is reported after the taskbar.
|
||||
team: {
|
||||
getOrgSeat: () =>
|
||||
timed(events, 'seat', 5, () => {
|
||||
@@ -219,18 +217,12 @@ describe('buildUserDetails lookups', () => {
|
||||
{ isUser: true },
|
||||
);
|
||||
expect(warn.mock.calls).toEqual([
|
||||
['[user-details] taskbar_items failed:', expect.any(Error)],
|
||||
['[user-details] team lookup failed:', expect.any(Error)],
|
||||
]);
|
||||
} finally {
|
||||
warn.mockRestore();
|
||||
}
|
||||
expect(tailKeys(details)).toEqual([
|
||||
'taskbar_items',
|
||||
'directories',
|
||||
'last_activity_ts',
|
||||
]);
|
||||
expect(details.taskbar_items).toEqual([]);
|
||||
expect(tailKeys(details)).toEqual(['directories', 'last_activity_ts']);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -27,18 +27,12 @@ import {
|
||||
isCardFallbackEligible,
|
||||
type CardFallbackClients,
|
||||
} from './cardFallback.js';
|
||||
import { getTaskbarItems } from './taskbarItems.js';
|
||||
import { isEmailGateLast } from './verificationOrder.js';
|
||||
|
||||
type TaskbarDeps = Parameters<typeof getTaskbarItems>[1];
|
||||
|
||||
export interface UserDetailsDeps {
|
||||
config: IConfig;
|
||||
// `db.write` backs the taskbar's first-read default row.
|
||||
clients: CardFallbackClients & {
|
||||
db: { write: (query: string, params?: unknown[]) => Promise<unknown> };
|
||||
};
|
||||
stores: TaskbarDeps['stores'] & {
|
||||
clients: CardFallbackClients;
|
||||
stores: {
|
||||
kv: Pick<SystemKVStore, 'get'>;
|
||||
team?: Pick<TeamStoreContract, 'getOrgSeat'>;
|
||||
};
|
||||
@@ -78,8 +72,8 @@ const SENSITIVE_KEYS: ReadonlySet<string> = new Set([
|
||||
]);
|
||||
|
||||
/**
|
||||
* Delete every sensitive key at any depth (`metadata` and `taskbar_items` are
|
||||
* nested). Depth-limited and cycle-safe. Runs last over a whole payload.
|
||||
* Delete every sensitive key at any depth (`metadata` is nested). Depth-limited
|
||||
* and cycle-safe. Runs last over a whole payload.
|
||||
*/
|
||||
export const scrubSensitive = (
|
||||
value: unknown,
|
||||
@@ -124,7 +118,7 @@ export const toUnixSeconds = (value: unknown): number | undefined => {
|
||||
export async function buildUserDetails(
|
||||
user: UserRow,
|
||||
deps: UserDetailsDeps,
|
||||
opts: { isUser: boolean; iconSize?: number; noIcons?: boolean },
|
||||
opts: { isUser: boolean },
|
||||
): Promise<Record<string, unknown>> {
|
||||
const { config, clients, stores, services } = deps;
|
||||
const { isUser } = opts;
|
||||
@@ -170,9 +164,6 @@ export async function buildUserDetails(
|
||||
cardFallbackDepsFrom(clients),
|
||||
)
|
||||
: false,
|
||||
desktop_bg_url: user.desktop_bg_url,
|
||||
desktop_bg_color: user.desktop_bg_color,
|
||||
desktop_bg_fit: user.desktop_bg_fit,
|
||||
is_temp: user.password === null && user.email === null,
|
||||
is_user_token: true,
|
||||
// Null until the account asks for a code; never minted here.
|
||||
@@ -185,14 +176,6 @@ export async function buildUserDetails(
|
||||
hasDevAccountAccess: !!user.metadata?.hasDevAccountAccess,
|
||||
};
|
||||
|
||||
// Not an inline literal, so a `TaskbarDeps` without `clients` still
|
||||
// accepts it.
|
||||
const taskbarDeps = {
|
||||
clients,
|
||||
stores,
|
||||
apiBaseUrl: String(config.api_base_url ?? ''),
|
||||
config,
|
||||
};
|
||||
const linkedProvider = async () => {
|
||||
if (!oidcOnly) return null;
|
||||
try {
|
||||
@@ -202,19 +185,6 @@ export async function buildUserDetails(
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const taskbarItems = async () => {
|
||||
if (!isUser) return null;
|
||||
try {
|
||||
return {
|
||||
items: await getTaskbarItems(user, taskbarDeps, {
|
||||
iconSize: opts.iconSize,
|
||||
noIcons: opts.noIcons,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { error };
|
||||
}
|
||||
};
|
||||
// The team that pays for the account; every seat restriction keys on it.
|
||||
const orgSeat = async () => {
|
||||
if (!isUser || config.teams_enabled !== true) return null;
|
||||
@@ -226,26 +196,14 @@ export async function buildUserDetails(
|
||||
};
|
||||
// Independent and each best-effort, so read together; the results land
|
||||
// below in the order the payload has always listed them.
|
||||
const [provider, taskbar, team] = await Promise.all([
|
||||
linkedProvider(),
|
||||
taskbarItems(),
|
||||
orgSeat(),
|
||||
]);
|
||||
const [provider, team] = await Promise.all([linkedProvider(), orgSeat()]);
|
||||
|
||||
if (provider) {
|
||||
const origin = (config.origin ?? '').replace(/\/$/, '');
|
||||
details.oidc_revalidate_url = `${origin}/auth/oidc/${provider}/start?flow=revalidate&user_uuid=${encodeURIComponent(user.uuid)}`;
|
||||
}
|
||||
|
||||
if (taskbar) {
|
||||
// Best-effort: the account still works without them.
|
||||
if ('error' in taskbar) {
|
||||
console.warn('[user-details] taskbar_items failed:', taskbar.error);
|
||||
details.taskbar_items = [];
|
||||
} else {
|
||||
details.taskbar_items = taskbar.items;
|
||||
}
|
||||
|
||||
if (isUser) {
|
||||
const directories: Record<string, unknown> = {};
|
||||
const nameToProp: Record<string, string> = {
|
||||
desktop_uuid: `/${user.username}/Desktop`,
|
||||
|
||||
@@ -1339,7 +1339,7 @@ async function saveEditedApp (mode) {
|
||||
// Update title
|
||||
$(`.app-title[data-uid="${uid}"]`).html(html_encode(app.title));
|
||||
// Update app link
|
||||
$(`.app-url[data-uid="${uid}"]`).html(applink(app));
|
||||
$(`.app-url[data-uid="${uid}"]`).html(html_encode(applink(app)));
|
||||
$(`.app-url[data-uid="${uid}"]`).attr('href', applink(app));
|
||||
// Update icons
|
||||
$(`.app-icon[data-uid="${uid}"]`).attr('src', html_encode(app.icon ? app.icon : './img/app.svg'));
|
||||
|
||||
@@ -38,22 +38,27 @@ window.user = null;
|
||||
}
|
||||
})();
|
||||
|
||||
// domain and APIOrigin
|
||||
if ( window.url_params.has('puter.domain') ) {
|
||||
window.domain = window.url_params.get('puter.domain');
|
||||
// domain and port are built into links and deploy URLs, so anything other
|
||||
// than a bare hostname and a numeric port is ignored
|
||||
const domainParam = window.url_params.get('puter.domain');
|
||||
if ( domainParam && /^[a-z0-9-]+(\.[a-z0-9-]+)*$/i.test(domainParam) ) {
|
||||
window.domain = domainParam;
|
||||
}
|
||||
|
||||
const portParam = window.url_params.get('puter.port');
|
||||
window.port = portParam && /^\d{1,5}$/.test(portParam) ? portParam : '';
|
||||
|
||||
// static hosting domain
|
||||
window.static_hosting_domain = 'puter.site';
|
||||
if ( window.domain === 'puter.localhost' ) {
|
||||
window.static_hosting_domain = 'site.puter.localhost';
|
||||
} else if ( window.domain && window.domain !== 'puter.com' ) {
|
||||
window.static_hosting_domain = `site.${window.domain}`;
|
||||
}
|
||||
if ( window.domain === 'puter.localhost' ) {
|
||||
window.static_hosting_domain = 'site.puter.localhost';
|
||||
} else if ( window.domain && window.domain !== 'puter.com' ) {
|
||||
window.static_hosting_domain = `site.${window.domain}`;
|
||||
}
|
||||
|
||||
// add port to static_hosting_domain if provided
|
||||
if ( window.url_params.has('puter.port') && window.url_params.get('puter.port') ) {
|
||||
window.static_hosting_domain = `${window.static_hosting_domain }:${ html_encode(window.url_params.get('puter.port'))}`;
|
||||
if ( window.port ) {
|
||||
window.static_hosting_domain = `${window.static_hosting_domain}:${window.port}`;
|
||||
}
|
||||
|
||||
// protocol
|
||||
@@ -63,12 +68,6 @@ if ( window.url_params.has('puter.protocol') && window.url_params.get('puter.pro
|
||||
window.protocol = 'http';
|
||||
}
|
||||
|
||||
// port
|
||||
window.port = '';
|
||||
if ( window.url_params.has('puter.port') && window.url_params.get('puter.port') ) {
|
||||
window.port = html_encode(window.url_params.get('puter.port'));
|
||||
}
|
||||
|
||||
// source_path
|
||||
if ( window.url_params.has('source_path') ) {
|
||||
window.source_path = window.url_params.get('source_path');
|
||||
|
||||
@@ -385,6 +385,10 @@ The `usageDetails.serviceSpeed` field reports the served speed. Billing uses the
|
||||
|
||||
### OpenAI models
|
||||
|
||||
Passing `service_tier: "priority"` selects fast service, and `service_tier: "ultrafast"` selects ultrafast service. These requests use the same prices and supported-speed selection as `serviceSpeed`. An explicit `serviceSpeed` takes precedence.
|
||||
|
||||
Input and reasoning tokens reported by a non-streaming Responses API call are billed even when its output is empty. These charges apply whether the request fails or retries another provider.
|
||||
|
||||
Fast service is available on models with a published Fast rate card. Ultrafast is available for GPT-6.1 Sol and GPT-6 Astra. Other models fall back to fast or standard. Cache and long-context rates apply to the served tier.
|
||||
|
||||
#### `temperature`
|
||||
@@ -588,6 +592,8 @@ MiniMax M3 uses Priority admission for fast service. Earlier models with an equi
|
||||
|
||||
Fast service requests Priority when the account and model are eligible. The provider can serve the request at standard speed.
|
||||
|
||||
Passing `service_tier: "auto"` selects fast service, with the same prices as `serviceSpeed: "fast"`. An explicit `serviceSpeed` takes precedence.
|
||||
|
||||
### Alibaba Cloud models
|
||||
|
||||
Models with an equivalent Prime or Fast variant select that variant for fast service. Other models use standard service.
|
||||
|
||||
@@ -32,7 +32,7 @@ Fine-tune the conversion:
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `voice` | `String` | Target ElevenLabs voice ID. Defaults to `21m00Tcm4TlvDq8ikWAM`. |
|
||||
| `model` | `String` | Voice-changer model. Defaults to `eleven_multilingual_sts_v2`. You can also use `eleven_english_sts_v2` for English-only inputs. |
|
||||
| `model` | `String` | Voice-changer model, either `eleven_multilingual_sts_v2` or `eleven_english_sts_v2` (English-only inputs). Defaults to `eleven_multilingual_sts_v2`. Any other value fails with a `field_invalid` error. |
|
||||
| `output_format` | `String` | Desired output codec and bitrate, e.g. `mp3_44100_128`, `opus_48000_64`, or `pcm_48000`. Defaults to `mp3_44100_128`. |
|
||||
| `voice_settings` | `Object \| String` | ElevenLabs voice settings payload (e.g. `{"stability":0.5,"similarity_boost":0.75}`). |
|
||||
| `remove_background_noise` | `Boolean` | Apply background noise removal. |
|
||||
|
||||
@@ -12,7 +12,7 @@ When the user adds a new domain, the dialog shows the DNS records to set at thei
|
||||
|
||||
Your app doesn't need any permission to call this method. The user makes the choice in the dialog, and your app only receives the domain they chose. Custom domains are billed to the user's Puter account, and the dialog shows the price before the user adds one.
|
||||
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs 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 and signs 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.
|
||||
|
||||
## Syntax
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ A set of key/value pairs that configure the window.
|
||||
| `is_resizable` | `Boolean` | If set to `true`, the user can resize the window. |
|
||||
| `has_head` | `Boolean` | If set to `true`, the window has a head which contains the icon and the close, minimize, and maximize buttons. |
|
||||
| `disable_parent_window` | `Boolean` | If set to `true`, the parent window is blocked until the current window is closed. |
|
||||
| `show_in_taskbar` | `Boolean` | If set to `true`, the window is represented in the taskbar. |
|
||||
| `show_in_taskbar` | `Boolean` | Deprecated. It has no effect. |
|
||||
|
||||
## Return value
|
||||
A `Promise` that resolves to a window handle object with an `id` (String) property identifying the created window. This `id` can be passed as the `window_id` argument to the `setWindow*` methods.
|
||||
@@ -50,7 +50,6 @@ A `Promise` that resolves to a window handle object with an `id` (String) proper
|
||||
is_resizable: false,
|
||||
has_head: true,
|
||||
center: true,
|
||||
show_in_taskbar: false,
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -36,12 +36,11 @@ Without `background`, Puter creates and shows the window before the app's own co
|
||||
runs, so a service app cannot avoid briefly appearing on screen.
|
||||
|
||||
A background instance stays private to your app for as long as it is hidden: it has no
|
||||
taskbar item and no running mark on its icon, and opening the app from the
|
||||
taskbar or from Puter's app list starts a separate, ordinary instance for the
|
||||
user rather than handing them the one you are talking to. It can show itself at
|
||||
any time with [`puter.ui.showWindow()`](/UI/showWindow), and from that moment it
|
||||
is an ordinary window. It takes its place in the taskbar, and the user can
|
||||
return to it, hide it, or close it like any other.
|
||||
running mark on its icon, and opening the app from Puter's app list starts a
|
||||
separate, ordinary instance for the user rather than handing them the one you
|
||||
are talking to. It can show itself at any time with
|
||||
[`puter.ui.showWindow()`](/UI/showWindow), and from that moment it is an
|
||||
ordinary window that the user can return to, hide, or close like any other.
|
||||
|
||||
A background app closes when the app that launched it closes: it was launched to
|
||||
serve that app, and the user never saw it. Once it has shown itself it keeps
|
||||
|
||||
@@ -13,6 +13,20 @@ puter.ui.showColorPicker(defaultColor)
|
||||
puter.ui.showColorPicker(options)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
#### `defaultColor` (String)
|
||||
The color to select when the color picker is opened, as a hex string such as `#3b82f6` or `#38f`.
|
||||
|
||||
#### `options` (Object)
|
||||
An object with the following properties:
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `defaultColor` | `String` | The color to select when the color picker is opened, as a hex string. The picker has no alpha, so the alpha in an 8-digit hex such as `#3b82f680` is ignored. If the value isn't a valid hex color, the picker opens on `#3b82f6`. The `defaultValue` and `default` options are accepted as aliases. If more than one is given, `defaultValue` is used, then `defaultColor`, then `default`. |
|
||||
|
||||
## Return value
|
||||
A `Promise` that resolves to the selected color as a lowercase 6-digit hex string, such as `#ff0000`. If the user closes the picker without selecting a color, the promise resolves to `null`.
|
||||
|
||||
## Examples
|
||||
|
||||
### Change the background to the picked color
|
||||
@@ -23,7 +37,9 @@ puter.ui.showColorPicker(options)
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
puter.ui.showColorPicker().then((color)=>{
|
||||
document.body.style.backgroundColor = color;
|
||||
if (color) {
|
||||
document.body.style.backgroundColor = color;
|
||||
}
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
<script>
|
||||
document.getElementById('pick-color').addEventListener('click', () => {
|
||||
puter.ui.showColorPicker().then((color) => {
|
||||
document.body.style.backgroundColor = color;
|
||||
puter.print('Selected color: ' + color);
|
||||
if (color) {
|
||||
document.body.style.backgroundColor = color;
|
||||
puter.print('Selected color: ' + color);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -159,7 +159,7 @@ The [`puter.ai.realtime()`](/AI/realtime/) SDK also applies these limits before
|
||||
|
||||
`/puterai/anthropic/v1/messages/count_tokens` has its own budget of 120 requests per minute per user, with no concurrency limit, and is not charged.
|
||||
|
||||
Chat requests accept JSON bodies up to 128 MiB (134,217,728 bytes), including `text/plain;actually=json` bodies. That covers `puter-chat-completion` calls through `/drivers/call`, which `puter.ai.chat()` uses, and POSTs to `/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages` and `/puterai/anthropic/v1/messages/count_tokens`. A body over 50 MiB needs a `Content-Length` header and a token in the `Authorization` or `x-api-key` header (or a session cookie); an `auth_token` inside the body isn't read until the body is, so it only works up to 50 MiB. Larger bodies, and bodies over 50 MiB for other drivers, return HTTP 413. One account can have up to 128 MiB of these large bodies in flight at once; past that, requests get `429` with `Retry-After`. A server handling too many large bodies at once returns `503` with `Retry-After`. Retry either after the given number of seconds. Other routes accept JSON bodies up to 50 MiB.
|
||||
Chat requests accept JSON bodies up to 128 MiB (134,217,728 bytes), including `text/plain;actually=json` bodies. That covers `puter-chat-completion` calls through `/drivers/call`, which `puter.ai.chat()` uses, and POSTs to `/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages` and `/puterai/anthropic/v1/messages/count_tokens`. A body over 50 MiB needs a `Content-Length` header and a credential that can be read before the rest of the body. That is a token in the `Authorization` or `x-api-key` header, a session cookie, or an `auth_token` that is the first field of the body, which is where Puter.js sends it. An `auth_token` after other fields isn't read until the body is, so it only works up to 50 MiB. Larger bodies, and bodies over 50 MiB for other drivers, return HTTP 413. One account can have up to 128 MiB of these large bodies in flight at once; past that, requests get `429` with `Retry-After`. A server handling too many large bodies at once returns `503` with `Retry-After`. Retry either after the given number of seconds. Other routes accept JSON bodies up to 50 MiB. A JSON body in a charset other than UTF-8 is accepted up to 1 MiB. A JSON body over 32 KiB can nest arrays and objects up to 10,000 levels deep, and deeper nesting returns HTTP 400.
|
||||
|
||||
Claude's server-executed tools are clamped so a request can't reserve an unbounded amount of credit:
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
## Credits
|
||||
|
||||
The default wallpaper is created by [Milad Fakurian](https://unsplash.com/photos/blue-orange-and-yellow-wallpaper-E8Ufcyxz514) and published on [Unsplash](https://unsplash.com/).
|
||||
|
||||
Icons by [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) under GPL-3.0 license.
|
||||
|
||||
Icons by [Iconoir](https://iconoir.com/) under MIT license.
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
"/lib/jquery.dragster.js",
|
||||
"/lib/html-entities.js",
|
||||
"/lib/timeago.min.js",
|
||||
"/lib/iro.min.js",
|
||||
"/lib/isMobile.min.js",
|
||||
"/lib/fflate-0.8.2.min.js"
|
||||
],
|
||||
|
||||
@@ -40,7 +40,6 @@ 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', stub);
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', () => ({ default: permissionDialog }));
|
||||
|
||||
@@ -18,7 +18,6 @@ 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', stub);
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
|
||||
+28
-22
@@ -32,7 +32,6 @@ import UIPrompt from './UI/UIPrompt.js';
|
||||
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 UIWindowFontPicker from './UI/UIWindowFontPicker.js';
|
||||
import UIPermissionDialog from './UI/UIPermissionDialog.js';
|
||||
import UIEnablePushDialog from './UI/UIEnablePushDialog.js';
|
||||
@@ -485,7 +484,6 @@ const ipc_listener = async (event, handled) => {
|
||||
is_resizable: event.data.options.is_resizable,
|
||||
has_head: event.data.options.has_head,
|
||||
center: event.data.options.center,
|
||||
show_in_taskbar: event.data.options.show_in_taskbar,
|
||||
iframe_srcdoc: event.data.options.content,
|
||||
parent_uuid: event.data.appInstanceID,
|
||||
});
|
||||
@@ -1150,9 +1148,9 @@ const ipc_listener = async (event, handled) => {
|
||||
if ( event.data.y !== undefined ) {
|
||||
event.data.y = parseFloat(event.data.y);
|
||||
// we don't want the window to go off the top edge of the screen
|
||||
if ( event.data.y < window.taskbar_height )
|
||||
if ( event.data.y < 0 )
|
||||
{
|
||||
event.data.y = window.taskbar_height;
|
||||
event.data.y = 0;
|
||||
}
|
||||
// we don't want the window to go off the bottom edge of the screen
|
||||
if ( event.data.y > window.innerHeight - 100 )
|
||||
@@ -1218,9 +1216,9 @@ const ipc_listener = async (event, handled) => {
|
||||
if ( event.data.y !== undefined ) {
|
||||
event.data.y = parseFloat(event.data.y);
|
||||
// we don't want the window to go off the top edge of the screen
|
||||
if ( event.data.y < window.taskbar_height )
|
||||
if ( event.data.y < 0 )
|
||||
{
|
||||
event.data.y = window.taskbar_height;
|
||||
event.data.y = 0;
|
||||
}
|
||||
// we don't want the window to go off the bottom edge of the screen
|
||||
if ( event.data.y > window.innerHeight - 100 )
|
||||
@@ -1625,26 +1623,34 @@ const ipc_listener = async (event, handled) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// set options
|
||||
if ( typeof event.data.options === 'string' ) {
|
||||
event.data.options = { defaultColor: event.data.options };
|
||||
}
|
||||
event.data.options = event.data.options ?? {};
|
||||
const options = typeof event.data.options === 'string'
|
||||
? { defaultColor: event.data.options }
|
||||
: (event.data.options ?? {});
|
||||
const requested_color = options.defaultValue ?? options.defaultColor ?? options.default;
|
||||
// The picker has no alpha, so an 8-digit hex loses its last two digits.
|
||||
// Anything still not a 3- or 6-digit hex is left out: older builds of
|
||||
// the picker fail to open on it.
|
||||
const default_color = typeof requested_color === 'string'
|
||||
? requested_color.trim().replace(/^(#?[0-9a-f]{6})[0-9a-f]{2}$/i, '$1')
|
||||
: '';
|
||||
|
||||
// Clear window_options for security reasons
|
||||
event.data.options.window_options = {};
|
||||
// The same picker puter.js shows outside Puter, so an app gets one
|
||||
// answer shape everywhere: a 6-digit hex string, or null on cancel.
|
||||
const picker = document.createElement('puter-color-picker');
|
||||
if ( /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(default_color) ) picker.setAttribute('default-color', default_color);
|
||||
const selected_color = await new Promise((resolve) => {
|
||||
picker.addEventListener('response', (e) => resolve(e.detail ?? null), { once: true });
|
||||
document.body.appendChild(picker);
|
||||
picker.open();
|
||||
});
|
||||
// Older builds leave the element behind when Escape closes it.
|
||||
picker.remove();
|
||||
|
||||
// Set app as parent window of the font picker window
|
||||
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
|
||||
|
||||
// Open color picker
|
||||
let selected_color = await UIWindowColorPicker(event.data.options);
|
||||
|
||||
// Send selected color to requester window
|
||||
target_iframe.contentWindow.postMessage({
|
||||
// The app may have closed while the picker was up.
|
||||
target_iframe.contentWindow?.postMessage({
|
||||
msg: 'colorPicked',
|
||||
original_msg_id: msg_id,
|
||||
color: selected_color ? selected_color.color : undefined,
|
||||
color: selected_color,
|
||||
}, '*');
|
||||
$(target_iframe).get(0).focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
@@ -41,7 +41,6 @@ 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);
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// @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 } = vi.hoisted(() => ({ stub: () => ({ default: () => {} }) }));
|
||||
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/UIWindowEmailConfirmationRequired.js', stub);
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
vi.mock('./UI/UIEnablePushDialog.js', stub);
|
||||
vi.mock('./UI/UIWindowSaveAccount.js', stub);
|
||||
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(),
|
||||
}));
|
||||
|
||||
// Stands in for puter.js's <puter-color-picker>, which the GUI page gets from
|
||||
// the SDK: it records how it was opened, and the test answers for the user.
|
||||
const opened = [];
|
||||
class FakeColorPicker extends HTMLElement {
|
||||
open () {
|
||||
opened.push(this);
|
||||
}
|
||||
answer (color) {
|
||||
this.dispatchEvent(new CustomEvent('response', { detail: color }));
|
||||
}
|
||||
}
|
||||
customElements.define('puter-color-picker', FakeColorPicker);
|
||||
|
||||
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(() => {
|
||||
opened.length = 0;
|
||||
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 = (options) =>
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: { appInstanceID: 'inst-1', env: 'app', msg: 'showColorPicker', uuid: 'cb-1', options },
|
||||
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 === 'colorPicked');
|
||||
|
||||
describe('showColorPicker', () => {
|
||||
it.each([
|
||||
['a string', '#abcdef'],
|
||||
['defaultColor', { defaultColor: '#abcdef' }],
|
||||
['the legacy default alias', { default: '#abcdef' }],
|
||||
['the legacy defaultValue alias', { defaultValue: '#abcdef' }],
|
||||
['an 8-digit hex, without its alpha', '#abcdef80'],
|
||||
])('opens the picker on the color given as %s', async (_, options) => {
|
||||
request(options);
|
||||
await settle();
|
||||
expect(opened).toHaveLength(1);
|
||||
expect(opened[0].getAttribute('default-color')).toBe('#abcdef');
|
||||
expect(opened[0].isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no color', undefined],
|
||||
['a color that isn\'t hex', 'red'],
|
||||
['a malformed hex', '#abcd'],
|
||||
])('leaves the picker\'s own default when the app gives %s', async (_, options) => {
|
||||
request(options);
|
||||
await settle();
|
||||
expect(opened[0].hasAttribute('default-color')).toBe(false);
|
||||
});
|
||||
|
||||
it('replies with the picked color', async () => {
|
||||
request('#abcdef');
|
||||
await settle();
|
||||
opened[0].answer('#123456');
|
||||
await settle();
|
||||
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: '#123456' }]);
|
||||
expect(opened[0].isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('replies null when the user cancels', async () => {
|
||||
request();
|
||||
await settle();
|
||||
opened[0].answer(null);
|
||||
await settle();
|
||||
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: null }]);
|
||||
expect(opened[0].isConnected).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -69,6 +69,7 @@ beforeAll(async () => {
|
||||
[sessionToken]: { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-session-user': { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-other-user': { uuid: otherUser, username: 'other-user' },
|
||||
'app-token-subscriber': { uuid: sessionUser, username: 'session-user', subscribed: true },
|
||||
};
|
||||
// The SDK on a sibling subdomain sends credentialed cross-origin requests.
|
||||
app.use(['/whoami', '/profile', '/rao'], (req, res, next) => {
|
||||
@@ -513,6 +514,81 @@ describe('embedded app browser', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('offers Add credits to an account with a plan, and frames the top-up over the page', async () => {
|
||||
const context = await menuContext('app-token-subscriber');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
const item = page.locator('puter-user-menu .add-credits');
|
||||
await item.waitFor();
|
||||
expect(await item.textContent()).toBe('Add credits');
|
||||
// Under Usage, in the same row style as the links around it.
|
||||
expect(await page.locator('puter-user-menu .usage + .add-credits').count()).toBe(1);
|
||||
expect(await item.evaluate(el => getComputedStyle(el).height))
|
||||
.toBe(await page.locator('puter-user-menu .feedback').evaluate(el => getComputedStyle(el).height));
|
||||
|
||||
await item.click();
|
||||
const frame = page.locator('dialog.puter-popup-frame iframe');
|
||||
await frame.waitFor({ state: 'attached' });
|
||||
expect(await frame.getAttribute('src')).toBe(`${origin}/embed/top-up#user=${sessionUser}`);
|
||||
expect(await frame.getAttribute('allow')).toBe('payment; otp-credentials');
|
||||
expect(await page.locator('puter-user-menu .menu').isHidden()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns keyboard focus to the account button when Add credits is chosen', async () => {
|
||||
const context = await menuContext('app-token-subscriber');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('puter-user-menu .add-credits').waitFor();
|
||||
await page.locator('puter-user-menu .add-credits').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('dialog.puter-popup-frame iframe').waitFor({ state: 'attached' });
|
||||
const focused = () => page.evaluate(() => document.activeElement.shadowRoot?.activeElement?.className ?? document.activeElement.tagName);
|
||||
expect(await focused()).toBe('avatar');
|
||||
|
||||
// The dialog hands the focus back when it closes.
|
||||
const fromFrame = (state) => page.evaluate(([guiOrigin, frameState]) => {
|
||||
const source = document.querySelector('dialog.puter-popup-frame iframe').contentWindow;
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'puterPopupFrame', state: frameState }, origin: guiOrigin, source,
|
||||
}));
|
||||
}, [origin, state]);
|
||||
await fromFrame('ready');
|
||||
expect(await page.locator('dialog.puter-popup-frame').evaluate(el => el.open)).toBe(true);
|
||||
await fromFrame('closed');
|
||||
await page.locator('dialog.puter-popup-frame').waitFor({ state: 'detached' });
|
||||
expect(await focused()).toBe('avatar');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves Add credits out of the menu of an account without a plan', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
await page.locator('puter-user-menu .usage').waitFor();
|
||||
expect(await page.locator('puter-user-menu .add-credits').isHidden()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes the account menu when Tab leaves it', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import UIWindow from '../UIWindow.js';
|
||||
import {
|
||||
openChangeEmailDialog,
|
||||
openChangeLanguageDialog,
|
||||
openChangePasswordDialog,
|
||||
openChangeUsernameDialog,
|
||||
openCreateTokenDialog,
|
||||
@@ -141,6 +142,21 @@ const TabAccount = {
|
||||
h += '</div>';
|
||||
}
|
||||
|
||||
// Language card
|
||||
const language = window.listSupportedLanguages().find((lang) => lang.code === window.locale);
|
||||
h += '<div class="dashboard-card dashboard-settings-card">';
|
||||
h += '<div class="dashboard-settings-card-content">';
|
||||
h += '<div class="dashboard-settings-card-icon">';
|
||||
h += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';
|
||||
h += '</div>';
|
||||
h += '<div class="dashboard-settings-card-info">';
|
||||
h += `<strong>${i18n('language')}</strong>`;
|
||||
h += `<span>${html_encode(language?.name ?? window.locale)}</span>`;
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
h += `<button class="button change-language">${i18n('change_language')}</button>`;
|
||||
h += '</div>';
|
||||
|
||||
// API token card
|
||||
h += '<div class="dashboard-card dashboard-settings-card">';
|
||||
h += '<div class="dashboard-settings-card-content">';
|
||||
@@ -213,6 +229,9 @@ const TabAccount = {
|
||||
$el_window.find('.dashboard-section-account .change-email').on('click', function () {
|
||||
openChangeEmailDialog(dialogOptions(this));
|
||||
});
|
||||
$el_window.find('.dashboard-section-account .change-language').on('click', function () {
|
||||
openChangeLanguageDialog(dialogOptions(this));
|
||||
});
|
||||
$el_window.find('.dashboard-section-account .copy-auth-token').on('click', function () {
|
||||
openCreateTokenDialog({ ...dialogOptions(this), $sessionsParent: $el_window });
|
||||
});
|
||||
@@ -251,8 +270,6 @@ const TabAccount = {
|
||||
function showProfilePicture (picture) {
|
||||
const url = picture ?? window.icons['profile.svg'];
|
||||
$('.profile-pic').css('background-image', `url(${ html_encode(url) })`);
|
||||
$('.profile-image').css('background-image', `url(${ html_encode(url) })`);
|
||||
$('.profile-image').toggleClass('profile-image-has-picture', !! picture);
|
||||
}
|
||||
// A save started after another one owns the avatar and the hint; the
|
||||
// earlier one's answer must not put its picture (or a failure) back.
|
||||
|
||||
@@ -50,7 +50,7 @@ import { parent_path_for, parse_shared_path, shared_crumbs_for, shared_uids_from
|
||||
import resolve_shared_item from '../../helpers/resolveSharedItem.js';
|
||||
import { is_owned_by_me } from '../../helpers/pathOwner.js';
|
||||
import parse_item_metadata from '../../helpers/parseItemMetadata.js';
|
||||
import { compareSharers, filterBySharer, fitSharedByWidth, sharedByCellHtml, sharerFilterHtml, summarizeSharers } from './sharedBy.js';
|
||||
import { compareSharers, filterBySharer, fitSharedByWidth, sharedByCellHtml, sharerFilterHtml, sharerOf, summarizeSharers } from './sharedBy.js';
|
||||
import { paintAvatars } from '../../helpers/profilePictures.js';
|
||||
|
||||
const { html_encode, SelectionArea } = window;
|
||||
@@ -2983,7 +2983,7 @@ const TabFiles = {
|
||||
// Rebuilding the chips drops focus and scroll; carry both across.
|
||||
const focused = $bar.find('.sharer-chip:focus').attr('data-sharer');
|
||||
const scrollLeft = bar.scrollLeft;
|
||||
const html = sharerFilterHtml(sharers, this.sharerFilter);
|
||||
const html = sharerFilterHtml(sharers, this.sharerFilter, rows.filter((row) => sharerOf(row)).length);
|
||||
$bar.html(html).prop('hidden', ! html);
|
||||
paintAvatars(bar);
|
||||
bar.scrollLeft = scrollLeft;
|
||||
@@ -6011,8 +6011,10 @@ const TabFiles = {
|
||||
shared_with_me: true,
|
||||
share_mode: share.mode,
|
||||
shared_by: share.issuer,
|
||||
shared_by_all: share.issuers,
|
||||
owner: share.owner,
|
||||
holder_team: share.holderTeam,
|
||||
also_team_share: share.alsoHeldByTeam,
|
||||
}));
|
||||
|
||||
const linked = this.pendingSharedLinks ?? [];
|
||||
|
||||
@@ -1667,6 +1667,34 @@ describe('TabFiles listSharedView', () => {
|
||||
});
|
||||
expect(rows[1].holder_team).toEqual(team);
|
||||
});
|
||||
|
||||
it('merges the grants on one item into a single row', async () => {
|
||||
const team = { uid: 't-1', name: 'Acme', handle: 'acme' };
|
||||
const grant = { entryUid: 'u-1', name: 'a.txt', path: '/bob/u-1/a.txt', isDir: false, owner: 'bob' };
|
||||
window.puter = {
|
||||
fs: {
|
||||
listShared: vi.fn(async () => ({
|
||||
items: [
|
||||
{ ...grant, mode: 'read', issuer: 'bob', holderTeam: team },
|
||||
{ ...grant, mode: 'manage', issuer: 'bob' },
|
||||
{ ...grant, mode: 'read', issuer: 'carol' },
|
||||
],
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
const rows = await TabFiles.listSharedView();
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({
|
||||
uid: 'u-1',
|
||||
share_mode: 'manage',
|
||||
shared_by: 'bob',
|
||||
shared_by_all: ['bob', 'carol'],
|
||||
also_team_share: true,
|
||||
});
|
||||
expect(rows[0].holder_team).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TabFiles path field', () => {
|
||||
|
||||
@@ -296,25 +296,6 @@ const TabHome = {
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
// Open Desktop card (spans full width, links to the desktop interface)
|
||||
h +=
|
||||
'<a href="/desktop" target="_blank" rel="noopener" class="bento-card bento-desktop allow-native-ctxmenu">';
|
||||
h +=
|
||||
'<div class="bento-card-fancy-icon bento-card-fancy-icon-desktop">';
|
||||
h +=
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>';
|
||||
h += '</div>';
|
||||
h += '<div class="bento-card-fancy-text">';
|
||||
h += `<h2>${i18n('open_desktop')}</h2>`;
|
||||
h += '<span class="bento-card-fancy-subtitle">';
|
||||
h +=
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
|
||||
h += i18n('open_desktop_hint');
|
||||
h += '</span>';
|
||||
h += '</div>';
|
||||
h += '<span class="bento-desktop-arrow">›</span>';
|
||||
h += '</a>';
|
||||
|
||||
h += '</div>';
|
||||
return h;
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
import { formatCount, formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
|
||||
import { isOrgSeat } from './orgSeat.js';
|
||||
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { addonCreditsBudget, addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { getMonthlyUsage, getStorageSpace } from './usageRequests.js';
|
||||
|
||||
// Whether the server reported credits — decides whether the usage surfaces
|
||||
@@ -67,7 +67,7 @@ const TabUsage = {
|
||||
</div>
|
||||
<div class="driver-usage-container" style="margin-top: 30px;">
|
||||
<div class="driver-usage-header">
|
||||
<h3 style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('Resources')}</h3>
|
||||
<h3 style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('monthly_credits_title')}</h3>
|
||||
<div style="font-size: 13px; margin-bottom: 3px; opacity:0.85;">
|
||||
<span class="usage-progbar-percent">--%</span>
|
||||
<span> · </span>
|
||||
@@ -77,10 +77,22 @@ const TabUsage = {
|
||||
<div class="usage-progbar-wrapper">
|
||||
<div class="usage-progbar" style="width: 0;"></div>
|
||||
</div>
|
||||
<p class="usage-addon-credits" style="display: none;">
|
||||
<span class="usage-addon-left"></span>
|
||||
<span class="usage-addon-note">· ${i18n('addon_credits_note')}</span>
|
||||
</p>
|
||||
<div class="usage-addon" style="display: none;">
|
||||
<div class="driver-usage-header">
|
||||
<h3 id="usage-addon-title" style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('addon_credits')}</h3>
|
||||
<div style="font-size: 13px; margin-bottom: 3px; opacity:0.85;">
|
||||
<span class="usage-addon-percent">--%</span>
|
||||
<span> · </span>
|
||||
${i18n('used_of', { used: '<span class="usage-addon-used">--</span>', available: '<span class="usage-addon-capacity">--</span>' }, false)}
|
||||
</div>
|
||||
</div>
|
||||
<div class="usage-progbar-wrapper" role="progressbar" aria-labelledby="usage-addon-title" aria-valuemin="0" aria-valuemax="100">
|
||||
<div class="usage-addon-bar" style="width: 0;"></div>
|
||||
</div>
|
||||
<p class="usage-addon-credits">
|
||||
<span class="usage-addon-note">${i18n('addon_credits_note')}</span>
|
||||
</p>
|
||||
</div>
|
||||
<h3 style="margin:15px 0 10px 0; font-size: 14px; font-weight: 500;">${i18n('usage_details')}</h3>
|
||||
<div class="driver-usage-details-content visible">
|
||||
</div>
|
||||
@@ -330,9 +342,20 @@ async function update_usage_details ($el_window) {
|
||||
'background-color': window.usage_bar_color(budget.barPercent),
|
||||
});
|
||||
|
||||
$('.usage-addon-credits').toggle(addonLeft !== null);
|
||||
if ( addonLeft !== null ) {
|
||||
$('.usage-addon-left').html(i18n('addon_credits_available', { amount: amount(addonLeft) }));
|
||||
// Its own meter under the monthly one, for an account that has ever had any.
|
||||
const addon = addonCreditsBudget(res.allowanceInfo);
|
||||
$('.usage-addon').toggle(addon !== null);
|
||||
if ( addon !== null ) {
|
||||
$('.usage-addon-used').html(amount(addon.used));
|
||||
$('.usage-addon-capacity').html(amount(addon.capacity));
|
||||
$('.usage-addon-percent').html(`${addon.percent}%`);
|
||||
$('.usage-addon-bar').css({
|
||||
width: `${addon.barPercent}%`,
|
||||
'background-color': window.usage_bar_color(addon.barPercent),
|
||||
}).parent().attr({
|
||||
'aria-valuenow': addon.percent,
|
||||
'aria-valuetext': `${addon.percent}%`,
|
||||
});
|
||||
}
|
||||
|
||||
// Store raw data for sorting
|
||||
|
||||
@@ -25,6 +25,7 @@ import check_password_strength from '../../helpers/checkPasswordStrength.js';
|
||||
import create_access_token from '../../helpers/createAccessToken.js';
|
||||
import postUserProtected from '../../helpers/postUserProtected.js';
|
||||
import update_username_in_gui from '../../helpers/updateUsernameInGui.js';
|
||||
import changeLanguage from '../../i18n/i18nChangeLanguage.js';
|
||||
import UIWindowManageSessions from '../UIWindowManageSessions.js';
|
||||
import UIDashboardFormDialog, { copyRowHtml } from './UIDashboardFormDialog.js';
|
||||
|
||||
@@ -119,6 +120,42 @@ export function openEditProfileDialog ({ onSave, ...opts } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the language Puter is shown in, then reloads the page in it.
|
||||
*
|
||||
* @param {AccountDialogOptions} [opts]
|
||||
*/
|
||||
export function openChangeLanguageDialog (opts = {}) {
|
||||
return UIDashboardFormDialog({
|
||||
...opts,
|
||||
title: t('change_language'),
|
||||
submitLabel: t('save'),
|
||||
fields: [
|
||||
{
|
||||
name: 'language',
|
||||
type: 'select',
|
||||
label: i18n('language'),
|
||||
value: window.locale,
|
||||
options: window.listSupportedLanguages().map((lang) => ({
|
||||
value: lang.code,
|
||||
label: html_encode(lang.name),
|
||||
})),
|
||||
},
|
||||
],
|
||||
async onSubmit (dialog) {
|
||||
const { language } = dialog.values();
|
||||
if ( language === window.locale ) {
|
||||
dialog.close();
|
||||
return;
|
||||
}
|
||||
// On success the page reloads, so the dialog stays in progress.
|
||||
if ( ! await changeLanguage(language) ) {
|
||||
dialog.setStatus(t('language_save_failed'), { field: 'language' });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the signed-in user's username.
|
||||
*
|
||||
|
||||
@@ -293,6 +293,57 @@ describe('create API token', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('change language', () => {
|
||||
beforeEach(() => {
|
||||
window.locale = 'en';
|
||||
window.listSupportedLanguages = () => [
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'de', name: 'Deutsch' },
|
||||
{ code: 'ja', name: '日本語' },
|
||||
];
|
||||
window.mutate_user_preferences = vi.fn();
|
||||
globalThis.puter.kv = { set: vi.fn(async () => true) };
|
||||
});
|
||||
|
||||
it('lists every language by its own name, with the current one selected', () => {
|
||||
dialogs.openChangeLanguageDialog();
|
||||
const options = field('language').find('option').map((_, el) => [[el.value, el.textContent]]).get();
|
||||
expect(options).toEqual([['en', 'English'], ['de', 'Deutsch'], ['ja', '日本語']]);
|
||||
expect(field('language').val()).toBe('en');
|
||||
});
|
||||
|
||||
it('closes without saving when the language is unchanged', async () => {
|
||||
dialogs.openChangeLanguageDialog();
|
||||
|
||||
await submitWith({ language: 'en' });
|
||||
|
||||
expect(puter.kv.set).not.toHaveBeenCalled();
|
||||
expect(isOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it('saves the picked language to the account', async () => {
|
||||
dialogs.openChangeLanguageDialog();
|
||||
|
||||
await submitWith({ language: 'de' });
|
||||
|
||||
expect(puter.kv.set).toHaveBeenCalledWith('user_preferences.language', 'de');
|
||||
expect(window.mutate_user_preferences).toHaveBeenCalledWith({ language: 'de' });
|
||||
expect(status()).toBe('');
|
||||
});
|
||||
|
||||
it('stays open with an error when the save fails', async () => {
|
||||
puter.kv.set.mockRejectedValue(new Error('offline'));
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
dialogs.openChangeLanguageDialog();
|
||||
|
||||
await submitWith({ language: 'de' });
|
||||
|
||||
expect(window.mutate_user_preferences).not.toHaveBeenCalled();
|
||||
expect(status()).toBe('language_save_failed');
|
||||
expect(isOpen()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete account', () => {
|
||||
it('asks a temporary account to type confirm', async () => {
|
||||
// What the server sends for a temporary account: no password, so `oidc_only` too.
|
||||
|
||||
@@ -75,8 +75,7 @@ async function UIDashboard (options) {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
options = options ?? {};
|
||||
|
||||
// Mark dashboard mode on <body> so window chrome can adapt — e.g. app
|
||||
// windows keep their minimize button even though fullpage-mode hides it.
|
||||
// Mark dashboard mode on <body> so window chrome and notifications can adapt.
|
||||
$('body').addClass('dashboard-mode');
|
||||
|
||||
// Create mutable tabs array from built-in tabs
|
||||
|
||||
@@ -109,10 +109,9 @@ const count_label = (count) => (count === 1
|
||||
: i18n('items_count_other', { count }));
|
||||
|
||||
/**
|
||||
* A responsive, from-scratch sharing modal for the Dashboard's Files tab.
|
||||
* Unlike UIWindowShare (which spawns a desktop UIWindow), this renders a
|
||||
* self-contained overlay that behaves as a centered card on desktop and a
|
||||
* bottom sheet on mobile, styled with the dashboard's design tokens.
|
||||
* A responsive sharing modal for the Dashboard's Files tab: a self-contained
|
||||
* overlay that behaves as a centered card on desktop and a bottom sheet on
|
||||
* mobile, styled with the dashboard's design tokens.
|
||||
*
|
||||
* Shares one item or a whole selection. With several items the access list is
|
||||
* one row per person folded across them ({@link aggregateShares}), so every
|
||||
@@ -120,10 +119,9 @@ const count_label = (count) => (count === 1
|
||||
* rather than a chore repeated per file. A person who holds only some of the
|
||||
* selection says so, and can be extended to the rest in one click.
|
||||
*
|
||||
* Feature-equivalent to UIWindowShare: grant access by email or username,
|
||||
* list who has access (owner, direct grants, grants inherited from an
|
||||
* ancestor folder), change a grant's mode, and revoke — with the revoke
|
||||
* confirmation inlined into the row instead of a stacked alert window.
|
||||
* Grants access by email or username, lists who has access (owner, direct
|
||||
* grants, grants inherited from an ancestor folder), changes a grant's mode,
|
||||
* and revokes, with the revoke confirmation inlined into the row.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {Array<Object>} [opts.items] - The items to share, each
|
||||
|
||||
@@ -221,7 +221,7 @@ describe('aggregateShares', () => {
|
||||
|
||||
it('falls back to the handle, then the uid, for an unnamed team', () => {
|
||||
// Whatever team_label says, so a team reads the same here as it does
|
||||
// in the desktop dialog's access list.
|
||||
// in the recipient suggestions.
|
||||
const named = (team) => aggregateShares(['/me/a'], new Map([
|
||||
['/me/a', [grant(null, 'read', { holderTeam: team })]],
|
||||
]))[0].name;
|
||||
|
||||
@@ -22,9 +22,10 @@
|
||||
|
||||
import { avatarHue, avatarInitial } from '../../helpers/shareAvatar.js';
|
||||
import { avatarUserAttr } from '../../helpers/profilePictures.js';
|
||||
import { intlLocale } from '../../i18n/intlLocale.js';
|
||||
|
||||
/**
|
||||
* @typedef {{ shared_by?: string | null, owner?: string | null }} SharedRow
|
||||
* @typedef {{ shared_by?: string | null, shared_by_all?: string[], owner?: string | null }} SharedRow
|
||||
* @typedef {{ name: string, count: number }} Sharer
|
||||
*/
|
||||
|
||||
@@ -37,6 +38,19 @@ import { avatarUserAttr } from '../../helpers/profilePictures.js';
|
||||
*/
|
||||
export const sharerOf = (row) => row?.shared_by || row?.owner || '';
|
||||
|
||||
/**
|
||||
* Everyone who shared a row with the user, `sharerOf` first. More than one
|
||||
* when the item was granted by several people.
|
||||
*
|
||||
* @param {SharedRow} [row]
|
||||
* @returns {string[]} usernames
|
||||
*/
|
||||
export const sharersOf = (row) => {
|
||||
const first = sharerOf(row);
|
||||
if ( ! row?.shared_by_all?.length ) return first ? [first] : [];
|
||||
return [...new Set([first, ...row.shared_by_all])].filter(Boolean);
|
||||
};
|
||||
|
||||
/**
|
||||
* Everyone who shared something in `rows`, with how many items each, most
|
||||
* items first and ties by name.
|
||||
@@ -47,8 +61,7 @@ export const sharerOf = (row) => row?.shared_by || row?.owner || '';
|
||||
export const summarizeSharers = (rows) => {
|
||||
const counts = new Map();
|
||||
for ( const row of rows ) {
|
||||
const name = sharerOf(row);
|
||||
if ( name ) counts.set(name, (counts.get(name) ?? 0) + 1);
|
||||
for ( const name of sharersOf(row) ) counts.set(name, (counts.get(name) ?? 0) + 1);
|
||||
}
|
||||
return [...counts]
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
@@ -56,7 +69,8 @@ export const summarizeSharers = (rows) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* The rows `sharer` shared; every row when `sharer` is empty.
|
||||
* The rows `sharer` shared, each shown as shared by them; every row when
|
||||
* `sharer` is empty.
|
||||
*
|
||||
* @template {SharedRow} T
|
||||
* @param {T[]} rows
|
||||
@@ -64,7 +78,9 @@ export const summarizeSharers = (rows) => {
|
||||
* @returns {T[]}
|
||||
*/
|
||||
export const filterBySharer = (rows, sharer) => (sharer
|
||||
? rows.filter((row) => sharerOf(row) === sharer)
|
||||
? rows
|
||||
.filter((row) => sharersOf(row).includes(sharer))
|
||||
.map((row) => (sharerOf(row) === sharer ? row : { ...row, shared_by: sharer }))
|
||||
: rows);
|
||||
|
||||
/**
|
||||
@@ -80,6 +96,21 @@ export const compareSharers = (a, b) => compareNames(sharerOf(a), sharerOf(b));
|
||||
// one per call, which made sorting a large Shared listing over 20x slower.
|
||||
const compareNames = new Intl.Collator(undefined, { sensitivity: 'base' }).compare;
|
||||
|
||||
/**
|
||||
* Names joined the way the user's language lists them ("ann and bob").
|
||||
*
|
||||
* @param {string[]} names
|
||||
* @returns {string}
|
||||
*/
|
||||
const listNames = (names) => {
|
||||
if ( names.length === 1 ) return names[0];
|
||||
try {
|
||||
return new Intl.ListFormat(intlLocale(window.locale ?? 'en'), { type: 'conjunction' }).format(names);
|
||||
} catch {
|
||||
return names.join(', ');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The "Shared by" column's width beside an auto-width name column: `width`,
|
||||
* held to 40% of the `room` the two split so the name keeps the larger part,
|
||||
@@ -102,15 +133,16 @@ export const fitSharedByWidth = (width, room) => Math.max(60, Math.min(width, Ma
|
||||
const avatarHtml = (name, className) => `<span class="${className}" style="--share-avatar-hue: ${avatarHue(name)}"${avatarUserAttr(name)} aria-hidden="true">${window.html_encode(avatarInitial(name))}</span>`;
|
||||
|
||||
/**
|
||||
* Tooltip for a row's sharer, naming the owner too when someone else re-shared it.
|
||||
* Tooltip for a row's sharers, naming the owner too when none of them owns it.
|
||||
*
|
||||
* @param {SharedRow} row
|
||||
* @returns {string} plain text
|
||||
*/
|
||||
export const sharedByTitle = (row) => {
|
||||
const username = sharerOf(row);
|
||||
if ( ! username ) return '';
|
||||
return row.owner && row.owner !== username
|
||||
const sharers = sharersOf(row);
|
||||
if ( sharers.length === 0 ) return '';
|
||||
const username = listNames(sharers);
|
||||
return row.owner && ! sharers.includes(row.owner)
|
||||
? i18n('shared_by_user_owned_by', { username, owner: row.owner }, false)
|
||||
: i18n('shared_by_user', { username }, false);
|
||||
};
|
||||
@@ -137,11 +169,11 @@ export const sharedByCellHtml = (row) => {
|
||||
*
|
||||
* @param {Sharer[]} sharers - From summarizeSharers
|
||||
* @param {string | null} active - The sharer filtered to, or null for everyone
|
||||
* @param {number} total - Items anyone shared; an item counts once however many shared it
|
||||
* @returns {string} markup
|
||||
*/
|
||||
export const sharerFilterHtml = (sharers, active) => {
|
||||
export const sharerFilterHtml = (sharers, active, total) => {
|
||||
if ( sharers.length < 2 ) return '';
|
||||
const total = sharers.reduce((sum, sharer) => sum + sharer.count, 0);
|
||||
const chip = (value, inner, count, title) => {
|
||||
const pressed = (active ?? '') === value;
|
||||
return `<button type="button" class="sharer-chip${pressed ? ' active' : ''}" data-sharer="${window.html_encode(value)}" aria-pressed="${pressed}"${title ? ` title="${window.html_encode(title)}"` : ''}>`
|
||||
|
||||
@@ -40,6 +40,13 @@ const {
|
||||
} = await import('./sharedBy.js');
|
||||
|
||||
const row = (shared_by, owner = shared_by, name = 'f') => ({ shared_by, owner, name });
|
||||
// An item granted by more than one person: `shared_by` holds the strongest grant's.
|
||||
const multiRow = (shared_by_all, owner = shared_by_all[0], name = 'f') => ({
|
||||
shared_by: shared_by_all[0],
|
||||
shared_by_all,
|
||||
owner,
|
||||
name,
|
||||
});
|
||||
|
||||
describe('sharerOf', () => {
|
||||
it('names whoever granted the share', () => {
|
||||
@@ -74,6 +81,13 @@ describe('summarizeSharers', () => {
|
||||
it('skips rows that name nobody', () => {
|
||||
expect(summarizeSharers([{}, row('ann')])).toEqual([{ name: 'ann', count: 1 }]);
|
||||
});
|
||||
|
||||
it('counts an item for everyone who shared it', () => {
|
||||
expect(summarizeSharers([multiRow(['bob', 'ann']), row('ann')])).toEqual([
|
||||
{ name: 'ann', count: 2 },
|
||||
{ name: 'bob', count: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterBySharer', () => {
|
||||
@@ -83,6 +97,20 @@ describe('filterBySharer', () => {
|
||||
expect(filterBySharer(rows, 'ann').map((r) => r.name)).toEqual(['a', 'c']);
|
||||
});
|
||||
|
||||
it('keeps an item for each person who shared it', () => {
|
||||
const shared = [multiRow(['bob', 'ann'], 'ann', 'both'), row('cy', 'cy', 'c')];
|
||||
expect(filterBySharer(shared, 'ann').map((r) => r.name)).toEqual(['both']);
|
||||
expect(filterBySharer(shared, 'bob').map((r) => r.name)).toEqual(['both']);
|
||||
});
|
||||
|
||||
it('shows a kept item as shared by the person filtered to', () => {
|
||||
const [both, own] = filterBySharer([multiRow(['bob', 'ann'], 'ann', 'both'), row('ann', 'ann', 'own')], 'ann');
|
||||
expect(sharerOf(both)).toBe('ann');
|
||||
expect(sharedByCellHtml(both)).toContain('<span class="item-shared-by-name">ann</span>');
|
||||
expect(sharedByTitle(both)).toBe('shared_by_user:ann and bob');
|
||||
expect(sharerOf(own)).toBe('ann');
|
||||
});
|
||||
|
||||
it('keeps everything without a filter', () => {
|
||||
expect(filterBySharer(rows, null)).toBe(rows);
|
||||
expect(filterBySharer(rows, '')).toBe(rows);
|
||||
@@ -123,6 +151,11 @@ describe('sharedByTitle', () => {
|
||||
it('names the owner too when someone else re-shared it', () => {
|
||||
expect(sharedByTitle(row('ann', 'bob'))).toBe('shared_by_user_owned_by:ann,bob');
|
||||
});
|
||||
|
||||
it('names everyone who shared the item', () => {
|
||||
expect(sharedByTitle(multiRow(['bob', 'ann'], 'ann'))).toBe('shared_by_user:bob and ann');
|
||||
expect(sharedByTitle(multiRow(['bob', 'cy'], 'ann'))).toBe('shared_by_user_owned_by:bob and cy,ann');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sharedByCellHtml', () => {
|
||||
@@ -155,7 +188,7 @@ describe('sharerFilterHtml', () => {
|
||||
});
|
||||
|
||||
it('leads with Everyone, counting every item', () => {
|
||||
const h = sharerFilterHtml([{ name: 'bob', count: 2 }, { name: 'ann', count: 1 }], null);
|
||||
const h = sharerFilterHtml([{ name: 'bob', count: 2 }, { name: 'ann', count: 1 }], null, 3);
|
||||
const chips = h.match(/<button[^>]*>/g);
|
||||
expect(chips).toHaveLength(3);
|
||||
expect(chips[0]).toContain('data-sharer=""');
|
||||
@@ -165,6 +198,11 @@ describe('sharerFilterHtml', () => {
|
||||
expect(h).toContain('data-avatar-user="bob"');
|
||||
});
|
||||
|
||||
it('counts an item shared by two people once under Everyone', () => {
|
||||
const h = sharerFilterHtml([{ name: 'ann', count: 2 }, { name: 'bob', count: 1 }], null, 2);
|
||||
expect(h).toContain('shared_filter_everyone:</span><span class="sharer-chip-count">2</span>');
|
||||
});
|
||||
|
||||
it('presses the active sharer only', () => {
|
||||
const h = sharerFilterHtml([{ name: 'bob', count: 2 }, { name: 'ann', count: 1 }], 'ann');
|
||||
const pressed = h.match(/<button[^>]*aria-pressed="true"[^>]*>/g);
|
||||
|
||||
@@ -30,8 +30,8 @@ export const meterPercent = (share) => (share < 100 ? Math.min(99, Math.round(sh
|
||||
|
||||
/**
|
||||
* @typedef {Object} UsageBudget
|
||||
* @property {number} used - Allowance-charged spend, in the server's units.
|
||||
* @property {number} capacity - The monthly plan allowance.
|
||||
* @property {number} used - Spend charged to it, in the server's units.
|
||||
* @property {number} capacity - What the meter is out of: the monthly plan allowance, or the add-on credit bought.
|
||||
* @property {number} percent - `used` as a whole-number share of `capacity`.
|
||||
* @property {number} barPercent - The share clamped to 0-100, for a bar width.
|
||||
*/
|
||||
@@ -83,6 +83,28 @@ export const addonCreditsRemaining = (allowanceInfo) => {
|
||||
return Math.max(0, purchased - nonNegative(addons.consumedPurchaseCredits));
|
||||
};
|
||||
|
||||
/**
|
||||
* The add-on credit meter: what has been spent of all the add-on credit the
|
||||
* account ever bought. Null when it has never had any, as there is no pool
|
||||
* to meter.
|
||||
*
|
||||
* @param {Object | null | undefined} allowanceInfo
|
||||
* @returns {UsageBudget | null}
|
||||
*/
|
||||
export const addonCreditsBudget = (allowanceInfo) => {
|
||||
const left = addonCreditsRemaining(allowanceInfo);
|
||||
if ( left === null ) return null;
|
||||
const capacity = nonNegative(allowanceInfo.addons.purchasedCredits);
|
||||
const used = capacity - left;
|
||||
const share = (used / capacity) * 100;
|
||||
return {
|
||||
used,
|
||||
capacity,
|
||||
percent: meterPercent(share),
|
||||
barPercent: Math.max(0, Math.min(100, share)),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* `getMonthlyUsage()` resolves with whatever body the server answered, an
|
||||
* error included. Throws unless that body is a usage report, so a failed
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { addonCreditsBudget, addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
|
||||
const info = (allowance, addons = {}) => ({
|
||||
monthUsageAllowance: allowance,
|
||||
@@ -148,6 +148,41 @@ describe('addonCreditsRemaining', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('addonCreditsBudget', () => {
|
||||
it('has no meter for an account that never had add-on credit', () => {
|
||||
expect(addonCreditsBudget(info(900_000_000))).toBeNull();
|
||||
expect(addonCreditsBudget(info(900_000_000, { purchasedCredits: 0 }))).toBeNull();
|
||||
expect(addonCreditsBudget(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('meters what was spent of the credit bought', () => {
|
||||
expect(addonCreditsBudget(info(900_000_000, {
|
||||
purchasedCredits: 2_500,
|
||||
consumedPurchaseCredits: 850,
|
||||
}))).toEqual({ used: 850, capacity: 2_500, percent: 34, barPercent: 34 });
|
||||
});
|
||||
|
||||
it('starts empty when nothing has been spent, or the spend is unreadable', () => {
|
||||
expect(addonCreditsBudget(info(0, { purchasedCredits: 1_000 })))
|
||||
.toEqual({ used: 0, capacity: 1_000, percent: 0, barPercent: 0 });
|
||||
expect(addonCreditsBudget(info(0, { purchasedCredits: 1_000, consumedPurchaseCredits: NaN })).used).toBe(0);
|
||||
});
|
||||
|
||||
it('reads full, never past it, once the pool is spent', () => {
|
||||
expect(addonCreditsBudget(info(0, {
|
||||
purchasedCredits: 1_000,
|
||||
consumedPurchaseCredits: 1_200,
|
||||
}))).toEqual({ used: 1_000, capacity: 1_000, percent: 100, barPercent: 100 });
|
||||
});
|
||||
|
||||
it('holds at 99% while any credit is left', () => {
|
||||
expect(addonCreditsBudget(info(0, {
|
||||
purchasedCredits: 100_000,
|
||||
consumedPurchaseCredits: 99_999,
|
||||
})).percent).toBe(99);
|
||||
});
|
||||
});
|
||||
|
||||
describe('monthlyUsageOrThrow', () => {
|
||||
it('passes a usage report through', () => {
|
||||
const res = { usage: { total: 0 }, allowanceInfo: null };
|
||||
|
||||
@@ -79,7 +79,6 @@ async function UIWindowDisable2FA (options) {
|
||||
width: 350,
|
||||
height: 'auto',
|
||||
dominant: true,
|
||||
show_in_taskbar: false,
|
||||
on_before_exit: async () => {
|
||||
if ( ! disabled_successfully ) {
|
||||
promise.resolve(false);
|
||||
|
||||
@@ -136,7 +136,6 @@ function UIAlert (options) {
|
||||
selectable_body: false,
|
||||
draggable_body: options.draggable_body ?? true,
|
||||
allow_context_menu: false,
|
||||
show_in_taskbar: false,
|
||||
window_class: 'window-alert',
|
||||
dominant: true,
|
||||
body_content: h,
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a reusable color picker widget using iro.ColorPicker
|
||||
* @param {HTMLElement|jQuery} container - Container element for the color picker
|
||||
* @param {Object} options - Configuration options
|
||||
* @param {string} options.default - Default color in hex format (e.g., "#f00" or "#ff0000ff")
|
||||
* @param {Object} options.layout - Custom layout configuration for iro.ColorPicker
|
||||
* @param {Function} options.onColorChange - Callback function called when color changes
|
||||
* @returns {Object} Color picker instance with methods to interact with it
|
||||
*/
|
||||
export function UIColorPickerWidget (container, options = {}) {
|
||||
// Get the DOM element if it's a jQuery object
|
||||
const domElement = container instanceof HTMLElement
|
||||
? container
|
||||
: $(container).get(0);
|
||||
|
||||
if ( ! domElement ) {
|
||||
throw new Error('Container element is required');
|
||||
}
|
||||
|
||||
// Default layout configuration
|
||||
const defaultLayout = [
|
||||
{
|
||||
component: iro.ui.Box,
|
||||
options: {
|
||||
layoutDirection: 'horizontal',
|
||||
width: 265,
|
||||
height: 265,
|
||||
},
|
||||
},
|
||||
{
|
||||
component: iro.ui.Slider,
|
||||
options: {
|
||||
sliderType: 'alpha',
|
||||
layoutDirection: 'horizontal',
|
||||
height: 265,
|
||||
width: 265,
|
||||
},
|
||||
},
|
||||
{
|
||||
component: iro.ui.Slider,
|
||||
options: {
|
||||
sliderType: 'hue',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Initialize the color picker
|
||||
const colorPicker = new iro.ColorPicker(domElement, {
|
||||
layout: options.layout ?? defaultLayout,
|
||||
color: options.default ?? '#f00',
|
||||
});
|
||||
|
||||
// Set up color change callback if provided
|
||||
if ( options.onColorChange ) {
|
||||
colorPicker.on('color:change', (color) => {
|
||||
options.onColorChange(color);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Get the current color
|
||||
* @returns {Object} iro.Color object
|
||||
*/
|
||||
getColor: () => colorPicker.color,
|
||||
|
||||
/**
|
||||
* Get the current color as hex8 string (includes alpha)
|
||||
* @returns {string} Color in hex8 format (e.g., "#ff0000ff")
|
||||
*/
|
||||
getHex8String: () => colorPicker.color.hex8String,
|
||||
|
||||
/**
|
||||
* Get the current color as hex string (no alpha)
|
||||
* @returns {string} Color in hex format (e.g., "#ff0000")
|
||||
*/
|
||||
getHexString: () => colorPicker.color.hexString,
|
||||
|
||||
/**
|
||||
* Get the current color as HSLA object
|
||||
* @returns {Object} Object with h, s, l, a properties
|
||||
*/
|
||||
getHSLA: () => {
|
||||
const color = colorPicker.color;
|
||||
return color.hsla;
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the color
|
||||
* @param {string|Object} color - Color in hex format (e.g., "#f00" or "#ff0000ff") or HSLA object
|
||||
*/
|
||||
setColor: (color) => {
|
||||
if ( typeof color === 'string' ) {
|
||||
// Remove # if present for matching
|
||||
const hexValue = color.startsWith('#') ? color.substring(1) : color;
|
||||
|
||||
// Check if it's a hex8 string (8 hex digits)
|
||||
if ( /^[0-9a-fA-F]{8}$/.test(hexValue) ) {
|
||||
// It's a hex8 string, set both hex and alpha
|
||||
const hex6 = `#${ hexValue.substring(0, 6)}`; // Get first 6 hex digits
|
||||
const alphaHex = hexValue.substring(6, 8); // Get last 2 hex digits (alpha)
|
||||
colorPicker.color.hexString = hex6;
|
||||
colorPicker.color.alpha = parseInt(alphaHex, 16) / 255;
|
||||
} else {
|
||||
// Regular hex string (with or without #)
|
||||
colorPicker.color.hexString = color.startsWith('#') ? color : `#${ color}`;
|
||||
}
|
||||
} else if ( typeof color === 'object' && color.h !== undefined ) {
|
||||
// HSLA object - set properties directly
|
||||
colorPicker.color.hue = color.h;
|
||||
colorPicker.color.saturation = color.s;
|
||||
colorPicker.color.lightness = color.l;
|
||||
colorPicker.color.alpha = color.a !== undefined ? color.a : 1;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Add an event listener
|
||||
* @param {string} event - Event name (e.g., 'color:change')
|
||||
* @param {Function} callback - Callback function
|
||||
*/
|
||||
on: (event, callback) => {
|
||||
colorPicker.on(event, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an event listener
|
||||
* @param {string} event - Event name
|
||||
* @param {Function} callback - Callback function
|
||||
*/
|
||||
off: (event, callback) => {
|
||||
colorPicker.off(event, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the underlying iro.ColorPicker instance
|
||||
* @returns {iro.ColorPicker} The iro.ColorPicker instance
|
||||
*/
|
||||
getPicker: () => colorPicker,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts HSLA values to hex8 string
|
||||
* @param {number} h - Hue (0-360)
|
||||
* @param {number} s - Saturation (0-100)
|
||||
* @param {number} l - Lightness (0-100)
|
||||
* @param {number} a - Alpha (0-1)
|
||||
* @returns {string} Color in hex8 format
|
||||
*/
|
||||
export function hslaToHex8 (h, s, l, a) {
|
||||
// Convert HSL to RGB
|
||||
s /= 100;
|
||||
l /= 100;
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s;
|
||||
const x = c * (1 - Math.abs((h / 60) % 2 - 1));
|
||||
const m = l - c / 2;
|
||||
let r = 0, g = 0, b = 0;
|
||||
|
||||
if ( h >= 0 && h < 60 ) {
|
||||
r = c; g = x; b = 0;
|
||||
} else if ( h >= 60 && h < 120 ) {
|
||||
r = x; g = c; b = 0;
|
||||
} else if ( h >= 120 && h < 180 ) {
|
||||
r = 0; g = c; b = x;
|
||||
} else if ( h >= 180 && h < 240 ) {
|
||||
r = 0; g = x; b = c;
|
||||
} else if ( h >= 240 && h < 300 ) {
|
||||
r = x; g = 0; b = c;
|
||||
} else if ( h >= 300 && h < 360 ) {
|
||||
r = c; g = 0; b = x;
|
||||
}
|
||||
|
||||
r = Math.round((r + m) * 255);
|
||||
g = Math.round((g + m) * 255);
|
||||
b = Math.round((b + m) * 255);
|
||||
const alpha = Math.round(a * 255);
|
||||
|
||||
return `#${[r, g, b, alpha].map(x => {
|
||||
const hex = x.toString(16);
|
||||
return hex.length === 1 ? `0${ hex}` : hex;
|
||||
}).join('')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts hex8 string to HSLA object
|
||||
* @param {string} hex8 - Color in hex8 format (e.g., "#ff0000ff")
|
||||
* @returns {Object} Object with h, s, l, a properties
|
||||
*/
|
||||
export function hex8ToHSLA (hex8) {
|
||||
// Remove # if present
|
||||
hex8 = hex8.replace('#', '');
|
||||
|
||||
// Parse hex values
|
||||
const r = parseInt(hex8.substring(0, 2), 16) / 255;
|
||||
const g = parseInt(hex8.substring(2, 4), 16) / 255;
|
||||
const b = parseInt(hex8.substring(4, 6), 16) / 255;
|
||||
const a = parseInt(hex8.substring(6, 8), 16) / 255;
|
||||
|
||||
// Convert RGB to HSL
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h, s, l = (max + min) / 2;
|
||||
|
||||
if ( max === min ) {
|
||||
h = s = 0; // achromatic
|
||||
} else {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
|
||||
switch ( max ) {
|
||||
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
|
||||
case g: h = ((b - r) / d + 2) / 6; break;
|
||||
case b: h = ((r - g) / d + 4) / 6; break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
h: Math.round(h * 360),
|
||||
s: Math.round(s * 100),
|
||||
l: Math.round(l * 100),
|
||||
a: a,
|
||||
};
|
||||
}
|
||||
@@ -568,9 +568,9 @@ function UIContextMenu (options) {
|
||||
|
||||
// Y position
|
||||
// is the menu going to go out of the window from the bottom?
|
||||
if ( (start_y + menu_height) > (window.innerHeight - window.taskbar_height - 10) )
|
||||
if ( (start_y + menu_height) > (window.innerHeight - 10) )
|
||||
{
|
||||
y_pos = window.innerHeight - menu_height - window.taskbar_height - 10;
|
||||
y_pos = window.innerHeight - menu_height - 10;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -801,9 +801,6 @@ function UIContextMenu (options) {
|
||||
$(options.parent_element).css('overflow', 'scroll');
|
||||
|
||||
$(options.parent_element).removeClass('has-open-contextmenu');
|
||||
if ( $(options.parent_element).hasClass('taskbar-item') ) {
|
||||
window.make_taskbar_sortable();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+32
-1008
File diff suppressed because it is too large.
Load diff
+52
-101
@@ -18,23 +18,20 @@
|
||||
*/
|
||||
|
||||
import UIWindowItemProperties from './UIWindowItemProperties.js';
|
||||
import ensureConfirmedEmail from '../helpers/ensureConfirmedEmail.js';
|
||||
import UIPopover from './UIPopover.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import UIWindowPublishWorker from './UIWindowPublishWorker.js';
|
||||
import UIWindowShare from './UIWindowShare.js';
|
||||
import path from '../lib/path.js';
|
||||
import truncate_filename from '../helpers/truncateFilename.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import open_item from '../helpers/openItem.js';
|
||||
import publish_as_website from '../helpers/publishAsWebsite.js';
|
||||
import mime from '../lib/mime.js';
|
||||
import { isWeblinkName, weblinkChangeIconMenuItem } from '../helpers/weblink.js';
|
||||
import { is_owned_by_me } from '../helpers/pathOwner.js';
|
||||
import { can_rename, can_restructure, invalidate_shared_roots, shared_mode_for } from '../helpers/sharedAccess.js';
|
||||
import { can_rename, can_restructure, invalidate_shared_roots } from '../helpers/sharedAccess.js';
|
||||
import { is_default_app } from '../helpers/defaultApp.js';
|
||||
import openWithAI from '../helpers/openWithAI.js';
|
||||
import refresh_item_container from '../helpers/refreshItemContainer.js';
|
||||
|
||||
async function UIItem (options) {
|
||||
const matching_appendto_count = $(options.appendTo).length;
|
||||
@@ -64,6 +61,7 @@ async function UIItem (options) {
|
||||
options.share_mode = options.share_mode ?? '';
|
||||
options.shared_by = options.shared_by ?? '';
|
||||
options.is_team_share = options.is_team_share ?? false;
|
||||
options.is_also_team_share = options.is_also_team_share ?? false;
|
||||
options.owner = options.owner ?? '';
|
||||
options.metadata = options.metadata ?? '';
|
||||
options.multiselectable = (options.multiselectable === undefined || options.multiselectable === true) ? true : false;
|
||||
@@ -102,6 +100,7 @@ async function UIItem (options) {
|
||||
data-share_mode="${html_encode(options.share_mode)}"
|
||||
data-shared_by="${html_encode(options.shared_by)}"
|
||||
data-is_team_share="${options.is_team_share ? 1 : 0}"
|
||||
data-is_also_team_share="${options.is_also_team_share ? 1 : 0}"
|
||||
data-owner="${html_encode(options.owner)}"
|
||||
data-has_website="${show_website_badge ? 1 : 0 }"
|
||||
data-website_url = "${website_url ? html_encode(website_url) : ''}"
|
||||
@@ -326,7 +325,6 @@ async function UIItem (options) {
|
||||
last_window_dragged_over = null;
|
||||
|
||||
window.an_item_is_being_dragged = true;
|
||||
$('.toolbar').css('pointer-events', 'none');
|
||||
},
|
||||
drag: function (event, ui) {
|
||||
// Constrain item within desktop bounds
|
||||
@@ -393,7 +391,7 @@ async function UIItem (options) {
|
||||
// do not highlight if the target is the same as the item being moved
|
||||
$(el_item).attr('data-path') !== $(window.mouseover_item_container).attr('data-path') &&
|
||||
// do not highlight if item is being moved to where it already is
|
||||
$(el_item).attr('data-path') !== $(window.mouseover_item_container).attr('data-path') ) {
|
||||
path.dirname($(el_item).attr('data-path')) !== $(window.mouseover_item_container).attr('data-path') ) {
|
||||
|
||||
// highlight item container
|
||||
$(window.mouseover_item_container).addClass('item-container-active');
|
||||
@@ -413,10 +411,11 @@ async function UIItem (options) {
|
||||
},
|
||||
stop: function (event, ui) {
|
||||
// Allow rearranging only if item is on desktop, not trash container, auto arrange is disabled and item is not dropped into another item
|
||||
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path &&
|
||||
// the desktop itself, not a window showing the Desktop folder
|
||||
if ( $(el_item).closest('.item-container').hasClass('desktop') &&
|
||||
!window.is_auto_arrange_enabled && $(el_item).attr('data-path') !== window.trash_path && !ui.helper.data('dropped') &&
|
||||
// Item must be dropped on the Desktop and not on the taskbar
|
||||
window.mouseover_window === undefined && ui.position.top <= window.desktop_height - window.taskbar_height - 15 ) {
|
||||
// .desktop clips its overflow, so the whole item has to fit above the bottom edge
|
||||
window.mouseover_window === undefined && ui.position.top + $(el_item).outerHeight(true) <= window.desktop_height ) {
|
||||
|
||||
el_item.style.position = 'absolute';
|
||||
el_item.style.left = `${ui.position.left }px`;
|
||||
@@ -431,12 +430,13 @@ async function UIItem (options) {
|
||||
// re-enable all droppable UIItems that are not a dir
|
||||
$('.item[data-is_dir=\'0\']:not(.item-selected)').droppable('enable');
|
||||
// remove active item-container border highlights
|
||||
$('.item-container').removeClass('item-container-active');
|
||||
$('.item-container').removeClass('item-container-active item-container-transparent-border');
|
||||
// a drop that bailed out early never re-enables the containers an item's hover disabled
|
||||
$('.item-container.ui-droppable').droppable('enable');
|
||||
// reset longer hover timeout and last window dragged over
|
||||
clearTimeout(longer_hover_timeout);
|
||||
last_window_dragged_over = null;
|
||||
window.an_item_is_being_dragged = false;
|
||||
$('.toolbar').css('pointer-events', 'auto');
|
||||
},
|
||||
});
|
||||
|
||||
@@ -545,11 +545,14 @@ async function UIItem (options) {
|
||||
}
|
||||
// Otherwise, move items
|
||||
else if ( options.is_dir ) {
|
||||
// a selected folder can be the drop target of its own selection; it stays where it is
|
||||
const items_to_drop = items_to_move.filter(item => $(item).attr('data-uid') !== $(el_item).attr('data-uid'));
|
||||
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path ) {
|
||||
delete window.desktop_item_positions[$(el_item).attr('data-uid')];
|
||||
// the items leaving the desktop lose their saved positions, not the folder they land in
|
||||
items_to_drop.forEach(item => delete window.desktop_item_positions[$(item).attr('data-uid')]);
|
||||
window.save_desktop_item_positions();
|
||||
}
|
||||
window.move_items(items_to_move, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
|
||||
window.move_items(items_to_drop, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,8 +563,9 @@ async function UIItem (options) {
|
||||
},
|
||||
over: function (event, ui) {
|
||||
// Check hovering over an item that is VISIBILE
|
||||
// A desktop item has no window, so it only counts while the pointer is over the desktop itself
|
||||
const $event_parent_win = $(event.target).closest('.window');
|
||||
if ( $event_parent_win.length > 0 && $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
|
||||
if ( $event_parent_win.attr('data-id') !== $(window.mouseover_window).attr('data-id') )
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -719,7 +723,7 @@ async function UIItem (options) {
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on('click', function (e) {
|
||||
$(document).on(`click.item-${item_id}`, function (e) {
|
||||
if ( !$(e.target).hasClass('item') && !$(e.target).hasClass('item-name') && !$(e.target).hasClass('item-icon') ) {
|
||||
skip_a_rename_click = true;
|
||||
}
|
||||
@@ -728,6 +732,10 @@ async function UIItem (options) {
|
||||
skip_a_rename_click = true;
|
||||
}
|
||||
});
|
||||
// a document handler outlives the row unless it is released with it
|
||||
$(el_item).on('remove', function () {
|
||||
$(document).off(`click.item-${item_id}`);
|
||||
});
|
||||
|
||||
// --------------------------------------------------------
|
||||
// Rename
|
||||
@@ -735,6 +743,7 @@ async function UIItem (options) {
|
||||
function rename () {
|
||||
if ( rename_cancelled ) {
|
||||
rename_cancelled = false;
|
||||
$(el_item_name_editor).removeClass('item-name-editor-active');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -754,10 +763,12 @@ async function UIItem (options) {
|
||||
UIAlert('The name ".." is not allowed, because it is a reserved name. Please choose another name.');
|
||||
}
|
||||
|
||||
$(el_item_name).html(html_encode(truncate_filename(options.name)));
|
||||
$(el_item_name).html(html_encode(truncate_filename($(el_item).attr('data-name'))));
|
||||
$(el_item_name).show();
|
||||
$(el_item_name_editor).val($(el_item).attr('data-name'));
|
||||
$(el_item_name_editor).hide();
|
||||
// the Delete shortcut skips an item whose editor is marked active
|
||||
$(el_item_name_editor).removeClass('item-name-editor-active');
|
||||
return;
|
||||
}
|
||||
// deactivate item name editable
|
||||
@@ -803,8 +814,9 @@ async function UIItem (options) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
rename_cancelled = true;
|
||||
$(el_item_name_editor).removeClass('item-name-editor-active');
|
||||
$(el_item_name_editor).hide();
|
||||
$(el_item_name_editor).val(options.name);
|
||||
$(el_item_name_editor).val($(el_item).attr('data-name'));
|
||||
$(el_item_name).show();
|
||||
}
|
||||
});
|
||||
@@ -863,6 +875,11 @@ async function UIItem (options) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The menu is built after lookups that take time, so it opens where the pointer was when it was asked for.
|
||||
const menu_position = (isMobile.phone || isMobile.tablet)
|
||||
? { left: window.last_touch_x, top: window.last_touch_y }
|
||||
: { left: window.mouseX, top: window.mouseY };
|
||||
|
||||
// if editing item name, preserve native context menu
|
||||
if ( event.target === el_item_name_editor )
|
||||
{
|
||||
@@ -1076,11 +1093,6 @@ async function UIItem (options) {
|
||||
// Someone else's, however we got here — including items reached by
|
||||
// opening a shared folder, which carry no share markers.
|
||||
const is_not_mine = !is_owned_by_me($(el_item).attr('data-path'));
|
||||
// `manage` inherits downwards, so a file inside a folder you manage
|
||||
// counts too — the row itself only carries a mode at a shared root.
|
||||
const can_manage_share =
|
||||
$(el_item).attr('data-share_mode') === 'manage'
|
||||
|| (await shared_mode_for($(el_item).attr('data-path'))) === 'manage';
|
||||
// Moving and deleting go by the holding folder, not by the item.
|
||||
const may_restructure = !is_not_mine
|
||||
|| await can_restructure($(el_item).attr('data-path'));
|
||||
@@ -1134,7 +1146,7 @@ async function UIItem (options) {
|
||||
// try to find suitable apps
|
||||
const suitable_apps = await window.suggest_apps_for_fsentry({
|
||||
uid: options.uid,
|
||||
path: options.path,
|
||||
path: $(el_item).attr('data-path'),
|
||||
});
|
||||
if ( suitable_apps && suitable_apps.length > 0 ) {
|
||||
options.suggested_apps = suitable_apps;
|
||||
@@ -1246,19 +1258,6 @@ async function UIItem (options) {
|
||||
});
|
||||
|
||||
}
|
||||
//-------------------------------------------
|
||||
// Publish as Worker
|
||||
// -------------------------------------------
|
||||
// The backend refuses deploys from a file someone else owns.
|
||||
if ( !is_trashed && !is_trash && !is_not_mine && !options.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') ) {
|
||||
menu_items.push({
|
||||
html: i18n('publish_as_serverless_worker'),
|
||||
onClick: async function () {
|
||||
if ( ! await ensureConfirmedEmail(i18n('save_account_to_publish')) ) return;
|
||||
UIWindowPublishWorker(options.uid, $(el_item).attr('data-name'), $(el_item).attr('data-path'));
|
||||
},
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Deploy As App
|
||||
// -------------------------------------------
|
||||
@@ -1272,7 +1271,7 @@ async function UIItem (options) {
|
||||
file_path: $(el_item).attr('data-path'),
|
||||
file_uid: $(el_item).attr('data-uid'),
|
||||
params: {
|
||||
source_path: options.path,
|
||||
source_path: $(el_item).attr('data-path'),
|
||||
},
|
||||
});
|
||||
},
|
||||
@@ -1292,20 +1291,6 @@ async function UIItem (options) {
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Share
|
||||
// -------------------------------------------
|
||||
if ( !is_trash && !is_trashed && (!is_not_mine || can_manage_share) ) {
|
||||
menu_items.push({
|
||||
html: i18n('share_ellipsis'),
|
||||
onClick: async function () {
|
||||
UIWindowShare({
|
||||
path: $(el_item).attr('data-path'),
|
||||
name: $(el_item).attr('data-name'),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Download
|
||||
// -------------------------------------------
|
||||
if ( !is_trash && !is_trashed && (options.associated_app_name === null || options.associated_app_name === undefined) ) {
|
||||
@@ -1319,49 +1304,7 @@ async function UIItem (options) {
|
||||
}
|
||||
else
|
||||
{
|
||||
window.trigger_download([options.path]);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Set as Wallpaper
|
||||
// -------------------------------------------
|
||||
const mime_type = mime.getType($(el_item).attr('data-name')) ??
|
||||
'application/octet-stream';
|
||||
if ( !is_trashed && !is_trash && !options.is_dir && mime_type.startsWith('image/') ) {
|
||||
menu_items.push({
|
||||
html: i18n('set_as_background'),
|
||||
onClick: async function () {
|
||||
const read_url = await puter.fs.sign(undefined, { uid: $(el_item).attr('data-uid'), action: 'read' });
|
||||
window.set_desktop_background({
|
||||
url: read_url.items.read_url,
|
||||
fit: window.desktop_bg_fit,
|
||||
});
|
||||
try {
|
||||
$.ajax({
|
||||
url: `${window.api_origin }/set-desktop-bg`,
|
||||
type: 'POST',
|
||||
data: JSON.stringify({
|
||||
url: window.desktop_bg_url,
|
||||
color: window.desktop_bg_color,
|
||||
fit: window.desktop_bg_fit,
|
||||
}),
|
||||
async: true,
|
||||
contentType: 'application/json',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.auth_token}`,
|
||||
},
|
||||
statusCode: {
|
||||
401: function (xhr) {
|
||||
window.handle401(xhr);
|
||||
},
|
||||
},
|
||||
});
|
||||
$(el_window).close();
|
||||
resolve(true);
|
||||
} catch ( err ) {
|
||||
// Ignore
|
||||
window.trigger_download([$(el_item).attr('data-path')]);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1434,12 +1377,13 @@ async function UIItem (options) {
|
||||
// -------------------------------------------
|
||||
// Cut
|
||||
// -------------------------------------------
|
||||
if ( $(el_item).attr('data-immutable') === '0' ) {
|
||||
// Trashed items leave the Trash through Restore; moved any other way, they'd keep their uid as their name.
|
||||
if ( $(el_item).attr('data-immutable') === '0' && !is_trashed && may_restructure ) {
|
||||
menu_items.push({
|
||||
html: i18n('cut'),
|
||||
onClick: function () {
|
||||
window.clipboard_op = 'move';
|
||||
window.clipboard = [options.path];
|
||||
window.clipboard = [$(el_item).attr('data-path')];
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1451,7 +1395,7 @@ async function UIItem (options) {
|
||||
html: i18n('copy'),
|
||||
onClick: function () {
|
||||
window.clipboard_op = 'copy';
|
||||
window.clipboard = [{ path: options.path }];
|
||||
window.clipboard = [{ path: $(el_item).attr('data-path') }];
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1499,7 +1443,7 @@ async function UIItem (options) {
|
||||
base_dir,
|
||||
options.appendTo,
|
||||
options.shortcut_to === '' ? options.uid : options.shortcut_to,
|
||||
options.shortcut_to_path === '' ? options.path : options.shortcut_to_path,
|
||||
options.shortcut_to_path === '' ? $(el_item).attr('data-path') : options.shortcut_to_path,
|
||||
);
|
||||
},
|
||||
});
|
||||
@@ -1529,7 +1473,13 @@ async function UIItem (options) {
|
||||
// Or mode lookups keep answering for a share we
|
||||
// just walked away from.
|
||||
invalidate_shared_roots();
|
||||
$(el_item).removeItems();
|
||||
// A team that still shares it keeps it listed,
|
||||
// as the team's share.
|
||||
if ( $(el_item).attr('data-is_also_team_share') === '1' ) {
|
||||
refresh_item_container($(el_item).closest('.item-container'));
|
||||
} else {
|
||||
$(el_item).removeItems();
|
||||
}
|
||||
} catch (e) {
|
||||
UIAlert({ message: e?.message ?? i18n('error_unknown_cause') });
|
||||
}
|
||||
@@ -1604,7 +1554,7 @@ async function UIItem (options) {
|
||||
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
|
||||
|
||||
let top = $(el_item).position().top + $(el_item).height();
|
||||
top = top > (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.taskbar_height + window.toolbar_height)) : top;
|
||||
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
|
||||
|
||||
UIWindowItemProperties(
|
||||
$(el_item).attr('data-name'),
|
||||
@@ -1622,6 +1572,7 @@ async function UIItem (options) {
|
||||
// Create ContextMenu
|
||||
UIContextMenu({
|
||||
parent_element: ($(options.appendTo).hasClass('desktop') ? undefined : options.appendTo),
|
||||
position: menu_position,
|
||||
items: menu_items,
|
||||
});
|
||||
|
||||
|
||||
@@ -27,12 +27,11 @@ vi.mock('./UIPopover.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIWindowEmailConfirmationRequired.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIAlert.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIWindowPublishWorker.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIWindowShare.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/openItem.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/publishAsWebsite.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/openWithAI.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/refreshItemContainer.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.$ = jQuery;
|
||||
globalThis.jQuery = jQuery;
|
||||
@@ -67,6 +66,8 @@ Object.assign(window, {
|
||||
|
||||
const { default: UIItem } = await import('./UIItem.js');
|
||||
const { default: UIContextMenu } = await import('./UIContextMenu.js');
|
||||
const { default: refresh_item_container } =
|
||||
await import('../helpers/refreshItemContainer.js');
|
||||
|
||||
const menuLabels = async (options) => {
|
||||
document.body.innerHTML =
|
||||
@@ -90,14 +91,25 @@ const menuLabels = async (options) => {
|
||||
return UIContextMenu.mock.calls[0][0].items.map((item) => item?.html);
|
||||
};
|
||||
|
||||
const removeFromShared = async (options) => {
|
||||
await menuLabels(options);
|
||||
await UIContextMenu.mock.calls[0][0].items
|
||||
.find((item) => item?.html === 'share_remove_from_shared')
|
||||
.onClick();
|
||||
};
|
||||
|
||||
describe('UIItem Remove from Shared', () => {
|
||||
beforeEach(() => {
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = '/alice/Trash';
|
||||
window.puter = {
|
||||
fs: { listShared: vi.fn(async () => ({ items: [] })) },
|
||||
fs: {
|
||||
listShared: vi.fn(async () => ({ items: [] })),
|
||||
unshare: vi.fn(async () => ({ revoked: 1 })),
|
||||
},
|
||||
};
|
||||
globalThis.puter = window.puter;
|
||||
refresh_item_container.mockClear();
|
||||
});
|
||||
|
||||
it('is offered on an item shared with the user directly', async () => {
|
||||
@@ -109,4 +121,107 @@ describe('UIItem Remove from Shared', () => {
|
||||
expect($('.item').attr('data-is_team_share')).toBe('1');
|
||||
expect(labels).not.toContain('share_remove_from_shared');
|
||||
});
|
||||
|
||||
it('takes the item away once the user has left it', async () => {
|
||||
await removeFromShared({});
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith('/bob/u-1/Photos', 'alice');
|
||||
expect($('.item')).toHaveLength(0);
|
||||
expect(refresh_item_container).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists the item again when a team still shares it', async () => {
|
||||
await removeFromShared({ is_also_team_share: true });
|
||||
expect(puter.fs.unshare).toHaveBeenCalledWith('/bob/u-1/Photos', 'alice');
|
||||
expect($('.item')).toHaveLength(1);
|
||||
expect(refresh_item_container).toHaveBeenCalledTimes(1);
|
||||
expect(refresh_item_container.mock.calls[0][0][0]).toBe($('.item-container')[0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIItem Share', () => {
|
||||
beforeEach(() => {
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = '/alice/Trash';
|
||||
});
|
||||
|
||||
it('is not offered, even on an item the user owns', async () => {
|
||||
const labels = await menuLabels({
|
||||
path: '/alice/Photos',
|
||||
owner: 'alice',
|
||||
shared_with_me: false,
|
||||
share_mode: undefined,
|
||||
shared_by: undefined,
|
||||
});
|
||||
expect(labels).not.toContain('share_ellipsis');
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIItem Publish as Worker', () => {
|
||||
beforeEach(() => {
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = '/alice/Trash';
|
||||
});
|
||||
|
||||
it('is not offered, even on a .js file the user owns', async () => {
|
||||
const labels = await menuLabels({
|
||||
path: '/alice/worker.js',
|
||||
name: 'worker.js',
|
||||
is_dir: false,
|
||||
owner: 'alice',
|
||||
shared_with_me: false,
|
||||
share_mode: undefined,
|
||||
shared_by: undefined,
|
||||
});
|
||||
expect(labels).not.toContain('publish_as_serverless_worker');
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIItem dropped on the desktop', () => {
|
||||
let stop;
|
||||
|
||||
beforeEach(async () => {
|
||||
document.body.innerHTML = '<div class="item-container desktop"></div>';
|
||||
Object.assign(window, {
|
||||
user: { username: 'alice' },
|
||||
trash_path: '/alice/Trash',
|
||||
desktop_height: 800,
|
||||
is_auto_arrange_enabled: false,
|
||||
mouseover_window: undefined,
|
||||
desktop_item_positions: {},
|
||||
save_desktop_item_positions: vi.fn(),
|
||||
});
|
||||
const draggable = jQuery.fn.draggable;
|
||||
jQuery.fn.draggable = function (options) {
|
||||
if ( typeof options === 'object' ) stop = options.stop;
|
||||
return this;
|
||||
};
|
||||
try {
|
||||
await UIItem({
|
||||
appendTo: $('.item-container'),
|
||||
uid: 'u-2',
|
||||
path: '/alice/Desktop/Notes',
|
||||
name: 'Notes',
|
||||
is_dir: true,
|
||||
icon: { image: '', type: 'icon' },
|
||||
});
|
||||
} finally {
|
||||
jQuery.fn.draggable = draggable;
|
||||
}
|
||||
// jsdom has no stylesheet, so give the item the size style.css does.
|
||||
$('.item').css({ height: '70px', margin: '15px 5px 30px 5px' });
|
||||
});
|
||||
|
||||
const dropAt = (top) => stop({}, { position: { top, left: 300 }, helper: $('<div>') });
|
||||
|
||||
it('moves there when the whole item fits on screen', () => {
|
||||
dropAt(685);
|
||||
expect($('.item')[0].style.top).toBe('685px');
|
||||
expect(window.save_desktop_item_positions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stays put when the item would hang off the bottom edge', () => {
|
||||
dropAt(735);
|
||||
expect($('.item')[0].style.top).toBe('');
|
||||
expect(window.save_desktop_item_positions).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -62,47 +62,17 @@ function UIPopover (options) {
|
||||
function position_popover () {
|
||||
// X position
|
||||
const popover_width = options.width ?? $(el_popover).width();
|
||||
if ( options.center_horizontally ) {
|
||||
// Check taskbar position to determine popover positioning
|
||||
const taskbar_position = window.taskbar_position || 'bottom';
|
||||
|
||||
if ( taskbar_position === 'left' ) {
|
||||
// Position in top-left corner for left taskbar
|
||||
x_pos = window.taskbar_height + 10; // Just to the right of the taskbar
|
||||
} else if ( taskbar_position === 'right' ) {
|
||||
// Position in top-right corner for right taskbar
|
||||
x_pos = window.innerWidth - popover_width - window.taskbar_height - 40; // Just to the left of the taskbar
|
||||
} else {
|
||||
// Default bottom taskbar behavior - center horizontally
|
||||
x_pos = window.innerWidth / 2 - popover_width / 2 - 15;
|
||||
}
|
||||
} else {
|
||||
if ( options.position === 'bottom' || options.position === 'top' )
|
||||
{
|
||||
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width / 2) + 10);
|
||||
}
|
||||
else
|
||||
{
|
||||
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
|
||||
}
|
||||
if ( options.position === 'bottom' || options.position === 'top' )
|
||||
{
|
||||
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width / 2) + 10);
|
||||
}
|
||||
else
|
||||
{
|
||||
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
|
||||
}
|
||||
|
||||
// Y position
|
||||
const popover_height = options.height ?? $(el_popover).height();
|
||||
if ( options.center_horizontally ) {
|
||||
// Check taskbar position to determine popover positioning
|
||||
const taskbar_position = window.taskbar_position || 'bottom';
|
||||
|
||||
if ( taskbar_position === 'left' || taskbar_position === 'right' ) {
|
||||
// Position at top for left/right taskbars
|
||||
y_pos = window.toolbar_height + 10; // Just below the toolbar
|
||||
} else {
|
||||
// Default bottom taskbar behavior - position above taskbar
|
||||
y_pos = options.top ?? (window.innerHeight - (window.taskbar_height + popover_height + 10));
|
||||
}
|
||||
} else {
|
||||
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
|
||||
}
|
||||
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
|
||||
|
||||
$(el_popover).css({
|
||||
left: `${x_pos }px`,
|
||||
|
||||
@@ -71,7 +71,6 @@ function UIPrompt (options) {
|
||||
selectable_body: false,
|
||||
draggable_body: true,
|
||||
allow_context_menu: false,
|
||||
show_in_taskbar: false,
|
||||
window_class: 'window-alert',
|
||||
dominant: true,
|
||||
body_content: h,
|
||||
|
||||
@@ -1,769 +0,0 @@
|
||||
/*
|
||||
* 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 { createUploadThumbnailGenerator } from '../services/pdfThumbnails/index.js';
|
||||
import UITaskbarItem from './UITaskbarItem.js';
|
||||
import UIPopover from './UIPopover.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import { appIconAttrs, appIconSrc } from '../helpers/appIcon.js';
|
||||
import { filterLaunchableApps } from '../helpers/launchAppsList.js';
|
||||
|
||||
const TASKBAR_POSITIONS = ['left', 'bottom', 'right'];
|
||||
|
||||
async function UITaskbar (options) {
|
||||
window.global_element_id++;
|
||||
|
||||
options = options ?? {};
|
||||
options.content = options.content ?? '';
|
||||
|
||||
let taskbar_position;
|
||||
|
||||
// if first visit ever, set taskbar position to left
|
||||
if ( window.first_visit_ever ) {
|
||||
puter.kv.set('taskbar_position', 'left').catch(err => console.warn('Could not save taskbar_position:', err));
|
||||
taskbar_position = 'left';
|
||||
} else {
|
||||
taskbar_position = await puter.kv.get('taskbar_position').catch(() => null);
|
||||
// if this is not first visit, set taskbar position to bottom since it's from a user that
|
||||
// used puter before customizing taskbar position was added and the taskbar position was set to bottom
|
||||
// Unknown values are discarded too: this ends up in markup and stored values may be poisoned.
|
||||
if ( ! TASKBAR_POSITIONS.includes(taskbar_position) ) {
|
||||
taskbar_position = 'bottom'; // default position
|
||||
puter.kv.set('taskbar_position', taskbar_position).catch(err => console.warn('Could not save taskbar_position:', err));
|
||||
}
|
||||
}
|
||||
|
||||
// Force bottom position on mobile devices
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
taskbar_position = 'bottom';
|
||||
}
|
||||
|
||||
// Set global taskbar position
|
||||
window.taskbar_position = taskbar_position;
|
||||
|
||||
let launchAppsRequest = 0;
|
||||
let pendingLaunchApps;
|
||||
const fetchLaunchApps = () => {
|
||||
pendingLaunchApps?.abort();
|
||||
pendingLaunchApps = $.ajax({
|
||||
url: `${window.api_origin}/get-launch-apps?icon_size=64`,
|
||||
type: 'GET',
|
||||
contentType: 'application/json',
|
||||
timeout: 30000,
|
||||
headers: { 'Authorization': `Bearer ${window.auth_token}` },
|
||||
});
|
||||
return pendingLaunchApps;
|
||||
};
|
||||
const logRefreshFailure = (xhr, status) => {
|
||||
if ( status !== 'abort' ) console.error('Failed to refresh launch apps:', status);
|
||||
};
|
||||
|
||||
fetchLaunchApps().done(apps => {
|
||||
if ( launchAppsRequest === 0 ) window.launch_apps = apps;
|
||||
}).fail(logRefreshFailure);
|
||||
|
||||
let h = '';
|
||||
h += `<div id="ui-taskbar_${window.global_element_id}" class="taskbar taskbar-position-${taskbar_position}" style="height:${window.taskbar_height}px;">`;
|
||||
h += '<div class="taskbar-sortable" style="display: flex; justify-content: center; z-index: 99999;"></div>';
|
||||
h += '</div>';
|
||||
|
||||
if ( taskbar_position === 'left' || taskbar_position === 'right' ) {
|
||||
$('.desktop').addClass(`desktop-taskbar-position-${taskbar_position}`);
|
||||
}
|
||||
|
||||
$('.desktop').append(h);
|
||||
|
||||
//---------------------------------------------
|
||||
// add `Start` to taskbar
|
||||
//---------------------------------------------
|
||||
UITaskbarItem({
|
||||
icon: window.icons['start.svg'],
|
||||
name: i18n('start'),
|
||||
sortable: false,
|
||||
keep_in_taskbar: true,
|
||||
disable_context_menu: true,
|
||||
onClick: async function (item) {
|
||||
// skip if popover already open
|
||||
if ( $(item).hasClass('has-open-popover') )
|
||||
{
|
||||
$('.popover-launcher').remove();
|
||||
return;
|
||||
}
|
||||
|
||||
// show popover
|
||||
let popover = UIPopover({
|
||||
content: '<div class="launch-popover hide-scrollbar"></div>',
|
||||
snapToElement: item,
|
||||
parent_element: item,
|
||||
width: 500,
|
||||
height: 500,
|
||||
class: 'popover-launcher',
|
||||
center_horizontally: true,
|
||||
});
|
||||
|
||||
$(popover).on('remove', () => pendingLaunchApps?.abort());
|
||||
const request = ++launchAppsRequest;
|
||||
if ( ! window.launch_apps?.recent ) {
|
||||
window.launch_apps = { recent: [], recommended: [] };
|
||||
}
|
||||
$(popover).find('.launch-popover').append(`
|
||||
<div class="launch-search-wrapper">
|
||||
<input style="background-image:url('${window.icons['magnifier-outline.svg']}');" class="launch-search">
|
||||
<img class="launch-search-clear" src="${window.icons['close.svg']}">
|
||||
</div>
|
||||
`);
|
||||
|
||||
const renderApps = () => {
|
||||
const recentApps = filterLaunchableApps(window.launch_apps.recent);
|
||||
const recommendedApps = filterLaunchableApps(window.launch_apps.recommended);
|
||||
let apps_str = '';
|
||||
|
||||
// -------------------------------------------
|
||||
// Recent apps
|
||||
// -------------------------------------------
|
||||
if ( recentApps.length > 0 ) {
|
||||
// heading
|
||||
apps_str += `<h1 class="start-section-heading start-section-heading-recent">${i18n('recent')}</h1>`;
|
||||
|
||||
// apps
|
||||
apps_str += '<div class="launch-apps-recent">';
|
||||
for ( let index = 0; index < window.launch_recent_apps_count && index < recentApps.length; index++ ) {
|
||||
const app_info = recentApps[index];
|
||||
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
|
||||
const icon = appIconSrc(app_info);
|
||||
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
|
||||
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
|
||||
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
|
||||
apps_str += '</div>';
|
||||
apps_str += '</div>';
|
||||
}
|
||||
apps_str += '</div>';
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Recommended apps
|
||||
// -------------------------------------------
|
||||
if ( recommendedApps.length > 0 ) {
|
||||
// heading
|
||||
apps_str += `<h1 class="start-section-heading start-section-heading-recommended" style="${recentApps.length > 0 ? 'padding-top: 30px;' : ''}">${i18n('recommended')}</h1>`;
|
||||
// apps
|
||||
apps_str += '<div class="launch-apps-recommended">';
|
||||
for ( let index = 0; index < recommendedApps.length; index++ ) {
|
||||
const app_info = recommendedApps[index];
|
||||
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
|
||||
const icon = appIconSrc(app_info);
|
||||
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
|
||||
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
|
||||
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
|
||||
apps_str += '</div>';
|
||||
apps_str += '</div>';
|
||||
}
|
||||
apps_str += '</div>';
|
||||
}
|
||||
|
||||
// Replace tiles only, so the search input keeps its text and focus.
|
||||
$(popover).find('.start-section-heading, .launch-apps-recent, .launch-apps-recommended').remove();
|
||||
$(popover).find('.launch-popover').append(apps_str);
|
||||
|
||||
// make apps draggable
|
||||
$(popover).find('.start-app').draggable({
|
||||
appendTo: 'body',
|
||||
revert: 'invalid',
|
||||
connectToSortable: '.taskbar-sortable',
|
||||
zIndex: parseInt($(popover).css('z-index')) + 1,
|
||||
scroll: false,
|
||||
distance: 5,
|
||||
revertDuration: 100,
|
||||
helper: 'clone',
|
||||
cursorAt: { left: 18, top: 20 },
|
||||
start: function (event, ui) {
|
||||
},
|
||||
drag: function (event, ui) {
|
||||
},
|
||||
stop: function () {
|
||||
},
|
||||
});
|
||||
};
|
||||
renderApps();
|
||||
if ( ! isMobile.phone ) $(popover).find('.launch-search').focus();
|
||||
|
||||
fetchLaunchApps().done(apps => {
|
||||
if ( request !== launchAppsRequest || !popover.isConnected ) return;
|
||||
window.launch_apps = apps;
|
||||
renderApps();
|
||||
$(popover).find('.launch-search').trigger('change');
|
||||
}).fail(logRefreshFailure);
|
||||
|
||||
$(popover).on('click', function () {
|
||||
// close other context menus
|
||||
$('.context-menu').fadeOut(200, function () {
|
||||
$(this).remove();
|
||||
$('.launch-app-selected').removeClass('launch-app-selected');
|
||||
});
|
||||
});
|
||||
|
||||
$(popover).on('contextmenu taphold', function (e) {
|
||||
if ( ! e.target.closest('.launch-search') ) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on('contextmenu taphold', '.start-app', function (e) {
|
||||
if ( e.type === 'taphold' && !isMobile.phone && !isMobile.tablet )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
e.stopImmediatePropagation();
|
||||
e.preventDefault();
|
||||
|
||||
// close other context menus
|
||||
$('.context-menu').fadeOut(200, function () {
|
||||
$(this).remove();
|
||||
});
|
||||
|
||||
let items = [{
|
||||
html: i18n('open'),
|
||||
onClick: function () {
|
||||
$(e.currentTarget).trigger('click');
|
||||
},
|
||||
}];
|
||||
|
||||
$('.launch-app-selected').removeClass('launch-app-selected');
|
||||
$(e.currentTarget).parent().addClass('launch-app-selected');
|
||||
|
||||
// Determine pin state
|
||||
const $existingTaskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
|
||||
const isPinned = $existingTaskbarItem.length > 0 && $existingTaskbarItem.attr('data-keep-in-taskbar') === 'true';
|
||||
|
||||
items.push({
|
||||
html: i18n('add_to_desktop'),
|
||||
onClick: async function () {
|
||||
try {
|
||||
const fileName = `${e.currentTarget.dataset.appTitle}.app`;
|
||||
const content = JSON.stringify({
|
||||
app: e.currentTarget.dataset.appName,
|
||||
title: e.currentTarget.dataset.appTitle,
|
||||
icon: e.currentTarget.dataset.appIcon,
|
||||
});
|
||||
await puter.fs.upload(new File([content], fileName), window.desktop_path, {
|
||||
generateThumbnails: true,
|
||||
thumbnailGenerator: createUploadThumbnailGenerator(),
|
||||
});
|
||||
} catch ( err ) {
|
||||
console.error('Failed to add shortcut to desktop:', err);
|
||||
// Consider showing a user-facing error notification
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if ( ! isPinned ) {
|
||||
items.push({
|
||||
html: i18n('keep_in_taskbar'),
|
||||
onClick: function () {
|
||||
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
|
||||
if ( $taskbarItem.length === 0 ) {
|
||||
// No taskbar item yet: create a new pinned one
|
||||
UITaskbarItem({
|
||||
icon: e.currentTarget.dataset.appIcon,
|
||||
iconFallback: e.currentTarget.dataset.appIconFallback,
|
||||
app: e.currentTarget.dataset.appName,
|
||||
name: e.currentTarget.dataset.appTitle,
|
||||
keep_in_taskbar: true,
|
||||
});
|
||||
} else if ( $taskbarItem.attr('data-keep-in-taskbar') !== 'true' ) {
|
||||
// mark as pinned
|
||||
$taskbarItem.attr('data-keep-in-taskbar', 'true');
|
||||
}
|
||||
// Persist
|
||||
window.update_taskbar();
|
||||
},
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
html: i18n('remove_from_taskbar'),
|
||||
onClick: function () {
|
||||
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
|
||||
if ( $taskbarItem.length === 0 ) return; // nothing to do
|
||||
// Unpin
|
||||
$taskbarItem.attr('data-keep-in-taskbar', 'false');
|
||||
// If no open windows for this app, remove the item
|
||||
if ( $taskbarItem.attr('data-open-windows') === '0' ) {
|
||||
if ( window.remove_taskbar_item ) {
|
||||
window.remove_taskbar_item($taskbarItem.get(0));
|
||||
} else {
|
||||
$taskbarItem.remove();
|
||||
}
|
||||
}
|
||||
window.update_taskbar();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
UIContextMenu({
|
||||
items: items,
|
||||
});
|
||||
return false;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
//---------------------------------------------
|
||||
// add `Explorer` to the taskbar
|
||||
//---------------------------------------------
|
||||
UITaskbarItem({
|
||||
icon: window.icons['folders.svg'],
|
||||
app: 'explorer',
|
||||
name: 'Explorer',
|
||||
sortable: false,
|
||||
keep_in_taskbar: true,
|
||||
lock_keep_in_taskbar: true,
|
||||
onClick: function () {
|
||||
let open_window_count = parseInt($('.taskbar-item[data-app="explorer"]').attr('data-open-windows'));
|
||||
if ( open_window_count === 0 ) {
|
||||
launch_app({ name: 'explorer', path: window.home_path });
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
//---------------------------------------------
|
||||
// add separator before trash
|
||||
//---------------------------------------------
|
||||
UITaskbarItem({
|
||||
icon: '', // No icon for separator
|
||||
name: 'separator',
|
||||
app: 'separator',
|
||||
sortable: false,
|
||||
keep_in_taskbar: true,
|
||||
lock_keep_in_taskbar: true,
|
||||
disable_context_menu: true,
|
||||
style: 'pointer-events: none;', // Make it non-interactive
|
||||
onClick: function () {
|
||||
// Separator is non-interactive
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
//---------------------------------------------
|
||||
// Add other useful apps to the taskbar
|
||||
//---------------------------------------------
|
||||
if ( window.user.taskbar_items && window.user.taskbar_items.length > 0 ) {
|
||||
for ( let index = 0; index < window.user.taskbar_items.length; index++ ) {
|
||||
const app_info = window.user.taskbar_items[index];
|
||||
const icon = appIconSrc(app_info);
|
||||
// add taskbar item for each app
|
||||
UITaskbarItem({
|
||||
icon: icon.src,
|
||||
iconFallback: icon.fallback,
|
||||
app: app_info.name,
|
||||
name: app_info.title,
|
||||
keep_in_taskbar: true,
|
||||
onClick: function () {
|
||||
let open_window_count = parseInt($(`.taskbar-item[data-app="${app_info.name}"]`).attr('data-open-windows'));
|
||||
if ( open_window_count === 0 ) {
|
||||
launch_app({
|
||||
name: app_info.name,
|
||||
});
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//---------------------------------------------
|
||||
// add `Trash` to the taskbar
|
||||
//---------------------------------------------
|
||||
const trash = await puter.fs.stat({ path: window.trash_path, consistency: 'eventual' });
|
||||
if ( window.socket ) {
|
||||
window.socket.emit('trash.is_empty', { is_empty: trash.is_empty });
|
||||
}
|
||||
|
||||
UITaskbarItem({
|
||||
icon: trash.is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg'],
|
||||
app: 'trash',
|
||||
name: `${i18n('trash')}`,
|
||||
sortable: false,
|
||||
keep_in_taskbar: true,
|
||||
lock_keep_in_taskbar: true,
|
||||
onClick: function () {
|
||||
let open_windows = $(`.window[data-path="${html_encode(window.trash_path)}"]`);
|
||||
if ( open_windows.length === 0 ) {
|
||||
launch_app({ name: 'explorer', path: window.trash_path });
|
||||
} else {
|
||||
open_windows.focusWindow();
|
||||
}
|
||||
},
|
||||
onItemsDrop: function (items) {
|
||||
window.move_items(items, window.trash_path);
|
||||
},
|
||||
});
|
||||
|
||||
//---------------------------------------------
|
||||
// add separator before trash
|
||||
//---------------------------------------------
|
||||
UITaskbarItem({
|
||||
icon: '', // No icon for separator
|
||||
name: 'separator',
|
||||
app: 'separator',
|
||||
sortable: false,
|
||||
keep_in_taskbar: true,
|
||||
lock_keep_in_taskbar: true,
|
||||
disable_context_menu: true,
|
||||
style: 'pointer-events: none;', // Make it non-interactive
|
||||
onClick: function () {
|
||||
// Separator is non-interactive
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
window.make_taskbar_sortable();
|
||||
}
|
||||
|
||||
//-------------------------------------------
|
||||
// Taskbar is sortable
|
||||
//-------------------------------------------
|
||||
window.make_taskbar_sortable = function () {
|
||||
const position = window.taskbar_position || 'bottom';
|
||||
const axis = position === 'bottom' ? 'x' : 'y';
|
||||
|
||||
$('.taskbar-sortable').sortable({
|
||||
axis: axis,
|
||||
items: '.taskbar-item-sortable:not(.has-open-contextmenu):not([data-app="separator"])',
|
||||
cancel: '.has-open-contextmenu',
|
||||
placeholder: 'taskbar-item-sortable-placeholder',
|
||||
helper: 'clone',
|
||||
distance: 5,
|
||||
revert: 10,
|
||||
receive: function (event, ui) {
|
||||
if ( ! $(ui.item).hasClass('taskbar-item') ) {
|
||||
// if app is already in taskbar, cancel
|
||||
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
|
||||
$(this).sortable('cancel');
|
||||
$('.taskbar .start-app').remove();
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
update: function (event, ui) {
|
||||
if ( ! $(ui.item).hasClass('taskbar-item') ) {
|
||||
// if app is already in taskbar, cancel
|
||||
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
|
||||
$(this).sortable('cancel');
|
||||
$('.taskbar .start-app').remove();
|
||||
return;
|
||||
}
|
||||
|
||||
let item = UITaskbarItem({
|
||||
icon: $(ui.item).attr('data-app-icon'),
|
||||
iconFallback: $(ui.item).attr('data-app-icon-fallback'),
|
||||
app: $(ui.item).attr('data-app-name'),
|
||||
name: $(ui.item).attr('data-app-title'),
|
||||
append_to_taskbar: false,
|
||||
keep_in_taskbar: true,
|
||||
onClick: function () {
|
||||
let open_window_count = parseInt($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).attr('data-open-windows'));
|
||||
if ( open_window_count === 0 ) {
|
||||
launch_app({
|
||||
name: $(ui.item).attr('data-app-name'),
|
||||
});
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
let el = ($(item).detach());
|
||||
$(el).insertAfter(ui.item);
|
||||
$(el).show();
|
||||
$(ui.item).removeItems();
|
||||
window.update_taskbar();
|
||||
}
|
||||
// only proceed to update DB if the item sorted was a pinned item otherwise no point in updating the taskbar in DB
|
||||
else if ( $(ui.item).attr('data-keep-in-taskbar') === 'true' ) {
|
||||
window.update_taskbar();
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Function to update taskbar position
|
||||
window.update_taskbar_position = async function (new_position) {
|
||||
// Prevent position changes on mobile devices - always keep bottom
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! TASKBAR_POSITIONS.includes(new_position) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Store the new position
|
||||
puter.kv.set('taskbar_position', new_position).catch(err => console.warn('Could not save taskbar_position:', err));
|
||||
window.taskbar_position = new_position;
|
||||
|
||||
// Remove old position classes and add new one
|
||||
$('.taskbar').removeClass('taskbar-position-left taskbar-position-bottom taskbar-position-right');
|
||||
$('.taskbar').addClass(`taskbar-position-${new_position}`);
|
||||
|
||||
// update desktop class, if left or right, add `desktop-taskbar-position-left` or `desktop-taskbar-position-right`
|
||||
$('.desktop').removeClass('desktop-taskbar-position-left');
|
||||
$('.desktop').removeClass('desktop-taskbar-position-right');
|
||||
$('.desktop').addClass(`desktop-taskbar-position-${new_position}`);
|
||||
|
||||
// Update desktop height/width calculations based on new position
|
||||
window.update_desktop_dimensions_for_taskbar();
|
||||
|
||||
// Update window positions if needed (for maximized windows)
|
||||
$('.window[data-is_maximized="1"]').each(function () {
|
||||
const el_window = this;
|
||||
window.update_maximized_window_for_taskbar(el_window);
|
||||
});
|
||||
|
||||
// Re-initialize sortable with correct axis
|
||||
$('.taskbar-sortable').sortable('destroy');
|
||||
window.make_taskbar_sortable();
|
||||
|
||||
// Adjust taskbar item sizes for the new position
|
||||
setTimeout(() => {
|
||||
window.adjust_taskbar_item_sizes();
|
||||
}, 10);
|
||||
|
||||
// Reinitialize all taskbar item tooltips with new position
|
||||
$('.taskbar-item').each(function () {
|
||||
const $item = $(this);
|
||||
// Destroy existing tooltip
|
||||
if ( $item.data('ui-tooltip') ) {
|
||||
$item.tooltip('destroy');
|
||||
}
|
||||
|
||||
// Helper function to get tooltip position based on taskbar position
|
||||
function getTooltipPosition () {
|
||||
const taskbarPosition = window.taskbar_position || 'bottom';
|
||||
|
||||
if ( taskbarPosition === 'bottom' ) {
|
||||
return {
|
||||
my: 'center bottom-20',
|
||||
at: 'center top',
|
||||
};
|
||||
} else if ( taskbarPosition === 'top' ) {
|
||||
return {
|
||||
my: 'center top+20',
|
||||
at: 'center bottom',
|
||||
};
|
||||
} else if ( taskbarPosition === 'left' ) {
|
||||
return {
|
||||
my: 'left+20 center',
|
||||
at: 'right center',
|
||||
};
|
||||
} else if ( taskbarPosition === 'right' ) {
|
||||
return {
|
||||
my: 'right-20 center',
|
||||
at: 'left center',
|
||||
};
|
||||
}
|
||||
return {
|
||||
my: 'center bottom-20',
|
||||
at: 'center top',
|
||||
}; // fallback
|
||||
}
|
||||
|
||||
const tooltipPosition = getTooltipPosition();
|
||||
|
||||
// Reinitialize tooltip with new position
|
||||
$item.tooltip({
|
||||
items: ".taskbar:not(.children-have-open-contextmenu) .taskbar-item:not([data-app='separator'])",
|
||||
position: {
|
||||
my: tooltipPosition.my,
|
||||
at: tooltipPosition.at,
|
||||
using: function ( position, feedback ) {
|
||||
$(this).css( position);
|
||||
$('<div>')
|
||||
.addClass( 'arrow')
|
||||
.addClass( feedback.vertical)
|
||||
.addClass( feedback.horizontal)
|
||||
.appendTo( this);
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Function to update desktop dimensions based on taskbar position
|
||||
window.update_desktop_dimensions_for_taskbar = function () {
|
||||
const position = window.taskbar_position || 'bottom';
|
||||
|
||||
if ( position === 'bottom' ) {
|
||||
$('.desktop').css({
|
||||
'height': `calc(100vh - ${window.taskbar_height + window.toolbar_height}px)`,
|
||||
'width': '100%',
|
||||
'left': '0',
|
||||
'top': `${window.toolbar_height}px`,
|
||||
});
|
||||
} else if ( position === 'left' ) {
|
||||
$('.desktop').css({
|
||||
'height': `calc(100vh - ${window.toolbar_height}px)`,
|
||||
'width': `calc(100% - ${window.taskbar_height}px)`,
|
||||
'left': `${window.taskbar_height}px`,
|
||||
'top': `${window.toolbar_height}px`,
|
||||
});
|
||||
} else if ( position === 'right' ) {
|
||||
$('.desktop').css({
|
||||
'height': `calc(100vh - ${window.toolbar_height}px)`,
|
||||
'width': `calc(100% - ${window.taskbar_height}px)`,
|
||||
'left': '0',
|
||||
'top': `${window.toolbar_height}px`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
//-------------------------------------------
|
||||
// Dynamic taskbar item resizing for left/right positions
|
||||
//-------------------------------------------
|
||||
window.adjust_taskbar_item_sizes = function () {
|
||||
const position = window.taskbar_position || 'bottom';
|
||||
|
||||
// Only apply to left and right positions
|
||||
if ( position !== 'left' && position !== 'right' ) {
|
||||
// Reset to default sizes for bottom position
|
||||
$('.taskbar .taskbar-item').css({
|
||||
'width': '40px',
|
||||
'height': '40px',
|
||||
'min-width': '40px',
|
||||
'min-height': '40px',
|
||||
});
|
||||
$('.taskbar-icon').css('height', '40px');
|
||||
return;
|
||||
}
|
||||
|
||||
const taskbar = $('.taskbar')[0];
|
||||
const taskbarItems = $('.taskbar .taskbar-item:visible');
|
||||
|
||||
if ( !taskbar || taskbarItems.length === 0 ) return;
|
||||
|
||||
// Get available height (minus padding)
|
||||
const totalItemsNeeded = taskbarItems.length;
|
||||
const taskbarHeight = taskbar.clientHeight;
|
||||
const paddingTop = 20; // from CSS
|
||||
const paddingBottom = 20; // from CSS
|
||||
const availableHeight = taskbarHeight - paddingTop - paddingBottom - 180;
|
||||
|
||||
// Calculate space needed with default sizes
|
||||
const defaultItemSize = 40;
|
||||
const defaultMargin = 5;
|
||||
const spaceNeededDefault = (totalItemsNeeded * defaultItemSize) + ((totalItemsNeeded - 1) * defaultMargin);
|
||||
|
||||
if ( spaceNeededDefault <= availableHeight ) {
|
||||
// No overflow, use default sizes
|
||||
taskbarItems.css({
|
||||
'width': '40px',
|
||||
'height': '40px',
|
||||
'min-width': '40px',
|
||||
'min-height': '40px',
|
||||
'padding': '6px 5px 10px 5px', // default padding
|
||||
});
|
||||
$('.taskbar-icon').css('height', `${defaultItemSize }px`);
|
||||
$('.taskbar-icon').css('width', '40px');
|
||||
$('.taskbar-icon > img').css('width', 'auto');
|
||||
$('.taskbar-icon > img').css('margin', 'auto');
|
||||
$('.taskbar-icon > img').css('display', 'block');
|
||||
|
||||
// Reset margins to default
|
||||
taskbarItems.css('margin-bottom', '5px');
|
||||
taskbarItems.last().css('margin-bottom', '0px');
|
||||
} else {
|
||||
// Overflow detected, calculate smaller sizes
|
||||
// Reserve some margin space (minimum 2px between items)
|
||||
const minMargin = 2;
|
||||
const marginSpace = (totalItemsNeeded - 1) * minMargin;
|
||||
const availableForItems = availableHeight - marginSpace;
|
||||
const newItemSize = Math.floor(availableForItems / totalItemsNeeded);
|
||||
|
||||
// Ensure minimum size of 20px
|
||||
const finalItemSize = Math.max(20, newItemSize);
|
||||
|
||||
// Calculate proportional padding based on size ratio
|
||||
const sizeRatio = finalItemSize / defaultItemSize;
|
||||
const paddingTop = Math.max(1, Math.floor(6 * sizeRatio));
|
||||
const paddingRight = Math.max(1, Math.floor(5 * sizeRatio));
|
||||
const paddingBottom = Math.max(1, Math.floor(10 * sizeRatio));
|
||||
const paddingLeft = Math.max(1, Math.floor(5 * sizeRatio));
|
||||
|
||||
// Apply new sizes and padding
|
||||
taskbarItems.css({
|
||||
'width': '40px',
|
||||
'height': `${finalItemSize }px`,
|
||||
'min-width': '40px',
|
||||
'min-height': `${finalItemSize }px`,
|
||||
'padding': `${paddingTop}px ${paddingRight}px ${paddingBottom}px ${paddingLeft}px`,
|
||||
});
|
||||
$('.taskbar-icon').css('height', `${finalItemSize }px`);
|
||||
$('.taskbar-icon').css('width', '40px');
|
||||
$('.taskbar-icon > img').css('width', 'auto');
|
||||
$('.taskbar-icon > img').css('margin', 'auto');
|
||||
$('.taskbar-icon > img').css('display', 'block');
|
||||
// Adjust margins
|
||||
taskbarItems.css('margin-bottom', `${minMargin }px`);
|
||||
taskbarItems.last().css('margin-bottom', '0px');
|
||||
}
|
||||
};
|
||||
|
||||
// Hook into existing taskbar functionality
|
||||
$(document).ready(function () {
|
||||
// Watch for taskbar item changes
|
||||
const observer = new MutationObserver(function (mutations) {
|
||||
mutations.forEach(function (mutation) {
|
||||
if ( mutation.type === 'childList' || mutation.type === 'attributes' ) {
|
||||
// Delay to ensure DOM updates are complete
|
||||
setTimeout(() => {
|
||||
window.adjust_taskbar_item_sizes();
|
||||
}, 10);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Start observing when taskbar is available
|
||||
const checkTaskbar = setInterval(() => {
|
||||
const taskbar = document.querySelector('.taskbar-sortable');
|
||||
if ( taskbar ) {
|
||||
observer.observe(taskbar, {
|
||||
childList: true,
|
||||
attributes: true,
|
||||
subtree: true,
|
||||
});
|
||||
clearInterval(checkTaskbar);
|
||||
|
||||
// Initial call
|
||||
setTimeout(() => {
|
||||
window.adjust_taskbar_item_sizes();
|
||||
}, 100);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
// Also watch for window resize events
|
||||
window.addEventListener('resize', () => {
|
||||
setTimeout(() => {
|
||||
window.adjust_taskbar_item_sizes();
|
||||
}, 10);
|
||||
});
|
||||
});
|
||||
|
||||
export default UITaskbar;
|
||||
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user