mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a1ff1491c | ||
|
|
5dd2c53d12 | ||
|
|
711ece5800 | ||
|
|
40ea3686da | ||
|
|
db7ca8382b | ||
|
|
0f2c325598 | ||
|
|
ffcfb85749 | ||
|
|
44bf99f808 | ||
|
|
d392b6857d | ||
|
|
d8c3e01dd9 | ||
|
|
4bc679956f | ||
|
|
b751f75467 | ||
|
|
224b2f2367 | ||
|
|
80bcc4ba14 | ||
|
|
f26201649a | ||
|
|
1550be358d |
No files matched your search
@@ -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
|
||||
```
|
||||
@@ -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`', {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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(
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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' },
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1727,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`;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -1,114 +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 { UIColorPickerWidget, hslaToHex8 } from './UIColorPickerWidget.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
const UIWindowThemeDialog = async function UIWindowThemeDialog (options) {
|
||||
options = options ?? {};
|
||||
const services = globalThis.services;
|
||||
const svc_theme = services.get('theme');
|
||||
|
||||
// Get current theme values and convert to hex8 for the color picker
|
||||
const currentHue = svc_theme.get('hue');
|
||||
const currentSat = svc_theme.get('sat');
|
||||
const currentLig = svc_theme.get('lig');
|
||||
const currentAlpha = svc_theme.get('alpha');
|
||||
const initialColor = hslaToHex8(currentHue, currentSat, currentLig, currentAlpha);
|
||||
|
||||
let h = '';
|
||||
h += '<div class="theme-dialog-content" style="display: flex; flex-direction: column; gap: 10pt;">';
|
||||
h += `<button class="button button-secondary reset-colors-btn">${i18n('reset_colors')}</button>`;
|
||||
h += '<div class="color-picker-container" style="padding: 0; margin-bottom: 10px;">';
|
||||
h += '<div class="picker"></div>';
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('ui_colors'),
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
has_head: true,
|
||||
stay_on_top: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
show_in_taskbar: false,
|
||||
window_class: 'window-alert',
|
||||
dominant: true,
|
||||
width: 350,
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
padding: '20px',
|
||||
'background-color': `hsla(
|
||||
var(--primary-hue),
|
||||
var(--primary-saturation),
|
||||
var(--primary-lightness),
|
||||
var(--primary-alpha))`,
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
},
|
||||
...options.window_options,
|
||||
onAppend: function (window) {
|
||||
// Initialize the color picker widget
|
||||
const colorPickerWidget = UIColorPickerWidget($(window).find('.picker'), {
|
||||
default: initialColor,
|
||||
onColorChange: (color) => {
|
||||
// Convert color to HSLA format for theme service
|
||||
const hsla = colorPickerWidget.getHSLA();
|
||||
const state = {
|
||||
hue: hsla.h,
|
||||
sat: hsla.s,
|
||||
lig: hsla.l,
|
||||
alpha: hsla.a,
|
||||
light_text: hsla.l < 60 ? true : false,
|
||||
};
|
||||
svc_theme.apply(state);
|
||||
},
|
||||
});
|
||||
|
||||
// Store widget reference on window for reset functionality
|
||||
$(window).data('colorPickerWidget', colorPickerWidget);
|
||||
},
|
||||
});
|
||||
|
||||
// Reset button handler
|
||||
$(el_window).find('.reset-colors-btn').on('click', function () {
|
||||
svc_theme.reset();
|
||||
// Update color picker to reflect reset values
|
||||
const colorPickerWidget = $(el_window).data('colorPickerWidget');
|
||||
if ( colorPickerWidget ) {
|
||||
const resetHue = svc_theme.get('hue');
|
||||
const resetSat = svc_theme.get('sat');
|
||||
const resetLig = svc_theme.get('lig');
|
||||
const resetAlpha = svc_theme.get('alpha');
|
||||
const resetColor = hslaToHex8(resetHue, resetSat, resetLig, resetAlpha);
|
||||
colorPickerWidget.setColor(resetColor);
|
||||
}
|
||||
});
|
||||
|
||||
return {};
|
||||
};
|
||||
|
||||
export default UIWindowThemeDialog;
|
||||
@@ -117,11 +117,6 @@
|
||||
--dashboard-bento-usage-surface: #eef2ff;
|
||||
--dashboard-bento-usage-header-bg: #e0e7ff;
|
||||
--dashboard-bento-usage-bar-fill: #ea580c;
|
||||
/* Emerald (matches the green icon accent used elsewhere) */
|
||||
--dashboard-bento-desktop-icon-bg: #059669;
|
||||
--dashboard-bento-desktop-icon-shadow: rgba(5, 150, 105, 0.22);
|
||||
--dashboard-bento-desktop-surface: #ecfdf5;
|
||||
--dashboard-bento-desktop-header-bg: #d1fae5;
|
||||
|
||||
--dashboard-shadow-subtle: rgba(0, 0, 0, 0.04);
|
||||
--dashboard-shadow-light: rgba(0, 0, 0, 0.06);
|
||||
@@ -244,10 +239,6 @@ body {
|
||||
--dashboard-bento-usage-surface: #1c1d2e;
|
||||
--dashboard-bento-usage-header-bg: #252a42;
|
||||
--dashboard-bento-usage-bar-fill: #fb923c;
|
||||
--dashboard-bento-desktop-icon-bg: #10b981;
|
||||
--dashboard-bento-desktop-icon-shadow: rgba(16, 185, 129, 0.32);
|
||||
--dashboard-bento-desktop-surface: #16241f;
|
||||
--dashboard-bento-desktop-header-bg: #172e26;
|
||||
|
||||
--dashboard-shadow-subtle: rgba(0, 0, 0, 0.2);
|
||||
--dashboard-shadow-light: rgba(0, 0, 0, 0.3);
|
||||
@@ -7386,11 +7377,6 @@ body.myapps-reordering .myapps-tile {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.dashboard .bento-card-fancy-icon-desktop {
|
||||
background-color: var(--dashboard-bento-desktop-icon-bg);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.dashboard .bento-card-fancy-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -7553,41 +7539,6 @@ body.myapps-reordering .myapps-tile {
|
||||
color: var(--dashboard-text-tertiary);
|
||||
}
|
||||
|
||||
/* Open Desktop bento card (full width; links to the desktop interface) */
|
||||
.dashboard .bento-desktop {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 18px 24px;
|
||||
background-color: var(--dashboard-bento-desktop-header-bg);
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
transition: box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.dashboard .bento-desktop:hover {
|
||||
box-shadow:
|
||||
0 2px 4px var(--dashboard-shadow-subtle),
|
||||
0 10px 28px var(--dashboard-bento-desktop-icon-shadow);
|
||||
}
|
||||
|
||||
.dashboard .bento-desktop:hover .bento-desktop-arrow {
|
||||
transform: translateX(3px);
|
||||
color: var(--dashboard-text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.dashboard .bento-desktop-arrow {
|
||||
margin-left: auto;
|
||||
font-size: 22px;
|
||||
font-weight: 300;
|
||||
line-height: 1;
|
||||
color: var(--dashboard-text-hint);
|
||||
transition: transform 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
/* Usage bento card (cool indigo surfaces; orange bars stay as progress accent) */
|
||||
.dashboard .bento-usage {
|
||||
grid-column: 1 / -1;
|
||||
@@ -7910,11 +7861,6 @@ body.myapps-reordering .myapps-tile {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dashboard .bento-desktop {
|
||||
padding: 16px 20px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dashboard .bento-card-fancy-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
|
||||
@@ -5037,17 +5037,21 @@ fieldset[name=number-code] {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
#storage-bar, #storage-bar-host, .usage-progbar {
|
||||
#storage-bar, #storage-bar-host, .usage-progbar, .usage-addon-bar {
|
||||
height: 100%;
|
||||
background-color: var(--dashboard-bento-usage-bar-fill, #ea580c);
|
||||
width: 0;
|
||||
transition: width 0.4s ease, background-color 0.4s ease;
|
||||
}
|
||||
|
||||
#storage-used-percent, .usage-progbar-percent {
|
||||
#storage-used-percent, .usage-progbar-percent, .usage-addon-percent {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.usage-addon {
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.usage-addon-credits {
|
||||
margin: 8px 0 0;
|
||||
font-size: 13px;
|
||||
|
||||
@@ -22,6 +22,7 @@ import { encode } from 'html-entities';
|
||||
import { loadLocale } from './i18n/embedI18n.js';
|
||||
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
|
||||
import { embedSession } from './helpers/embedSession.js';
|
||||
import { overlayGone } from './helpers/overlayGone.js';
|
||||
|
||||
window.$ = window.jQuery = jQuery;
|
||||
window.html_encode = value => encode(String(value ?? ''), { mode: 'nonAsciiPrintable' });
|
||||
@@ -37,18 +38,6 @@ const localeReady = loadLocale(window.locale);
|
||||
/** Answers only the page frame-ancestors pinned, which the feedback is for. */
|
||||
const tellHost = (data) => window.parent.postMessage(data, config.hostOrigin);
|
||||
|
||||
/** Resolves once the dialog's overlay has left the page, after its success pane and exit. */
|
||||
const overlayGone = () => new Promise((resolve) => {
|
||||
const gone = () => !document.querySelector('.app-feedback-overlay');
|
||||
if ( gone() ) return resolve();
|
||||
const observer = new MutationObserver(() => {
|
||||
if ( ! gone() ) return;
|
||||
observer.disconnect();
|
||||
resolve();
|
||||
});
|
||||
observer.observe(document.body, { childList: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the app feedback dialog for the framing page, as the signed-in user it
|
||||
* names. Without that user's session, or with an email still to confirm, the
|
||||
@@ -75,7 +64,8 @@ async function run () {
|
||||
let sent = false;
|
||||
try {
|
||||
sent = await UIWindowAppFeedback({ origin: config.hostOrigin, source: 'web' });
|
||||
await overlayGone();
|
||||
// After its success pane and exit.
|
||||
await overlayGone(document, '.app-feedback-overlay');
|
||||
} catch (e) {
|
||||
console.error('feedback embed: dialog failed', e);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resolves once no element matching `selector` is left on `doc`'s body, such
|
||||
* as a dialog's overlay after its exit transition.
|
||||
*
|
||||
* @param {Document} doc
|
||||
* @param {string} selector
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export const overlayGone = (doc, selector) => new Promise((resolve) => {
|
||||
const gone = () => !doc.querySelector(selector);
|
||||
if ( gone() ) return resolve();
|
||||
const observer = new doc.defaultView.MutationObserver(() => {
|
||||
if ( ! gone() ) return;
|
||||
observer.disconnect();
|
||||
resolve();
|
||||
});
|
||||
observer.observe(doc.body, { childList: true });
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { overlayGone } from './overlayGone.js';
|
||||
|
||||
const settled = async (promise) => {
|
||||
let done = false;
|
||||
promise.then(() => {
|
||||
done = true;
|
||||
});
|
||||
// Mutation observers report in a microtask.
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
return done;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
describe('overlayGone', () => {
|
||||
it('resolves at once when no overlay is on the page', async () => {
|
||||
expect(await settled(overlayGone(document, '.overlay'))).toBe(true);
|
||||
});
|
||||
|
||||
it('waits until the overlay is removed', async () => {
|
||||
document.body.innerHTML = '<div class="overlay"></div><p></p>';
|
||||
const gone = overlayGone(document, '.overlay');
|
||||
expect(await settled(gone)).toBe(false);
|
||||
|
||||
// Another element leaving isn't the overlay leaving.
|
||||
document.querySelector('p').remove();
|
||||
expect(await settled(gone)).toBe(false);
|
||||
|
||||
document.querySelector('.overlay').remove();
|
||||
expect(await settled(gone)).toBe(true);
|
||||
});
|
||||
|
||||
it('waits for every matching overlay', async () => {
|
||||
document.body.innerHTML = '<div class="overlay"></div><div class="overlay"></div>';
|
||||
const gone = overlayGone(document, '.overlay');
|
||||
document.querySelector('.overlay').remove();
|
||||
expect(await settled(gone)).toBe(false);
|
||||
document.querySelector('.overlay').remove();
|
||||
expect(await settled(gone)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -30,7 +30,9 @@ export const FRAMED_POPUP_ACTIONS = new Set([
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
]);
|
||||
|
||||
// Actions a frame shows only for the user the framing page is signed in as.
|
||||
@@ -39,17 +41,19 @@ const HOST_USER_ACTIONS = new Set([
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
]);
|
||||
|
||||
// Actions framed over the whole page with no box, which their own dialog's
|
||||
// scrim covers.
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'request-email-confirmation']);
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'top-up', 'request-email-confirmation', 'attach-custom-domain']);
|
||||
|
||||
const UPGRADE_REASONS = new Set(['funds', 'subscription', 'storage']);
|
||||
const UPGRADE_METHOD_MAX = 200;
|
||||
|
||||
// Modal UI the upgrade dialog and the GUI's windows show. Once some has shown
|
||||
// Modal UI the upgrade and top-up dialogs and the GUI's windows show. Once some has shown
|
||||
// and all of it has been gone this long, the dialog closed without reporting
|
||||
// it, and the frame mustn't be left covering the page.
|
||||
const UPGRADE_MODAL_UI = '.window, [aria-modal="true"]';
|
||||
@@ -64,7 +68,7 @@ const FOCUS_RETRIES = 20;
|
||||
export const POPUP_FRAME_MSG = 'puterPopupFrame';
|
||||
|
||||
// The popup's query parameters a framing page may pass, in the fragment.
|
||||
const FRAGMENT_PARAMS = ['msg_id', 'options', 'request_auth'];
|
||||
const FRAGMENT_PARAMS = ['msg_id', 'options', 'request_auth', 'subdomain'];
|
||||
|
||||
// The account checks a sign-in can show (email, phone, card), and the
|
||||
// save-account window an email confirmation shows a temporary account first,
|
||||
@@ -233,6 +237,20 @@ export const closeAccountChecksOnEscape = (win, close = () => win.close()) => {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the GUI session `session` (its `/whoami`) has no account check
|
||||
* waiting. Those show at boot with no way to close the frame.
|
||||
*
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
const hasNoAccountCheck = (session) =>
|
||||
!!session &&
|
||||
!session.requires_email_confirmation &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
|
||||
/**
|
||||
* Whether a framed upgrade can show for the GUI session `session` (its
|
||||
* `/whoami`): the deployment has an upgrade dialog that reports when it
|
||||
@@ -244,12 +262,29 @@ export const closeAccountChecksOnEscape = (win, close = () => win.close()) => {
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowUpgradeFrame = (win, session) =>
|
||||
win.UIUpgradeAccount?.embeddable === true &&
|
||||
!!session &&
|
||||
!session.requires_email_confirmation &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
win.UIUpgradeAccount?.embeddable === true && hasNoAccountCheck(session);
|
||||
|
||||
/**
|
||||
* Whether a framed custom domain dialog can show for the GUI session
|
||||
* `session` (its `/whoami`): no account check is waiting, which a frame
|
||||
* couldn't be closed from.
|
||||
*
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowCustomDomainFrame = (session) => hasNoAccountCheck(session);
|
||||
|
||||
/**
|
||||
* Whether a framed top-up can show for the GUI session `session` (its
|
||||
* `/whoami`): the deployment has a top-up dialog that reports when it closes,
|
||||
* and no account check is waiting, which a frame couldn't be closed from.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowTopUpFrame = (win, session) =>
|
||||
win.UITopUp?.embeddable === true && hasNoAccountCheck(session);
|
||||
|
||||
/**
|
||||
* Whether a framed email confirmation can show for the GUI session `session`
|
||||
@@ -300,19 +335,18 @@ export const framedUpgradeDetails = (hash) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the deployment's upgrade dialog in a framed popup and tells the
|
||||
* Shows one of the deployment's dialogs in a framed popup and tells the
|
||||
* framing page it's ready once it's open, or before it opens when the page
|
||||
* still hides the frame. Resolves whether the user upgraded,
|
||||
* once the dialog closes, or false once every dialog and window it showed has
|
||||
* gone without it reporting a close.
|
||||
* still hides the frame. Resolves what the dialog reports when it closes, or
|
||||
* false once every dialog and window it showed has gone without it reporting
|
||||
* a close.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(closed: (result: boolean) => void) => unknown} open - opens the dialog, which calls `closed` when it closes
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedUpgrade = (win, attribution, tell) => new Promise((resolve, reject) => {
|
||||
const showFramedDialog = (win, open, tell) => new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let seen = false;
|
||||
let goneTimer = null;
|
||||
@@ -345,21 +379,47 @@ export const showFramedUpgrade = (win, attribution, tell) => new Promise((resolv
|
||||
toldReady = true;
|
||||
tell('ready');
|
||||
};
|
||||
const open = () => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => settle(() => resolve(result?.upgraded === true)),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
};
|
||||
whenFrameSized(win, ready)
|
||||
.then(open)
|
||||
.then(() => open((result) => settle(() => resolve(result))))
|
||||
.then(() => {
|
||||
check();
|
||||
ready();
|
||||
}, (e) => settle(() => reject(e)));
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the deployment's upgrade dialog in a framed popup. Resolves whether
|
||||
* the user upgraded, once the dialog closes.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedUpgrade = (win, attribution, tell) => showFramedDialog(win, (closed) => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => closed(result?.upgraded === true),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
}, tell);
|
||||
|
||||
/**
|
||||
* Shows the deployment's top-up dialog in a framed popup. Resolves whether
|
||||
* the user bought credit, once the dialog closes.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedTopUp = (win, tell) => showFramedDialog(win, (closed) => {
|
||||
const dialog = new win.UITopUp({
|
||||
onClose: (result) => closed(result?.toppedUp === true),
|
||||
});
|
||||
return dialog.open();
|
||||
}, tell);
|
||||
|
||||
/**
|
||||
* Resolves once the frame has a viewport. The page keeps a loading frame
|
||||
* hidden, which Chromium and WebKit lay out at 0x0, and a GUI window opened
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
POPUP_FRAME_MSG,
|
||||
canShowCustomDomainFrame,
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowTopUpFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
@@ -11,6 +13,7 @@ import {
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedTopUp,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './popupFrame.js';
|
||||
@@ -50,7 +53,9 @@ describe('framedPopupAction', () => {
|
||||
['/embed/show-save-file-picker', 'show-save-file-picker'],
|
||||
['/embed/show-directory-picker', 'show-directory-picker'],
|
||||
['/embed/upgrade', 'upgrade'],
|
||||
['/embed/top-up', 'top-up'],
|
||||
['/embed/request-email-confirmation', 'request-email-confirmation'],
|
||||
['/embed/attach-custom-domain', 'attach-custom-domain'],
|
||||
['/embed/apps', null],
|
||||
['/embed/feedback', null],
|
||||
['/embed/request-permission', null],
|
||||
@@ -65,11 +70,12 @@ describe('framedPopupAction', () => {
|
||||
|
||||
describe('framedPopupParams', () => {
|
||||
it('keeps only the popup parameters a framing page may pass', () => {
|
||||
const params = framedPopupParams('#msg_id=7&options=%7B%22multiple%22%3Atrue%7D&request_auth=true&user=abc&auth_token=x&attempt_temp_user_creation=true&api_origin=https%3A%2F%2Fevil.test');
|
||||
const params = framedPopupParams('#msg_id=7&options=%7B%22multiple%22%3Atrue%7D&request_auth=true&subdomain=mysite&user=abc&auth_token=x&attempt_temp_user_creation=true&api_origin=https%3A%2F%2Fevil.test');
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
msg_id: '7',
|
||||
options: '{"multiple":true}',
|
||||
request_auth: 'true',
|
||||
subdomain: 'mysite',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -85,7 +91,9 @@ describe('framesHostUser', () => {
|
||||
['show-save-file-picker', true],
|
||||
['show-directory-picker', true],
|
||||
['upgrade', true],
|
||||
['top-up', true],
|
||||
['request-email-confirmation', true],
|
||||
['attach-custom-domain', true],
|
||||
['sign-in', false],
|
||||
[null, false],
|
||||
])('%s serves only the framing page\'s user: %s', (action, expected) => {
|
||||
@@ -133,6 +141,55 @@ describe('canShowUpgradeFrame', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowTopUpFrame', () => {
|
||||
const win = { UITopUp: Object.assign(function () {}, { embeddable: true }) };
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify, when the dialog reports its close', () => {
|
||||
expect(canShowTopUpFrame(win, session)).toBe(true);
|
||||
});
|
||||
|
||||
it('needs a top-up dialog that reports its close, whatever the upgrade dialog does', () => {
|
||||
expect(canShowTopUpFrame({}, session)).toBe(false);
|
||||
expect(canShowTopUpFrame({ UITopUp: function () {} }, session)).toBe(false);
|
||||
expect(canShowTopUpFrame({ UIUpgradeAccount: Object.assign(function () {}, { embeddable: true }) }, session)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s to the tab', (check) => {
|
||||
expect(canShowTopUpFrame(win, { ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowTopUpFrame(win, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowCustomDomainFrame', () => {
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify', () => {
|
||||
expect(canShowCustomDomainFrame(session)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s to the popup', (check) => {
|
||||
expect(canShowCustomDomainFrame({ ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowCustomDomainFrame(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowEmailConfirmationFrame', () => {
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
@@ -361,6 +418,64 @@ describe('showFramedUpgrade', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('showFramedTopUp', () => {
|
||||
const topUpWindow = (open) => {
|
||||
const events = new EventTarget();
|
||||
return {
|
||||
document,
|
||||
innerWidth: 1280,
|
||||
innerHeight: 800,
|
||||
addEventListener: events.addEventListener.bind(events),
|
||||
removeEventListener: events.removeEventListener.bind(events),
|
||||
MutationObserver: window.MutationObserver,
|
||||
UITopUp: function (options) {
|
||||
this.open = () => open(options);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('tells the page it is ready once open, and resolves whether credit was bought', async () => {
|
||||
const tell = vi.fn();
|
||||
let options;
|
||||
const result = showFramedTopUp(topUpWindow(async (o) => {
|
||||
options = o;
|
||||
}), tell);
|
||||
await vi.waitFor(() => expect(tell).toHaveBeenCalledWith('ready'));
|
||||
expect(tell).toHaveBeenCalledTimes(1);
|
||||
|
||||
options.onClose({ toppedUp: true });
|
||||
await expect(result).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('resolves false for a close without a purchase', async () => {
|
||||
await expect(showFramedTopUp(topUpWindow(async (o) => o.onClose({ toppedUp: false })), vi.fn())).resolves.toBe(false);
|
||||
await expect(showFramedTopUp(topUpWindow(async (o) => o.onClose()), vi.fn())).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('resolves false once the dialog is gone without reporting a close', async () => {
|
||||
vi.useFakeTimers();
|
||||
const root = document.createElement('div');
|
||||
root.setAttribute('aria-modal', 'true');
|
||||
const result = showFramedTopUp(topUpWindow(async () => {
|
||||
document.body.append(root);
|
||||
}), vi.fn());
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
root.remove();
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects when the dialog fails to open', async () => {
|
||||
await expect(showFramedTopUp(topUpWindow(async () => {
|
||||
throw new Error('no dialog');
|
||||
}), vi.fn())).rejects.toThrow('no dialog');
|
||||
});
|
||||
});
|
||||
|
||||
describe('startPopupFrame', () => {
|
||||
it('does nothing without a framing page to answer', () => {
|
||||
const win = frameWindow();
|
||||
@@ -396,6 +511,11 @@ describe('startPopupFrame', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the framing page show through a top-up frame', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/top-up' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
});
|
||||
|
||||
it('lets the framing page show through an upgrade or email confirmation frame only', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/sign-in' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(false);
|
||||
@@ -406,6 +526,10 @@ describe('startPopupFrame', () => {
|
||||
document.documentElement.classList.remove('popup-frame-transparent');
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/request-email-confirmation' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
|
||||
document.documentElement.classList.remove('popup-frame-transparent');
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/attach-custom-domain' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
});
|
||||
|
||||
it('sends a boolean field with a state', () => {
|
||||
|
||||
@@ -41,7 +41,6 @@ const ar = {
|
||||
change_email: 'تغيير البريد الإلكتروني',
|
||||
change_language: 'تغيير اللغة',
|
||||
change_password: 'تغيير كلمة المرور',
|
||||
change_ui_colors: 'تغيير ألوان واجهة المستخدم',
|
||||
change_username: 'تغيير اسم المستخدم',
|
||||
close: 'إغلاق',
|
||||
close_all_windows: 'إغلاق جميع النوافذ',
|
||||
@@ -251,7 +250,6 @@ const ar = {
|
||||
replace: 'استبدال',
|
||||
replace_all: 'استبدال الكل',
|
||||
resend_confirmation_code: 'إعادة إرسال رمز التأكيد',
|
||||
reset_colors: 'إعادة ضبط الألوان',
|
||||
restart_puter_confirm: '؟Puter.com! هل أنت متأكد أنك تريد إعادة تشغيل',
|
||||
restore: 'استعادة',
|
||||
save: 'حفظ',
|
||||
@@ -310,7 +308,6 @@ const ar = {
|
||||
two_factor_enabled: 'تم تمكين المصادقة الثنائية',
|
||||
type: 'نوع',
|
||||
type_confirm_to_delete_account: ".اكتب 'تأكيد' لحذف حسابك",
|
||||
ui_colors: 'ألوان واجهة المستخدم',
|
||||
ui_manage_sessions: 'مدير الجلسات',
|
||||
ui_revoke: 'إلغاء',
|
||||
undo: 'تراجع',
|
||||
|
||||
@@ -43,7 +43,6 @@ const bg = {
|
||||
change_email: 'Промяна на имейл',
|
||||
change_language: 'Промяна на езика',
|
||||
change_password: 'Промяна на паролата',
|
||||
change_ui_colors: 'Промяна на цветовете на интерфейса',
|
||||
change_username: 'Промяна на потребителското име',
|
||||
close: 'Затвори',
|
||||
close_all_windows: 'Затвори всички прозорци',
|
||||
@@ -268,7 +267,6 @@ const bg = {
|
||||
replace: 'Замени',
|
||||
replace_all: 'Замени всички',
|
||||
resend_confirmation_code: 'Изпрати отново кода за потвърждение',
|
||||
reset_colors: 'Нулирай цветовете',
|
||||
restart_puter_confirm: 'Сигурни ли сте, че искате да рестартирате Puter?',
|
||||
restore: 'Възстанови',
|
||||
save: 'Запази',
|
||||
@@ -338,7 +336,6 @@ const bg = {
|
||||
type: 'Тип',
|
||||
type_confirm_to_delete_account:
|
||||
"Въведете 'confirm', за да изтриете акаунта си.",
|
||||
ui_colors: 'Цветове на интерфейса',
|
||||
ui_manage_sessions: 'Управление на сесии',
|
||||
ui_revoke: 'Отмени',
|
||||
undo: 'Върни',
|
||||
|
||||
@@ -41,7 +41,6 @@ const bn = {
|
||||
change_email: 'ই-মেইল পরিবর্তন করুন',
|
||||
change_language: 'ভাষা পরিবর্তন করুন',
|
||||
change_password: 'পাসওয়ার্ড পরিবর্তন করুন',
|
||||
change_ui_colors: 'ইউআই রঙ পরিবর্তন করুন',
|
||||
change_username: 'ইউজারনেম পরিবর্তন করুন',
|
||||
close: 'বন্ধ করুন',
|
||||
close_all_windows: 'সমস্ত উইন্ডো বন্ধ করুন',
|
||||
@@ -234,7 +233,6 @@ const bn = {
|
||||
replace: 'বদলান',
|
||||
replace_all: 'সকল কিছু বদলান',
|
||||
resend_confirmation_code: 'পুনরায় নিশ্চিতকরণ কোড প্রেরণ করুন',
|
||||
reset_colors: 'রঙ পুনঃনির্ধারণ করুন',
|
||||
restart_puter_confirm: 'আপনি কি নিশ্চিত যে Puter পুনরায় চালু করতে চান?',
|
||||
restore: 'পুনরুদ্ধার',
|
||||
save: 'সংরক্ষণ করুন',
|
||||
@@ -291,7 +289,6 @@ const bn = {
|
||||
two_factor_enabled: '2FA সক্ষম',
|
||||
type: 'ধরণ',
|
||||
type_confirm_to_delete_account: "অ্যাকাউন্ট মোছার জন্য 'অনুমোদন' টাইপ করুন।",
|
||||
ui_colors: 'ইউআই রঙ',
|
||||
ui_manage_sessions: 'সেশন ম্যানেজার',
|
||||
ui_revoke: 'প্রত্যাহার করুন',
|
||||
undo: 'পূর্বাবস্থায় ফেরত যান',
|
||||
|
||||
@@ -41,7 +41,6 @@ const br = {
|
||||
change_email: 'Mudar Email',
|
||||
change_language: 'Mudar Idioma',
|
||||
change_password: 'Mudar Senha',
|
||||
change_ui_colors: 'Mudar Cores da Interface',
|
||||
change_username: 'Mudar Nome de Usuário',
|
||||
close: 'Fechar',
|
||||
close_all_windows: 'Fechar Todas as Janelas',
|
||||
@@ -231,7 +230,6 @@ const br = {
|
||||
'replace': 'Substituir',
|
||||
'replace_all': 'Substituir Todos',
|
||||
'resend_confirmation_code': 'Reenviar Código de Confirmação',
|
||||
'reset_colors': 'Redefinir Cores',
|
||||
'restart_puter_confirm': 'Tem certeza de que deseja reiniciar o Puter?',
|
||||
'restore': 'Restaurar',
|
||||
'save': 'Salvar',
|
||||
@@ -288,7 +286,6 @@ const br = {
|
||||
'two_factor_enabled': '2FA Ativada',
|
||||
'type': 'Tipo',
|
||||
'type_confirm_to_delete_account': 'Digite \'confirmar\' para excluir sua conta.',
|
||||
'ui_colors': 'Cores da Interface',
|
||||
'ui_manage_sessions': 'Gerenciador de Sessões',
|
||||
'ui_revoke': 'Revogar',
|
||||
'undo': 'Desfazer',
|
||||
|
||||
@@ -81,7 +81,6 @@ const cs = {
|
||||
"change_email": "Změnit e-mail",
|
||||
"revalidated": "Znovu ověřeno.",
|
||||
"color_depth": "Barevná hloubka",
|
||||
"change_ui_colors": "Změnit barvy uživatelského rozhraní",
|
||||
"revalidate_with_google": "Znovu ověřte pomocí Googlu",
|
||||
"color": "Barva",
|
||||
"confirm": "Potvrdit",
|
||||
@@ -235,7 +234,6 @@ const cs = {
|
||||
"open_in_new_tab": "Otevřít na nové kartě",
|
||||
"open_in_new_window": "Otevřít v novém okně",
|
||||
"new_email": "Nový e-mail",
|
||||
"open_desktop": "Otevřít plochu",
|
||||
"new_username": "Nové uživatelské jméno",
|
||||
"open_with_ai": "Otevřít pomocí AI",
|
||||
"os": "Operační systém",
|
||||
@@ -319,7 +317,6 @@ const cs = {
|
||||
"restore": "Obnovit",
|
||||
"save": "Uložit",
|
||||
"saturation": "Nasycení",
|
||||
"reset_colors": "Obnovit barvy",
|
||||
"replace_all": "Nahradit vše",
|
||||
"recover_password": "Obnovit heslo",
|
||||
"publish_as_serverless_worker": "Publikovat jako pracovník",
|
||||
@@ -471,7 +468,6 @@ const cs = {
|
||||
"ui_search": "Hledat relace…",
|
||||
"ui_session_count_one": "1 aktivní relace",
|
||||
"ui_rename": "Přejmenovat relaci",
|
||||
"ui_colors": "Barvy uživatelského rozhraní",
|
||||
"ui_session_kind_access_token": "Přístupový token",
|
||||
"ui_session_kind_worker": "Pracovník",
|
||||
"undo": "Vrátit zpět",
|
||||
|
||||
@@ -41,7 +41,6 @@ const da = {
|
||||
change_email: 'Ændre e-mail',
|
||||
change_language: 'Ændre sprog',
|
||||
change_password: 'Ændre adgangskode',
|
||||
change_ui_colors: 'Ændre UI-farver',
|
||||
change_username: 'Ændre brugernavn',
|
||||
close: 'Luk',
|
||||
close_all_windows: 'Luk alle vinduer',
|
||||
@@ -231,7 +230,6 @@ const da = {
|
||||
replace: 'Erstat',
|
||||
replace_all: 'Erstat alle',
|
||||
resend_confirmation_code: 'Send bekræftelseskode igen',
|
||||
reset_colors: 'Nulstil farver',
|
||||
restart_puter_confirm: 'Er du sikker på, at du vil genstarte Puter?',
|
||||
restore: 'Gendan',
|
||||
save: 'Gem',
|
||||
@@ -288,7 +286,6 @@ const da = {
|
||||
two_factor_enabled: '2FA aktiveret',
|
||||
type: 'Type',
|
||||
type_confirm_to_delete_account: "Skriv 'bekræft' for at slette din konto.",
|
||||
ui_colors: 'UI-farver',
|
||||
ui_manage_sessions: 'Sessionshåndtering',
|
||||
ui_revoke: 'Tilbagekald',
|
||||
undo: 'Fortryd',
|
||||
|
||||
@@ -41,7 +41,6 @@ const de = {
|
||||
change_email: 'E-Mail ändern',
|
||||
change_language: 'Sprache ändern',
|
||||
change_password: 'Passwort ändern',
|
||||
change_ui_colors: 'Farben der UI ändern',
|
||||
change_username: 'Benutzername ändern',
|
||||
close: 'Schließen',
|
||||
close_all_windows: 'Alle Fenster schließen',
|
||||
@@ -230,7 +229,6 @@ const de = {
|
||||
replace: 'Ersetzen',
|
||||
replace_all: 'Alles ersetzen',
|
||||
resend_confirmation_code: 'Bestätigungscode erneut senden',
|
||||
reset_colors: 'Farben zurücksetzen',
|
||||
restart_puter_confirm: 'Möchten Sie Puter wirklich neu starten?',
|
||||
restore: 'Wiederherstellen',
|
||||
save: 'Speichern',
|
||||
@@ -287,7 +285,6 @@ const de = {
|
||||
two_factor_enabled: '2FA aktiviert',
|
||||
type: 'Typ',
|
||||
type_confirm_to_delete_account: "Geben Sie 'confirm' ein, um Ihr Konto zu löschen.",
|
||||
ui_colors: 'Farben der Benutzeroberfläche',
|
||||
ui_manage_sessions: 'Sitzungsmanager',
|
||||
ui_revoke: 'Widerrufen',
|
||||
undo: 'Rückgängig machen',
|
||||
|
||||
@@ -28,6 +28,7 @@ const en = {
|
||||
account_password: 'Verify Account Password',
|
||||
access_granted_to: 'Access Granted To',
|
||||
add_another_account: 'Add Another Account',
|
||||
addon_credits: 'Add-on credits',
|
||||
addon_credits_available: '+ {{amount}} add-on credits left',
|
||||
addon_credits_note: 'Used once your monthly credits run out.',
|
||||
add_app: 'Add an app',
|
||||
@@ -85,7 +86,6 @@ const en = {
|
||||
change_language: 'Change Language',
|
||||
change_password: 'Change Password',
|
||||
change_profile_picture: 'Change profile picture',
|
||||
change_ui_colors: 'Change UI Colors',
|
||||
change_username: 'Change Username',
|
||||
username_set_by_team: 'Set by {{team}}. Ask an admin to change it.',
|
||||
username_set_by_team_generic: 'Set by your team. Ask an admin to change it.',
|
||||
@@ -327,6 +327,7 @@ const en = {
|
||||
delete_account_description: 'Permanently delete your account and all associated data. This action cannot be undone.',
|
||||
modified: 'Modified',
|
||||
monthly_credits: 'monthly credits',
|
||||
monthly_credits_title: 'Monthly credits',
|
||||
move: 'Move',
|
||||
moving_file: 'Moving %%',
|
||||
my_websites: 'My Websites',
|
||||
@@ -368,7 +369,6 @@ const en = {
|
||||
or: 'or',
|
||||
open: 'Open',
|
||||
new_window: 'New Window',
|
||||
open_desktop: 'Open Desktop',
|
||||
open_with_ai: 'Open with AI',
|
||||
open_in_new_tab: 'Open in New Tab',
|
||||
app_pages: 'App pages',
|
||||
@@ -545,7 +545,6 @@ const en = {
|
||||
email_code_sent_to: 'To continue, please enter the 6-digit confirmation code sent to',
|
||||
email_code_sent_to_your_address: 'To continue, please enter the 6-digit confirmation code sent to your email address',
|
||||
resend_confirmation_code: 'Re-send Confirmation Code',
|
||||
reset_colors: 'Reset Colors',
|
||||
resource: 'Resource',
|
||||
'Resources': 'Resources',
|
||||
restart_puter_confirm: 'Are you sure you want to restart Puter?',
|
||||
@@ -777,7 +776,6 @@ const en = {
|
||||
no_recent_apps_hint: 'Apps you use will appear here',
|
||||
recently_used: 'Recently used',
|
||||
monthly_overview: 'Monthly overview',
|
||||
open_desktop_hint: 'Switch to the desktop interface',
|
||||
taking_longer_than_usual: 'Taking a little longer than usual. Please wait...',
|
||||
email_needed_to_create_token: 'This account has no email address, which tokens require.',
|
||||
payments_not_configured: 'Payments are not configured on this deployment.',
|
||||
@@ -807,7 +805,6 @@ const en = {
|
||||
two_factor_enabled: '2FA Enabled',
|
||||
type: 'Type',
|
||||
type_confirm_to_delete_account: "Type 'confirm' to delete your account.",
|
||||
ui_colors: 'UI Colors',
|
||||
ui_manage_sessions: 'Session Manager',
|
||||
ui_rename: 'Rename session',
|
||||
ui_revoke: 'Revoke',
|
||||
|
||||
@@ -48,7 +48,6 @@ const es = {
|
||||
change_email: 'Cambiar Correo Electrónico',
|
||||
change_language: 'Cambiar Idioma',
|
||||
change_password: 'Cambiar Contraseña',
|
||||
change_ui_colors: 'Cambiar colores de la interfaz',
|
||||
change_username: 'Cambiar Nombre de Usuario',
|
||||
close: 'Cerrar',
|
||||
close_all_windows: 'Cerrar todas las ventanas',
|
||||
@@ -263,7 +262,6 @@ const es = {
|
||||
replace: 'Remplazar',
|
||||
replace_all: 'Replace All',
|
||||
resend_confirmation_code: 'Reenviar Código de Confirmación',
|
||||
reset_colors: 'Restablecer colores',
|
||||
restart_puter_confirm: '¿Estás seguro que deseas reiniciar Puter?',
|
||||
restore: 'Restaurar',
|
||||
save: 'Guardar',
|
||||
@@ -325,7 +323,6 @@ const es = {
|
||||
type: 'Tipo',
|
||||
type_confirm_to_delete_account:
|
||||
"Ingrese 'Confirmar' para borrar esta cuenta.",
|
||||
ui_colors: 'Colores de interfaz',
|
||||
ui_manage_sessions: 'Administrador de sesión',
|
||||
ui_revoke: 'Revocar',
|
||||
undo: 'Deshacer',
|
||||
|
||||
@@ -43,7 +43,6 @@ const fa = {
|
||||
change_email: 'تغییر ایمیل',
|
||||
change_language: 'تغییر زبان',
|
||||
change_password: 'تغییر رمز عبور',
|
||||
change_ui_colors: 'تغییر رنگهای رابط کاربری',
|
||||
change_username: 'تغییر نام کاربری',
|
||||
close: 'بستن',
|
||||
close_all_windows: 'بستن همه پنجره ها',
|
||||
@@ -255,7 +254,6 @@ const fa = {
|
||||
replace: 'جایگزین کردن',
|
||||
replace_all: 'جایگزینی همه',
|
||||
resend_confirmation_code: 'ارسال مجدد کد تأیید',
|
||||
reset_colors: 'بازنشانی رنگ ها',
|
||||
restart_puter_confirm:
|
||||
'آیا مطمئن هستید که میخواهید پیوتر را مجددا راه اندازی کنید',
|
||||
restore: 'بازیابی',
|
||||
@@ -316,7 +314,6 @@ const fa = {
|
||||
type: 'نوع',
|
||||
type_confirm_to_delete_account:
|
||||
"عبارت 'تأیید' را برای حذف حساب خود وارد کنید",
|
||||
ui_colors: 'رنگهای رابط کاربری',
|
||||
ui_manage_sessions: 'مدیریت نشستها', // TN: better to use sessions instead of نشستها
|
||||
ui_revoke: 'لغو',
|
||||
undo: 'بازگشت',
|
||||
|
||||
@@ -47,7 +47,6 @@ const fi = {
|
||||
change_email: 'Vaihda sähköpostiosoite',
|
||||
change_language: 'Vaihda kieli',
|
||||
change_password: 'Vaihda salasana',
|
||||
change_ui_colors: 'Vaihda käyttöliittymän värejä',
|
||||
change_username: 'Vaihda käyttäjänimi',
|
||||
close: 'Sulje',
|
||||
close_all_windows: 'Sulje kaikki ikkunat',
|
||||
@@ -302,7 +301,6 @@ const fi = {
|
||||
replace: 'Replace',
|
||||
replace_all: 'Korvaa kaikki',
|
||||
resend_confirmation_code: 'Lähetä vahvistuskoodi Uudelleen',
|
||||
reset_colors: 'Palauta värit',
|
||||
restart_puter_confirm: 'Haluatko varmasti käynnistää Puterin uudelleen?',
|
||||
restore: 'Palauta',
|
||||
save: 'Tallenna',
|
||||
@@ -375,7 +373,6 @@ const fi = {
|
||||
// "Type on the keyboard" => 'Kirjoita'
|
||||
|
||||
type_confirm_to_delete_account: "Kirjoita 'vahvista' poistaaksesi tilisi.",
|
||||
ui_colors: 'Käyttöliittymän värit',
|
||||
ui_manage_sessions: 'Istunnon hallinta',
|
||||
ui_revoke: 'Peruuta',
|
||||
undo: 'Kumoa',
|
||||
|
||||
@@ -41,7 +41,6 @@ const fil = {
|
||||
change_email: 'Baguhin ang email',
|
||||
change_language: 'Baguhin ang wika',
|
||||
change_password: 'Baguhin ang password',
|
||||
change_ui_colors: 'Baguhin ang kulay ng UI',
|
||||
change_username: 'Baguhin ang username',
|
||||
close: 'Isara',
|
||||
close_all_windows: 'Isara ang lahat ng window',
|
||||
@@ -243,7 +242,6 @@ const fil = {
|
||||
replace: 'Palitan',
|
||||
replace_all: 'Palitan lahat',
|
||||
resend_confirmation_code: 'Ipadala ulit ang confirmation code',
|
||||
reset_colors: 'I-reset ang mga kulay',
|
||||
restart_puter_confirm: 'Ire-restart mo ba ang Puter?',
|
||||
restore: 'I-restore',
|
||||
save: 'I-save',
|
||||
@@ -302,7 +300,6 @@ const fil = {
|
||||
two_factor_enabled: 'Naka-enable ang 2FA',
|
||||
type: 'Uri',
|
||||
type_confirm_to_delete_account: "I-type ang 'confirm' para burahin ang account mo.",
|
||||
ui_colors: 'Mga kulay ng UI',
|
||||
ui_manage_sessions: 'Tagapamahala ng session',
|
||||
ui_revoke: 'Bawiin',
|
||||
undo: 'I-undo',
|
||||
|
||||
@@ -46,7 +46,6 @@ const fr = {
|
||||
change_email: "Changer l'e-mail",
|
||||
change_language: 'Changer de langue',
|
||||
change_password: 'Changer le mot de passe',
|
||||
change_ui_colors: "Changer les couleurs de l'interface",
|
||||
change_username: "Changer le nom d'utilisateur",
|
||||
color_depth: 'Profondeur de couleur',
|
||||
close: 'Fermer',
|
||||
@@ -259,7 +258,6 @@ const fr = {
|
||||
replace: 'Remplacer',
|
||||
replace_all: 'Tout remplacer',
|
||||
resend_confirmation_code: 'Renvoyer le code de confirmation',
|
||||
reset_colors: 'Réinitialiser les couleurs',
|
||||
'Resources': 'Ressources',
|
||||
restart_puter_confirm: 'Êtes-vous sûr de vouloir redémarrer Puter ?',
|
||||
restore: 'Restaurer',
|
||||
@@ -327,7 +325,6 @@ const fr = {
|
||||
two_factor_enabled: 'A2F activée',
|
||||
type: 'Type',
|
||||
type_confirm_to_delete_account: "Tapez 'confirm' pour supprimer votre compte.",
|
||||
ui_colors: "Couleurs d'interface",
|
||||
ui_manage_sessions: 'Gestionnaire de sessions',
|
||||
ui_revoke: 'Révoquer',
|
||||
undo: 'Annuler',
|
||||
|
||||
@@ -41,7 +41,6 @@ const he = {
|
||||
change_email: 'שינוי כתובת אימייל',
|
||||
change_language: 'החלפת שפה',
|
||||
change_password: 'שינוי סיסמה',
|
||||
change_ui_colors: 'שינוי צבעי ממשק המשתמש',
|
||||
change_username: 'שינוי שם משתמש',
|
||||
close: 'סגירה',
|
||||
close_all_windows: 'סגירת כל החלונות',
|
||||
@@ -247,7 +246,6 @@ const he = {
|
||||
replace: 'החלף',
|
||||
replace_all: 'החלף הכל',
|
||||
resend_confirmation_code: 'שליחה מחדש של קוד אישור',
|
||||
reset_colors: 'איפוס צבעים',
|
||||
restart_puter_confirm: 'האם אתה בטוח שברצונך להפעיל Puter מחדש ?',
|
||||
restore: 'שחזור',
|
||||
save: 'שמירה',
|
||||
@@ -305,7 +303,6 @@ const he = {
|
||||
two_factor_enabled: 'אימות דו-שלבי הופעל',
|
||||
type: 'סוג',
|
||||
type_confirm_to_delete_account: "הקלד 'אישור' כדי למחוק את חשבונך.",
|
||||
ui_colors: 'צבעי ממשק משתמש',
|
||||
ui_manage_sessions: 'מנהל חיבורים',
|
||||
ui_revoke: 'בטל',
|
||||
undo: 'בטל',
|
||||
|
||||
@@ -41,7 +41,6 @@ const hi = {
|
||||
change_email: 'ई - मेल बदले',
|
||||
change_language: 'भाषा बदलें',
|
||||
change_password: 'पासवर्ड बदलें',
|
||||
change_ui_colors: 'यूआई रंग बदलें',
|
||||
change_username: 'उपयोगकर्ता नाम बदलें',
|
||||
close: 'बंद ',
|
||||
close_all_windows: 'सभी विंडोज़ बंद करें',
|
||||
@@ -230,7 +229,6 @@ const hi = {
|
||||
replace: 'प्रतिस्थापित करें',
|
||||
replace_all: 'सबको बदली करें',
|
||||
resend_confirmation_code: 'पुष्टिकरण कोड पुनः भेजें',
|
||||
reset_colors: 'रंग रीसेट करें',
|
||||
restart_puter_confirm: 'क्या आप वाकई पुटर को पुनः आरंभ करना चाहते हैं?',
|
||||
restore: 'पुनर्स्थापित',
|
||||
save: 'सहेजें',
|
||||
@@ -287,7 +285,6 @@ const hi = {
|
||||
two_factor_enabled: '2एफए सक्षम',
|
||||
type: 'प्रकार',
|
||||
type_confirm_to_delete_account: "अपना खाता हटाने के लिए 'पुष्टि करें' टाइप करें।",
|
||||
ui_colors: 'यूआई रंग',
|
||||
ui_manage_sessions: 'सत्र प्रबंधक',
|
||||
ui_revoke: 'रद्द',
|
||||
undo: 'पूर्ववत',
|
||||
|
||||
@@ -41,7 +41,6 @@ const hu = {
|
||||
change_email: 'Email módosítása',
|
||||
change_language: 'Nyelv módosítása',
|
||||
change_password: 'Jelszó módosítása',
|
||||
change_ui_colors: 'UI színek módosítása',
|
||||
change_username: 'Felhasználónév módosítása',
|
||||
close: 'Bezár',
|
||||
close_all_windows: 'Minden ablak bezárása',
|
||||
@@ -231,7 +230,6 @@ const hu = {
|
||||
replace: 'Csere',
|
||||
replace_all: 'Összes cseréje',
|
||||
resend_confirmation_code: 'Megerősítő kód újraküldése',
|
||||
reset_colors: 'Színek visszaállítása',
|
||||
restart_puter_confirm: 'Biztosan újraindítod a Putert?',
|
||||
restore: 'Visszaállítás',
|
||||
save: 'Mentés',
|
||||
@@ -288,7 +286,6 @@ const hu = {
|
||||
two_factor_enabled: '2FA engedélyezve',
|
||||
type: 'Típus',
|
||||
type_confirm_to_delete_account: "Írd be, hogy 'megerősít' a fiók törléséhez.",
|
||||
ui_colors: 'UI színek',
|
||||
ui_manage_sessions: 'Munkamenetkezelő',
|
||||
ui_revoke: 'Visszavonás',
|
||||
undo: 'Visszavonás',
|
||||
|
||||
@@ -41,7 +41,6 @@ const hy = {
|
||||
change_email: 'Փոխել էլ. փոստը',
|
||||
change_language: 'Փոխել լեզուն',
|
||||
change_password: 'Փոխել գաղտնաբառը',
|
||||
change_ui_colors: 'Փոխել UI գույները',
|
||||
change_username: 'Փոխել օգտանունը',
|
||||
close: 'Փակել',
|
||||
close_all_windows: 'Փակել բոլոր պատուհանները',
|
||||
@@ -256,7 +255,6 @@ const hy = {
|
||||
replace: 'Փոխարինել',
|
||||
replace_all: 'Փոխարինել բոլորը',
|
||||
resend_confirmation_code: 'Նորից ուղարկել հաստատման կոդը',
|
||||
reset_colors: 'Վերականգնել գույները',
|
||||
restart_puter_confirm: 'Վստա՞հ եք, որ ցանկանում եք վերագործարկել Փութերը:',
|
||||
restore: 'Վերականգնել',
|
||||
save: 'Պահպանել',
|
||||
@@ -320,7 +318,6 @@ const hy = {
|
||||
two_factor_enabled: '2FA-ն միացված է',
|
||||
type: 'Տեսակ',
|
||||
type_confirm_to_delete_account: "Հաշիվը ջնջելու համար գրեք 'confirm':",
|
||||
ui_colors: 'UI գույներ',
|
||||
ui_manage_sessions: 'Սեսիայի կառավարիչ',
|
||||
ui_revoke: 'Հետ կանչել',
|
||||
undo: 'Հետարկել',
|
||||
|
||||
@@ -41,7 +41,6 @@ const id = {
|
||||
change_email: 'Ubah Email',
|
||||
change_language: 'Ubah Bahasa',
|
||||
change_password: 'Ubah Kata Sandi',
|
||||
change_ui_colors: 'Ubah Warna Tampilan',
|
||||
change_username: 'Ubah Nama Pengguna',
|
||||
close: 'Tutup',
|
||||
close_all_windows: 'Tutup Semua Jendela',
|
||||
@@ -248,7 +247,6 @@ const id = {
|
||||
replace: 'Ganti',
|
||||
replace_all: 'Ganti Semua',
|
||||
resend_confirmation_code: 'Kirim Ulang Kode Konfirmasi',
|
||||
reset_colors: 'Mengatur Ulang Warna',
|
||||
restart_puter_confirm: 'Apakah Anda yakin ingin memulai ulang Puter?',
|
||||
restore: 'Pulihkan',
|
||||
save: 'Simpan',
|
||||
@@ -307,7 +305,6 @@ const id = {
|
||||
two_factor_enabled: '2FA Diaktifkan',
|
||||
type: 'Tipe',
|
||||
type_confirm_to_delete_account: "Ketik 'confirm' untuk menghapus akun Anda.",
|
||||
ui_colors: 'Warna Tampilan',
|
||||
ui_manage_sessions: 'Pengelola Sesi',
|
||||
ui_revoke: 'Batalkan',
|
||||
undo: 'Batalkan',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ig = {
|
||||
change_email: 'ịgbanwe email',
|
||||
change_language: 'ịgbanwe Asụsụ',
|
||||
change_password: 'ịgbanwe paswọọdụ',
|
||||
change_ui_colors: 'ịgbanwe agba UI',
|
||||
change_username: 'ịgbanwe aha njirimara',
|
||||
close: 'mmechi',
|
||||
close_all_windows: 'mmechi Windows niile',
|
||||
@@ -251,7 +250,6 @@ const ig = {
|
||||
replace: 'Dochie',
|
||||
replace_all: 'Dochie ihe niile',
|
||||
resend_confirmation_code: 'Tinyegharịa koodu nkwenye',
|
||||
reset_colors: 'Tọgharịa Agba',
|
||||
restart_puter_confirm: "Ị ji n'aka na ịchọrọ ịmalitegharịa Puter?",
|
||||
restore: 'weghachi',
|
||||
save: 'chekwa',
|
||||
@@ -311,7 +309,6 @@ const ig = {
|
||||
two_factor_enabled: 'Agbanyere 2FA',
|
||||
type: 'Ụdị',
|
||||
type_confirm_to_delete_account: "Pịnye 'kwenye' ka ihichapụ akaụntụ gị.",
|
||||
ui_colors: 'Agba UI',
|
||||
ui_manage_sessions: 'Onye njikwa oge',
|
||||
ui_revoke: 'Kagbuo',
|
||||
undo: 'Megharịa',
|
||||
|
||||
@@ -41,7 +41,6 @@ const it = {
|
||||
change_email: 'Modifica Email',
|
||||
change_language: 'Cambia lingua',
|
||||
change_password: 'Modifica password',
|
||||
change_ui_colors: "Cambia i colori dell'interfaccia",
|
||||
change_username: 'Modifica Nome Utente',
|
||||
close: 'Chiudi',
|
||||
close_all_windows: 'Chiudi tutte le finestre',
|
||||
@@ -254,7 +253,6 @@ const it = {
|
||||
replace: 'Sostituisci',
|
||||
replace_all: 'Sostituisci tutto',
|
||||
resend_confirmation_code: 'Invia di nuovo il codice di conferma',
|
||||
reset_colors: 'Ripristina i colori',
|
||||
restart_puter_confirm: 'Sei sicuro di voler riavviare Puter?',
|
||||
restore: 'Ripristina',
|
||||
save: 'Salva',
|
||||
@@ -318,7 +316,6 @@ const it = {
|
||||
type: 'Tipo',
|
||||
type_confirm_to_delete_account:
|
||||
"Scrivi 'conferma' per eliminare il tuo account.",
|
||||
ui_colors: "Colori dell'interfaccia",
|
||||
ui_manage_sessions: 'Session Manager',
|
||||
ui_revoke: 'Revoca',
|
||||
undo: 'Annulla',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ja = {
|
||||
change_email: 'メールアドレスを変更',
|
||||
change_language: '言語を変更',
|
||||
change_password: 'パスワードを変更',
|
||||
change_ui_colors: 'UIの色を変更',
|
||||
change_username: 'ユーザー名を変更',
|
||||
close: '閉じる',
|
||||
close_all_windows: 'すべてのウィンドウを閉じる',
|
||||
@@ -231,7 +230,6 @@ const ja = {
|
||||
replace: '置換',
|
||||
replace_all: 'すべて置換',
|
||||
resend_confirmation_code: '確認コードを再送信',
|
||||
reset_colors: '色をリセット',
|
||||
restart_puter_confirm: 'Puterを再起動してもよろしいですか?',
|
||||
restore: '復元',
|
||||
save: '保存',
|
||||
@@ -288,7 +286,6 @@ const ja = {
|
||||
two_factor_enabled: '2FA有効',
|
||||
type: 'タイプ',
|
||||
type_confirm_to_delete_account: 'アカウントを削除するには「confirm」と入力してください。',
|
||||
ui_colors: 'UIカラー',
|
||||
ui_manage_sessions: 'セッションマネージャー',
|
||||
ui_revoke: '取り消し',
|
||||
undo: '元に戻す',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ko = {
|
||||
change_email: '이메일 변경',
|
||||
change_language: '언어 변경',
|
||||
change_password: '비밀번호 변경',
|
||||
change_ui_colors: 'UI 색상 변경',
|
||||
change_username: '사용자 이름 변경',
|
||||
close: '닫기',
|
||||
close_all_windows: '모든 창 닫기',
|
||||
@@ -257,7 +256,6 @@ const ko = {
|
||||
replace: '교체',
|
||||
replace_all: '모두 교체',
|
||||
resend_confirmation_code: '인증 코드 재전송',
|
||||
reset_colors: '색상 초기화',
|
||||
restart_puter_confirm: 'Puter를 다시 시작하시겠습니까?',
|
||||
restore: '복원',
|
||||
save: '저장',
|
||||
@@ -324,7 +322,6 @@ const ko = {
|
||||
type: '유형',
|
||||
type_confirm_to_delete_account:
|
||||
"계정을 삭제하려면 'confirm'을 입력해주세요.",
|
||||
ui_colors: 'UI 색상',
|
||||
ui_manage_sessions: '세션 관리자',
|
||||
ui_revoke: '해제',
|
||||
undo: '실행 취소',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ku = {
|
||||
change_email: 'گۆڕینی ئیمەیل',
|
||||
change_language: 'گۆڕینی زمان',
|
||||
change_password: 'گۆڕینی وشەی تێپەڕ',
|
||||
change_ui_colors: 'گۆڕینی ڕەنگەکانی وێنەی بەکارهێنەر',
|
||||
change_username: 'گۆڕینی ناوی بەکارهێنەر',
|
||||
close: 'داخستن',
|
||||
close_all_windows: 'داخستنی هەموو پەنجەکان',
|
||||
@@ -251,7 +250,6 @@ const ku = {
|
||||
replace: 'لە نوێکردنەوە',
|
||||
replace_all: 'لە نوێکردنەوەی هەموو',
|
||||
resend_confirmation_code: 'دووبارە ناردنی کۆدی پشتڕاستکردنەوە',
|
||||
reset_colors: 'ڕێکخستنی ڕەنگەکان',
|
||||
restart_puter_confirm: 'دڵنیایت کە ئەتەوێت پوتەر دووبارە دەستپێبکەیت؟',
|
||||
restore: 'گەڕاندنەوە',
|
||||
save: 'پاشەکەوت',
|
||||
@@ -311,7 +309,6 @@ const ku = {
|
||||
two_factor_enabled: '2FA چالاک کرا',
|
||||
type: 'جۆر',
|
||||
type_confirm_to_delete_account: "جۆری 'پشتڕاستکردن' بۆ سڕینەوەی هەژمار.",
|
||||
ui_colors: 'ڕەنگەکانی وێنەی بەکارهێنەر',
|
||||
ui_manage_sessions: 'بەڕێوەبردنی دانیشتنەکان',
|
||||
ui_revoke: 'ڕەتکردنەوە',
|
||||
undo: 'پەشیمانبوون',
|
||||
|
||||
@@ -43,7 +43,6 @@ const ml = {
|
||||
change_email: 'ഇമെയിൽ മാറ്റുക',
|
||||
change_language: 'ഭാഷ മാറ്റുക',
|
||||
change_password: 'പാസ്വേഡ് മാറ്റുക',
|
||||
change_ui_colors: 'UI നിറങ്ങൾ മാറ്റുക',
|
||||
change_username: 'ഉപയോക്തൃനാമം മാറ്റുക',
|
||||
close: 'അടയ്ക്കുക',
|
||||
close_all_windows: 'എല്ലാ വിൻഡോകളും അടയ്ക്കുക',
|
||||
@@ -233,7 +232,6 @@ const ml = {
|
||||
replace: 'മാറ്റിസ്ഥാപിക്കുക',
|
||||
replace_all: 'എല്ലാം മാറ്റിസ്ഥാപിക്കുക',
|
||||
resend_confirmation_code: 'സ്ഥിരീകരണ കോഡ് വീണ്ടും അയയ്ക്കുക',
|
||||
reset_colors: 'നിറങ്ങൾ പുനഃക്രമീകരിക്കുക',
|
||||
restart_puter_confirm: 'പ്യൂട്ടർ റീസ്റ്റാർട്ട് ചെയ്യണമെന്ന് തീർച്ചയാണോ?',
|
||||
restore: 'പുനഃസ്ഥാപിക്കുക',
|
||||
save: 'സംരക്ഷിക്കുക',
|
||||
@@ -290,7 +288,6 @@ const ml = {
|
||||
two_factor_enabled: '2FA പ്രവർത്തനക്ഷമമാക്കി',
|
||||
type: 'തരം',
|
||||
type_confirm_to_delete_account: "നിങ്ങളുടെ അക്കൗണ്ട് ഇല്ലാതാക്കാൻ 'confirm' എന്ന് ടൈപ്പ് ചെയ്യുക.",
|
||||
ui_colors: 'UI നിറങ്ങൾ',
|
||||
ui_manage_sessions: 'സെഷൻ മാനേജർ',
|
||||
ui_revoke: 'റദ്ദാക്കുക',
|
||||
undo: 'പഴയപടിയാക്കുക',
|
||||
|
||||
@@ -49,7 +49,6 @@ const my = {
|
||||
change_email: 'Tukar Emel',
|
||||
change_language: 'Tukar Bahasa',
|
||||
change_password: 'Tukar Kata Laluan',
|
||||
change_ui_colors: 'Tukar Warna UI',
|
||||
change_username: 'Tukar Nama Pengguna',
|
||||
close: 'Tutup',
|
||||
close_all_windows: 'Tutup Semua Tetingkap',
|
||||
@@ -259,7 +258,6 @@ const my = {
|
||||
replace: 'Ganti',
|
||||
replace_all: 'Ganti Semua',
|
||||
resend_confirmation_code: 'Hantar Semula Kod Pengesahan',
|
||||
reset_colors: 'Set Semula Warna',
|
||||
restart_puter_confirm: 'Adakah anda pasti mahu memulakan semula Puter?',
|
||||
restore: 'Pulihkan',
|
||||
save: 'Simpan',
|
||||
@@ -322,7 +320,6 @@ const my = {
|
||||
two_factor_enabled: '2FA Diaktifkan',
|
||||
type: 'Jenis',
|
||||
type_confirm_to_delete_account: 'Taip \'sahkan\' untuk memadam akaun anda.',
|
||||
ui_colors: 'Warna UI',
|
||||
ui_manage_sessions: 'Pengurus Sesi',
|
||||
ui_revoke: 'Tarik balik',
|
||||
undo: 'Buat asal',
|
||||
|
||||
@@ -48,7 +48,6 @@ const nb = {
|
||||
change_email: 'Endre e-post',
|
||||
change_language: 'Endre språk',
|
||||
change_password: 'Endre passord',
|
||||
change_ui_colors: 'Endre UI-farger',
|
||||
change_username: 'Endre brukernavn',
|
||||
close: 'Lukk',
|
||||
close_all_windows: 'Lukk alle vinduer',
|
||||
@@ -242,7 +241,6 @@ const nb = {
|
||||
replace: 'Erstatt',
|
||||
replace_all: 'Erstatt alle',
|
||||
resend_confirmation_code: 'Send bekreftelseskoden på nytt',
|
||||
reset_colors: 'Tilbakestill farger',
|
||||
restart_puter_confirm: 'Er du sikker på at du vil starte Puter på nytt?',
|
||||
restore: 'Gjenopprett',
|
||||
save: 'Lagre',
|
||||
@@ -305,7 +303,6 @@ const nb = {
|
||||
two_factor_enabled: '2FA aktivert',
|
||||
type: 'Type',
|
||||
type_confirm_to_delete_account: "Skriv 'bekreft' for å slette kontoen din.",
|
||||
ui_colors: 'UI-farger',
|
||||
ui_manage_sessions: 'Økthåndtering',
|
||||
ui_revoke: 'Opphev',
|
||||
undo: 'Angre',
|
||||
|
||||
@@ -41,7 +41,6 @@ const nl = {
|
||||
change_email: 'E-mail Wijzigen',
|
||||
change_language: 'Taal veranderen',
|
||||
change_password: 'Wachtwoord veranderen',
|
||||
change_ui_colors: 'UI Kleuren veranderen',
|
||||
change_username: 'Gebruikersnaam veranderen',
|
||||
close: 'Sluiten',
|
||||
close_all_windows: 'Alle vensters sluiten',
|
||||
@@ -232,7 +231,6 @@ const nl = {
|
||||
replace: 'Vervangen',
|
||||
replace_all: 'Alles vervangen',
|
||||
resend_confirmation_code: 'Bevestigingscode opnieuw verzenden',
|
||||
reset_colors: 'Kleuren resetten',
|
||||
restart_puter_confirm: 'Weet je zeker dat je Puter wilt herstarten?',
|
||||
restore: 'Herstellen',
|
||||
save: 'Opslaan',
|
||||
@@ -289,7 +287,6 @@ const nl = {
|
||||
two_factor_enabled: '2FA Ingeschakeld',
|
||||
type: 'Type',
|
||||
type_confirm_to_delete_account: 'Typ \'bevestigen\' om je account te verwijderen.',
|
||||
ui_colors: 'UI Kleuren',
|
||||
ui_manage_sessions: 'Sessiebeheer',
|
||||
ui_revoke: 'Intrekken',
|
||||
undo: 'Ongedaan maken',
|
||||
|
||||
@@ -179,7 +179,6 @@ const nn = {
|
||||
change: 'Endre', // In English: "Change"
|
||||
change_always_open_with: 'Vil du alltid opne denne filtypen med', // In English: "Do you want to always open this type of file with"
|
||||
change_email: 'Endre e-post', // In English: "Change Email"
|
||||
change_ui_colors: 'Endre fargar på brukargrensesnitt', // In English: "Change UI Colors"
|
||||
close: 'Lukk', // In English: "Close"
|
||||
close_all_windows_confirm: 'Er du sikker på at du vil lukke alle vindauge?', // In English: "Are you sure you want to close all windows?"
|
||||
close_all_windows_and_log_out: 'Lukk vindauge og logg ut', // In English: "Close Windows and Log Out"
|
||||
@@ -284,7 +283,6 @@ const nn = {
|
||||
recommended: 'Anbefalt',
|
||||
replace: 'Erstatt',
|
||||
replace_all: 'Erstatt alle',
|
||||
reset_colors: 'Nullstill fargar',
|
||||
restart_puter_confirm: 'Er du sikker på at du vil starte Puter på nytt?',
|
||||
save: 'Lagre',
|
||||
saturation: 'Metting',
|
||||
@@ -316,7 +314,6 @@ const nn = {
|
||||
two_factor_disabled: '2FA deaktivert',
|
||||
two_factor_enabled: '2FA aktivert',
|
||||
type_confirm_to_delete_account: "Skriv inn 'konfirmer' for å slette kontoen din.",
|
||||
ui_colors: 'Fargar på brukargrensesnitt',
|
||||
ui_manage_sessions: 'Øktbehandler',
|
||||
ui_revoke: 'Trekk tilbake',
|
||||
unlimited: 'Ubegrensa',
|
||||
|
||||
@@ -41,7 +41,6 @@ const pl = {
|
||||
change_email: 'Zmień email',
|
||||
change_language: 'Zmień język',
|
||||
change_password: 'Zmień hasło',
|
||||
change_ui_colors: 'Zmień kolory interfejsu',
|
||||
change_username: 'Zmień użytkownika',
|
||||
close: 'Zamknij',
|
||||
close_all_windows: 'Zamknij wszystkie okna',
|
||||
@@ -231,7 +230,6 @@ const pl = {
|
||||
replace: 'Zamień',
|
||||
replace_all: 'Zamień wszystkie',
|
||||
resend_confirmation_code: 'Wyślij kod potwierdzający ponownie.',
|
||||
reset_colors: 'Przywróc kolory',
|
||||
restart_puter_confirm: 'Na pewno zrestartować Puter?',
|
||||
restore: 'Odzyskaj',
|
||||
save: 'Zapisz',
|
||||
@@ -288,7 +286,6 @@ const pl = {
|
||||
two_factor_enabled: 'Uwierzytelnianie dwuetapowe odblokowane',
|
||||
type: 'Wpisz',
|
||||
type_confirm_to_delete_account: "Wpisz 'potwierdzam', aby skasować swoje konto.",
|
||||
ui_colors: 'Kolory interfejsu użytkownika',
|
||||
ui_manage_sessions: 'Menedżer sesji',
|
||||
ui_revoke: 'Unieważnij',
|
||||
undo: 'Cofnij',
|
||||
|
||||
@@ -42,7 +42,6 @@ const pt = {
|
||||
change_email: 'Alterar e-mail',
|
||||
change_language: 'Alterar Idioma',
|
||||
change_password: 'Alterar Senha',
|
||||
change_ui_colors: 'Alterar Cores da Interface',
|
||||
change_username: 'Alterar Nome de Utilizador',
|
||||
close: 'Fechar',
|
||||
close_all_windows: 'Fechar Todas as Janelas',
|
||||
@@ -234,7 +233,6 @@ const pt = {
|
||||
replace: 'Substituir',
|
||||
replace_all: 'Substituir Todos',
|
||||
resend_confirmation_code: 'Re-enviar o Código de Confirmação',
|
||||
reset_colors: 'Voltar às cores pré-definidas',
|
||||
restart_puter_confirm: 'Tem a certeza de que deseja reiniciar Puter?',
|
||||
restore: 'Restaurar',
|
||||
save: 'Gravar',
|
||||
@@ -291,7 +289,6 @@ const pt = {
|
||||
two_factor_enabled: '2FA Habilitado',
|
||||
type: 'Tipo',
|
||||
type_confirm_to_delete_account: "Escreve 'confirm' para apagares esta conta.",
|
||||
ui_colors: 'UI Colors',
|
||||
ui_manage_sessions: 'Session Manager',
|
||||
ui_revoke: 'Revoke',
|
||||
undo: 'Voltar atrás',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ro = {
|
||||
change_email: 'Schimbă e-mailul',
|
||||
change_language: 'Schimbă Limba',
|
||||
change_password: 'Schimbă Parola',
|
||||
change_ui_colors: 'Schimbă Culorile Interfeței',
|
||||
change_username: 'Schimbă User-ul',
|
||||
close: 'Închide',
|
||||
close_all_windows: 'Închide toate ferestrele',
|
||||
@@ -232,7 +231,6 @@ const ro = {
|
||||
replace: 'Înlocuiește',
|
||||
replace_all: 'Înlocuiește toate',
|
||||
resend_confirmation_code: 'Re-trimite cod de confirmare',
|
||||
reset_colors: 'Resetează culori',
|
||||
restart_puter_confirm: 'Sunteți sigur(ă) că doriți să reporniți Puter?',
|
||||
restore: 'Restaurare',
|
||||
save: 'Salvare',
|
||||
@@ -289,7 +287,6 @@ const ro = {
|
||||
two_factor_enabled: '2FA Activat',
|
||||
type: 'Type',
|
||||
type_confirm_to_delete_account: "Tastați 'confirm' pentru a șterge contul dumneavoastră.",
|
||||
ui_colors: 'Culori Interfața',
|
||||
ui_manage_sessions: 'Administrator Sesiuni',
|
||||
ui_revoke: 'Revocă',
|
||||
undo: 'Undo',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ru = {
|
||||
change_email: 'Изменить электронную почту',
|
||||
change_language: 'Изменить язык',
|
||||
change_password: 'Изменить пароль',
|
||||
change_ui_colors: 'Изменить тему оформления',
|
||||
change_username: 'Изменить имя пользователя',
|
||||
close: 'Закрыть',
|
||||
close_all_windows: 'Закрыть все окна',
|
||||
@@ -254,7 +253,6 @@ const ru = {
|
||||
replace: 'Заменить',
|
||||
replace_all: 'Заменить все',
|
||||
resend_confirmation_code: 'Повторно отправить код подтверждения',
|
||||
reset_colors: 'Сбросить цвета',
|
||||
restart_puter_confirm: 'Вы уверены, что хотите перезапустить Puter?',
|
||||
restore: 'Восстановить',
|
||||
save: 'Сохранить',
|
||||
@@ -320,7 +318,6 @@ const ru = {
|
||||
type: 'Тип',
|
||||
type_confirm_to_delete_account:
|
||||
"Введите 'подтвердить', чтобы удалить учетную запись.",
|
||||
ui_colors: 'Цвета пользовательского интерфейса',
|
||||
ui_manage_sessions: 'Менеджер Сеансов',
|
||||
ui_revoke: 'Отозвать',
|
||||
undo: 'Отменить',
|
||||
|
||||
@@ -43,7 +43,6 @@ const sl = {
|
||||
change_email: 'Spremeni e-poštni naslov',
|
||||
change_language: 'Spremeni jezik',
|
||||
change_password: 'Spremeni geslo',
|
||||
change_ui_colors: 'Spremeni barve vmesnika',
|
||||
change_username: 'Spremeni uporabniško ime',
|
||||
close: 'Zapri',
|
||||
close_all_windows: 'Zapri vsa okna',
|
||||
@@ -242,7 +241,6 @@ const sl = {
|
||||
replace: 'Zamenjaj',
|
||||
replace_all: 'Zamenjaj vse',
|
||||
resend_confirmation_code: 'Znova pošlji potrditveno kodo',
|
||||
reset_colors: 'Ponastavi barve',
|
||||
restart_puter_confirm: 'Ali ste prepričani, da želite znova zagnati Puter?',
|
||||
restore: 'Obnovi',
|
||||
save: 'Shrani',
|
||||
@@ -305,7 +303,6 @@ const sl = {
|
||||
two_factor_enabled: '2FA omogočeno',
|
||||
type: 'Vrsta',
|
||||
type_confirm_to_delete_account: "Za izbris računa vpišite 'Potrdi'.",
|
||||
ui_colors: 'Barve uporabniškega vmesnika',
|
||||
ui_manage_sessions: 'Upravitelj sej',
|
||||
ui_revoke: 'Prekliči',
|
||||
undo: 'Razveljavi',
|
||||
|
||||
@@ -41,7 +41,6 @@ const sv = {
|
||||
change_email: 'Ändra e-postadress',
|
||||
change_language: 'Ändra språk',
|
||||
change_password: 'Byt lösenord',
|
||||
change_ui_colors: 'Ändra gränssnittets färger',
|
||||
change_username: 'Byt användarnamn',
|
||||
close: 'Stäng',
|
||||
close_all_windows: 'Stäng alla fönster',
|
||||
@@ -231,7 +230,6 @@ const sv = {
|
||||
replace: 'Ersätt',
|
||||
replace_all: 'Ersätt alla',
|
||||
resend_confirmation_code: 'Skicka bekräftelsekoden igen',
|
||||
reset_colors: 'Nolställ färgerna',
|
||||
restart_puter_confirm: 'Är det säkert att du vill starta om Puter?',
|
||||
restore: 'Återställ',
|
||||
save: 'Spara',
|
||||
@@ -288,7 +286,6 @@ const sv = {
|
||||
two_factor_enabled: '2FA aktiverad',
|
||||
type: 'Typ',
|
||||
type_confirm_to_delete_account: "Skriv 'bekräfta' för att ta bort ditt konto.",
|
||||
ui_colors: 'Färger för användargränssnitt',
|
||||
ui_manage_sessions: 'Sessionshanterare',
|
||||
ui_revoke: 'Upphäv',
|
||||
undo: 'Ångra',
|
||||
|
||||
@@ -41,7 +41,6 @@ const ta = {
|
||||
change_email: 'மின்னஞ்சலை மாற்றவும்',
|
||||
change_language: 'மொழியை மாற்றவும்',
|
||||
change_password: 'கடவுச்சொல்லை மாற்றவும்',
|
||||
change_ui_colors: 'யுஐ நிறங்களை மாற்றவும்',
|
||||
change_username: 'பயனர் பெயரை மாற்றவும்',
|
||||
close: 'மூடு',
|
||||
close_all_windows: 'அனைத்து விண்டோஸ் மூடு',
|
||||
@@ -259,7 +258,6 @@ const ta = {
|
||||
replace: 'மாற்றவும்',
|
||||
replace_all: 'அனைத்தையும் மாற்றவும்',
|
||||
resend_confirmation_code: 'உறுதிப்படுத்தல் குறியீட்டை மீண்டும் அனுப்பவும்',
|
||||
reset_colors: 'வண்ணங்களை மீட்டமைக்கவும்',
|
||||
restart_puter_confirm:
|
||||
'நிச்சயமாக புட்டர்-ஐ மீண்டும் தொடங்க விரும்புகிறீர்களா?',
|
||||
restore: 'மீட்டமை',
|
||||
@@ -325,7 +323,6 @@ const ta = {
|
||||
type: 'வகை',
|
||||
type_confirm_to_delete_account:
|
||||
"உங்கள் கணக்கை நீக்க, 'உறுதிப்படுத்து' என தட்டச்சு செய்யவும்.",
|
||||
ui_colors: 'UI நிறங்கள்',
|
||||
ui_manage_sessions: 'அமர்வு மேலாளர்',
|
||||
ui_revoke: 'திரும்பப் பெறு',
|
||||
undo: 'செயல்தவிர்',
|
||||
|
||||
@@ -41,7 +41,6 @@ const th = {
|
||||
change_email: 'เปลี่ยนอีเมล',
|
||||
change_language: 'เปลี่ยนภาษา',
|
||||
change_password: 'เปลี่ยนรหัสผ่าน',
|
||||
change_ui_colors: 'เปลี่ยนสี UI',
|
||||
change_username: 'เปลี่ยนชื่อผู้ใช้',
|
||||
close: 'ปิด',
|
||||
close_all_windows: 'ปิดหน้าต่างทั้งหมด',
|
||||
@@ -229,7 +228,6 @@ const th = {
|
||||
replace: 'แทนที่',
|
||||
replace_all: 'แทนที่ทั้งหมด',
|
||||
resend_confirmation_code: 'ส่งรหัสยืนยันอีกครั้ง',
|
||||
reset_colors: 'ล้างค่าสี',
|
||||
restart_puter_confirm: 'คุณแน่ใจว่าจะรีสตาร์ท Puter?',
|
||||
restore: 'คืนค่า',
|
||||
saturation: 'ความอิ่มตัว',
|
||||
@@ -285,7 +283,6 @@ const th = {
|
||||
two_factor_enabled: 'เปิดการใช้งาน 2FA',
|
||||
type: 'ประเภท',
|
||||
type_confirm_to_delete_account: "พิมพ์ 'confirm' เพื่อลบบัญชี",
|
||||
ui_colors: 'สีของ UI',
|
||||
ui_manage_sessions: 'ตัวจัดการเซสชั่น',
|
||||
ui_revoke: 'เพิกถอน',
|
||||
undo: 'เลิกทำ',
|
||||
|
||||
@@ -41,7 +41,6 @@ const tr = {
|
||||
change_email: 'E-postayı Değiştir',
|
||||
change_language: 'Dili Değiştir',
|
||||
change_password: 'Parolayı Değiştir',
|
||||
change_ui_colors: 'Arayüz Renklerini Değiştir',
|
||||
change_username: 'Kullanıcı Adını Değiştir',
|
||||
close: 'Kapat',
|
||||
close_all_windows: 'Tüm Pencereleri Kapat',
|
||||
@@ -230,7 +229,6 @@ const tr = {
|
||||
replace: 'Değiştir',
|
||||
replace_all: 'Tümünü Değiştir',
|
||||
resend_confirmation_code: 'Onay Kodunu Yeniden Gönder',
|
||||
reset_colors: 'Renkleri Sıfırla',
|
||||
restart_puter_confirm: "Puter'i yeniden başlatmak istediğinize emin misiniz?",
|
||||
restore: 'Geri Yükle',
|
||||
save: 'Kaydet',
|
||||
@@ -287,7 +285,6 @@ const tr = {
|
||||
two_factor_enabled: 'İki Faktörlü Doğrulama Etkin',
|
||||
type: 'Tür',
|
||||
type_confirm_to_delete_account: "Hesabınızı silmek için 'onayla' yazın.",
|
||||
ui_colors: 'Arayüz Renkleri',
|
||||
ui_manage_sessions: 'Oturum Yöneticisi',
|
||||
ui_revoke: 'Sonlandır',
|
||||
undo: 'Geri Al',
|
||||
|
||||
@@ -42,7 +42,6 @@ const ua = {
|
||||
change_email: 'Змінити Email',
|
||||
change_language: 'Змінити Мову',
|
||||
change_password: 'Змінити Пароль',
|
||||
change_ui_colors: 'Змінити Тему Оформлення',
|
||||
change_username: "Змінити Ім\'я Користувача",
|
||||
close: 'Закрити',
|
||||
close_all_windows: 'Закрити всі Вікна',
|
||||
@@ -234,7 +233,6 @@ const ua = {
|
||||
replace: 'Замінити',
|
||||
replace_all: 'Замінити Все',
|
||||
resend_confirmation_code: 'Повторно надіслати Код Підтвердження',
|
||||
reset_colors: 'Скинути Кольори',
|
||||
restart_puter_confirm: 'Ви впевнені, що хочете перезапустити Puter?',
|
||||
restore: 'Відновити',
|
||||
save: 'Зберегти',
|
||||
@@ -290,7 +288,6 @@ const ua = {
|
||||
two_factor_enabled: 'Двофакторна аутентифікація увімкнена',
|
||||
type: 'Тип',
|
||||
type_confirm_to_delete_account: "Введіть 'Підтвердити', щоб видалити обліковий запис.",
|
||||
ui_colors: 'Кольори UI',
|
||||
ui_manage_sessions: 'Менеджер Сеансів',
|
||||
ui_revoke: 'Відкликати',
|
||||
undo: 'Скасувати',
|
||||
|
||||
@@ -39,7 +39,6 @@ const ur = {
|
||||
change_email: 'ای میل تبدیل کریں',
|
||||
change_language: 'زبان تبدیل کریں',
|
||||
change_password: 'پاس ورڈ تبدیل کریں',
|
||||
change_ui_colors: 'یوزر انٹرفیس کے رنگ تبدیل کریں۔',
|
||||
change_username: 'صارف کا نام تبدیل کریں',
|
||||
close: 'بند کریں',
|
||||
close_all_windows: 'تمام ونڈوز بند کریں',
|
||||
@@ -238,7 +237,6 @@ const ur = {
|
||||
replace: 'بدل دیں۔',
|
||||
replace_all: 'سبھی کو تبدیل کریں۔',
|
||||
resend_confirmation_code: 'تصدیقی کوڈ دوبارہ بھیجیں',
|
||||
reset_colors: 'رنگوں کو دوبارہ ترتیب دیں۔',
|
||||
restart_puter_confirm: 'کیا آپ واقعی Puter کو دوبارہ شروع کرنا چاہتے ہیں؟',
|
||||
restore: 'بحال کریں',
|
||||
saturation: 'سنترپتی',
|
||||
@@ -294,7 +292,6 @@ const ur = {
|
||||
type: 'لکہنا',
|
||||
type_confirm_to_delete_account:
|
||||
"اپنا اکاؤنٹ حذف کرنے کے لیے 'تصدیق' ٹائپ کریں۔",
|
||||
ui_colors: 'UI رنگ',
|
||||
ui_manage_sessions: 'سیشن مینیجر',
|
||||
ui_revoke: 'منسوخ کرنا',
|
||||
undo: 'واپسی کریں',
|
||||
|
||||
@@ -41,7 +41,6 @@ const vi = {
|
||||
change_email: 'Thay đổi email',
|
||||
change_language: 'Thay đổi ngôn ngữ',
|
||||
change_password: 'Thay đổi mật khẩu',
|
||||
change_ui_colors: 'Thay đổi màu sắc giao diện',
|
||||
change_username: 'Thay đổi tên người dùng',
|
||||
close: 'Đóng',
|
||||
close_all_windows: 'Đóng tất cả cửa sổ',
|
||||
@@ -231,7 +230,6 @@ const vi = {
|
||||
replace: 'Thay thế',
|
||||
replace_all: 'Thay thế tất cả',
|
||||
resend_confirmation_code: 'Gửi lại mã xác nhận',
|
||||
reset_colors: 'Đặt lại màu sắc',
|
||||
restart_puter_confirm: 'Bạn có chắc chắn muốn khởi động lại Puter không?',
|
||||
restore: 'Khôi phục',
|
||||
save: 'Lưu',
|
||||
@@ -288,7 +286,6 @@ const vi = {
|
||||
two_factor_enabled: '2FA đã bật',
|
||||
type: 'Loại',
|
||||
type_confirm_to_delete_account: "Gõ 'confirm' để xóa tài khoản của bạn.",
|
||||
ui_colors: 'Màu sắc giao diện',
|
||||
ui_manage_sessions: 'Quản lý phiên',
|
||||
ui_revoke: 'Thu hồi',
|
||||
undo: 'Hoàn tác',
|
||||
|
||||
@@ -41,7 +41,6 @@ const zh = {
|
||||
change_email: '更改邮箱',
|
||||
change_language: '更改语言',
|
||||
change_password: '更改密码',
|
||||
change_ui_colors: '更改界面颜色',
|
||||
change_username: '更改用户名',
|
||||
close: '关闭',
|
||||
close_all_windows: '关闭所有窗口',
|
||||
@@ -231,7 +230,6 @@ const zh = {
|
||||
replace: '替换',
|
||||
replace_all: '全部替换',
|
||||
resend_confirmation_code: '重新发送确认码',
|
||||
reset_colors: '重置颜色',
|
||||
restart_puter_confirm: '确定要重启Puter?',
|
||||
restore: '还原',
|
||||
save: '保存',
|
||||
@@ -288,7 +286,6 @@ const zh = {
|
||||
two_factor_enabled: '启用二次身份验证',
|
||||
type: '类型',
|
||||
type_confirm_to_delete_account: '请输入 confirm 以确认删除账号.',
|
||||
ui_colors: '界面颜色',
|
||||
ui_manage_sessions: '会话管理',
|
||||
ui_revoke: '取消',
|
||||
undo: '撤销',
|
||||
|
||||
@@ -60,7 +60,6 @@ const zhtw = {
|
||||
change_email: '更改電子郵件',
|
||||
change_language: '更改語言',
|
||||
change_password: '更改密碼',
|
||||
change_ui_colors: '更改使用者介面顏色',
|
||||
change_username: '更改使用者名稱',
|
||||
close: '關閉',
|
||||
close_all_windows: '關閉所有視窗',
|
||||
@@ -250,7 +249,6 @@ const zhtw = {
|
||||
replace: '取代',
|
||||
replace_all: '全部取代',
|
||||
resend_confirmation_code: '重新發送確認碼',
|
||||
reset_colors: '重設顏色',
|
||||
restart_puter_confirm: '您確定要重新啟動 Puter 嗎?',
|
||||
restore: '還原',
|
||||
save: '儲存',
|
||||
@@ -307,7 +305,6 @@ const zhtw = {
|
||||
two_factor_enabled: '雙重驗證已啟用',
|
||||
type: '類型',
|
||||
type_confirm_to_delete_account: '輸入「confirm」以刪除您的帳戶。',
|
||||
ui_colors: '使用者介面顏色',
|
||||
ui_manage_sessions: '工作階段管理器',
|
||||
ui_revoke: '撤銷',
|
||||
undo: '復原',
|
||||
|
||||
+33
-4
@@ -47,8 +47,11 @@ import UIAuthRecoverPassword from './UI/Auth/UIAuthRecoverPassword.js';
|
||||
import { PROCESS_RUNNING } from './definitions.js';
|
||||
import { isAttestedOrigin } from './helpers/attestedOrigin.js';
|
||||
import { embedHostUser } from './helpers/embedHostUser.js';
|
||||
import { overlayGone } from './helpers/overlayGone.js';
|
||||
import {
|
||||
canShowCustomDomainFrame,
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowTopUpFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
@@ -57,6 +60,7 @@ import {
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedTopUp,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './helpers/popupFrame.js';
|
||||
@@ -1048,6 +1052,23 @@ const postAuthActions = async (action) => {
|
||||
window.tell_popup_frame('closed', { upgraded });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: top-up — the deployment's top-up dialog for the first-party page framing it,
|
||||
// which hears whether the user bought credit once the dialog closes.
|
||||
// -------------------------------------------------------------------------------------
|
||||
if ( action === 'top-up' && window.embedded_in_frame ) {
|
||||
let toppedUp;
|
||||
try {
|
||||
toppedUp = await showFramedTopUp(window, window.tell_popup_frame);
|
||||
} catch (e) {
|
||||
// A dialog that failed to open leaves the page to open the top-up in a tab.
|
||||
console.error('top-up action failed', e);
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
}
|
||||
window.tell_popup_frame('closed', { toppedUp });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: request-email-confirmation — puter.ui.requestEmailConfirmation() on the
|
||||
// first-party page framing it, which hears whether the email is confirmed once the
|
||||
@@ -1069,7 +1090,8 @@ const postAuthActions = async (action) => {
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Action: attach-custom-domain — puter.hosting.attach() on a website. Hosts the custom
|
||||
// domain dialog for `subdomain` and posts the chosen domain back to the opener.
|
||||
// domain dialog for `subdomain` and posts the chosen domain back to the opener, or to
|
||||
// the first-party page framing it.
|
||||
// -------------------------------------------------------------------------------------
|
||||
if ( action === 'attach-custom-domain' ) {
|
||||
const msg_id = window.url_query_params.get('msg_id');
|
||||
@@ -1092,11 +1114,16 @@ const postAuthActions = async (action) => {
|
||||
if ( ! subdomain ) {
|
||||
throw new Error('no subdomain');
|
||||
}
|
||||
domain = await UIWindowAttachCustomDomain({
|
||||
// A frame covers its page, which shows around the floating dialog.
|
||||
const dialog = UIWindowAttachCustomDomain({
|
||||
subdomain,
|
||||
requester: target_origin,
|
||||
fullpage: window.embedded_in_popup === true,
|
||||
fullpage: window.embedded_in_popup === true && !window.embedded_in_frame,
|
||||
});
|
||||
if ( window.embedded_in_frame ) window.tell_popup_frame('ready');
|
||||
domain = await dialog;
|
||||
// The answer removes the frame, so the dialog's exit plays first.
|
||||
if ( window.embedded_in_frame ) await overlayGone(document, '.custom-domain-overlay');
|
||||
} catch (e) {
|
||||
console.error('attach-custom-domain action failed', e);
|
||||
}
|
||||
@@ -1841,7 +1868,9 @@ window.initgui = async function (options) {
|
||||
!host_user ||
|
||||
session_user !== host_user ||
|
||||
(action === 'upgrade' && !canShowUpgradeFrame(window, session)) ||
|
||||
(action === 'request-email-confirmation' && !canShowEmailConfirmationFrame(session))
|
||||
(action === 'top-up' && !canShowTopUpFrame(window, session)) ||
|
||||
(action === 'request-email-confirmation' && !canShowEmailConfirmationFrame(session)) ||
|
||||
(action === 'attach-custom-domain' && !canShowCustomDomainFrame(session))
|
||||
) {
|
||||
window.tell_popup_frame('unavailable');
|
||||
return;
|
||||
|
||||
@@ -297,7 +297,9 @@ const mountGuiEmbed = ({ guiOrigin, path, fragment, className, title, stateMsg,
|
||||
const removal = new MutationObserver(() => {
|
||||
if ( ! dialog.isConnected ) dismiss();
|
||||
});
|
||||
const restoreFocus = document.activeElement;
|
||||
// Down through shadow roots: a component's host can't take the focus back itself.
|
||||
let restoreFocus = document.activeElement;
|
||||
while ( restoreFocus?.shadowRoot?.activeElement ) restoreFocus = restoreFocus.shadowRoot.activeElement;
|
||||
const wait = (ms) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => finish(null), ms);
|
||||
@@ -454,12 +456,15 @@ const POPUP_FRAME_BOXES = {
|
||||
'show-directory-picker': { width: 700, height: 400 },
|
||||
};
|
||||
|
||||
// The upgrade has no box: it covers the page and its dialog draws its own
|
||||
// scrim. A payment in it may use the Payment Request API, which a frame can
|
||||
// use only when allowed, and Escape is left to the dialog, which doesn't close
|
||||
// mid-entry.
|
||||
// The upgrade and the top-up have no box: each covers the page and its dialog
|
||||
// draws its own scrim. A payment in it may use the Payment Request API, which
|
||||
// a frame can use only when allowed, and Escape is left to the dialog, which
|
||||
// doesn't close mid-entry. The custom domain dialog copies DNS records to the
|
||||
// clipboard, and keeps Escape so a request in flight isn't dropped.
|
||||
const UNBOXED_POPUP_FRAMES = {
|
||||
upgrade: { allow: 'payment; otp-credentials', escapeDismisses: false },
|
||||
'top-up': { allow: 'payment; otp-credentials', escapeDismisses: false },
|
||||
'attach-custom-domain': { allow: 'clipboard-write; otp-credentials', escapeDismisses: false },
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -476,8 +481,8 @@ const UNBOXED_POPUP_FRAMES = {
|
||||
* @template T
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.guiOrigin
|
||||
* @param {'sign-in' | 'show-open-file-picker' | 'show-save-file-picker' | 'show-directory-picker' | 'upgrade' | 'request-email-confirmation'} opts.action
|
||||
* @param {Record<string, string>} opts.fragment - the popup's parameters, and `user` for a picker, the upgrade or the email confirmation
|
||||
* @param {'sign-in' | 'show-open-file-picker' | 'show-save-file-picker' | 'show-directory-picker' | 'upgrade' | 'top-up' | 'request-email-confirmation' | 'attach-custom-domain'} opts.action
|
||||
* @param {Record<string, string>} opts.fragment - the popup's parameters, and `user` for every action but the sign-in
|
||||
* @param {string} opts.title - the frame's accessible name
|
||||
* @param {string} [opts.closeLabel] - puts a close button on the frame
|
||||
* @param {(data?: Record<string, unknown>) => T} opts.closed
|
||||
|
||||
@@ -1149,15 +1149,18 @@ const DRIVER_CONTENT_TYPE = 'text/plain;actually=json';
|
||||
|
||||
const callInstance = (call) => call.puter ?? globalThis.puter;
|
||||
|
||||
/** The wire body. Fields left `undefined` drop out of the JSON. */
|
||||
/**
|
||||
* The wire body. Fields left `undefined` drop out of the JSON. The token goes
|
||||
* first, where the server can read it before it has the rest of a large body.
|
||||
*/
|
||||
const callBody = (call, puter) =>
|
||||
JSON.stringify({
|
||||
auth_token: puter.authToken,
|
||||
interface: call.iface,
|
||||
driver: call.driver,
|
||||
test_mode: call.testMode,
|
||||
method: call.method,
|
||||
args: call.args,
|
||||
auth_token: puter.authToken,
|
||||
});
|
||||
|
||||
const logCall = (call, fields) => {
|
||||
|
||||
@@ -1233,6 +1233,14 @@ describe('driverCall', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the body with the token, ahead of the arguments', async () => {
|
||||
const xhrs = installFakeXHR(
|
||||
respond({ body: { success: true, result: 'v' } }),
|
||||
);
|
||||
await driverCall({ ...call, args: { key: '"auth_token":"decoy"' } });
|
||||
expect(xhrs[0].reqBody.startsWith('{"auth_token":"tok",')).toBe(true);
|
||||
});
|
||||
|
||||
it('sends driver and test_mode only when the caller sets them', async () => {
|
||||
const xhrs = installFakeXHR(
|
||||
respond({ body: { success: true, result: {} } }),
|
||||
|
||||
@@ -26,7 +26,7 @@ import { showUsageLimitDialog } from '../modules/UsageLimitDialog.js';
|
||||
*
|
||||
* @typedef {{
|
||||
* env?: string,
|
||||
* ui?: { requestUpgrade: Function, canShowUpgradeFrame_?: () => boolean, upgradeFrameShowing_?: () => boolean },
|
||||
* ui?: { requestUpgrade: Function, canShowUpgradeFrame_?: () => boolean, upgradeFrameShowing_?: () => boolean, topUpShowing_?: () => boolean },
|
||||
* authToken?: string,
|
||||
* appID?: string,
|
||||
* getAppIDFromAuthToken?: (token: unknown) => string | null,
|
||||
@@ -129,8 +129,9 @@ export const promptIfUpgradeRequired = (error, context = {}, puter = globalThis.
|
||||
puter.ui.requestUpgrade({ reason, method, message });
|
||||
} else if ( puter?.env === 'web' || reason === 'storage' ) {
|
||||
// The upgrade a first-party page already shows answers this refusal
|
||||
// too, and a dialog over it would block it.
|
||||
// too, and a dialog over it, or over a top-up, would block it.
|
||||
if ( puter.ui?.upgradeFrameShowing_?.() === true ) return;
|
||||
if ( puter.ui?.topUpShowing_?.() === true ) return;
|
||||
// A first-party page shows the upgrade in a frame over itself
|
||||
// instead of a dashboard tab.
|
||||
const framed = puter?.env === 'web' && puter.ui?.canShowUpgradeFrame_?.() === true;
|
||||
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user