Compare commits

...
Author SHA1 Message Date
Nariman Jelveh 6050ff78c3 Match dashboard paths in any letter case, and stop the e2e tests waiting on .desktop
- bootsDashboard() matches /dashboard and /app/<name> case-insensitively, as the server routes them, so /App/<name> boots the dashboard.
- The request-permission hardening tests wait for the page's own answer instead of the removed .desktop element.
- Remove the error_user_or_path_not_found string from fr.js.
2026-11-12 17:31:36 -07:00
Nariman Jelveh abb647d227 Remove the error_user_or_path_not_found string
Only the desktop's shared-item opener showed it.
2026-11-12 16:53:33 -07:00
Nariman Jelveh fa2d2d226a Remove UIDesktop
Nothing reaches it except a signed-in top-level /action/* page, where it
rendered an empty surface behind the page's dialog. Those pages now show
only the dialog, without a socket connection or notification toasts.

The full-page window styling it defined moves into UIWindow, its only
caller. The desktop-only closeLocalBanner helper, ProcessService's
gui:ready hook, and the .desktop and .window-container styles go with it.
2026-11-12 16:48:36 -07:00
Nariman Jelveh bb55d6c6a4 Boot the dashboard for framed / and /app/<name>, and remove the desktop's URL app launch
The root path and app landings boot the dashboard whether or not the page
is framed, so the desktop no longer launches an app from the URL. With that
gone, the fullpage_on_landing lookups, ?puter.fullpage= and the Dev Center
"full-page mode" checkbox have nothing to act on and are removed.
2026-11-12 16:40:04 -07:00
Juan Fernando CastroandDaniel Salazar 11107f3108 fix(permissions,share): revoked team shares and removed links aren't read back from a lagging replica (#4554)
* fix(permissions): a revoked group grant isn't read back from a lagging replica

* fix(share): links removed by trash or a move aren't read back from a lagging replica, in any region

* test(permissions): start each test server in the file on an empty redis mock

* fix(permissions): node deletes find just-made grants on the primary; add a group membership hook

* fix(share): link revokes reach peer regions even when the local marker fails, and subtree retires read the primary

* fix(permissions): read a group's members after the grant is deleted

* fix(permissions): mark group members before a group grant is deleted

The member read and the marker now come before the delete, so a failed
member read leaves the grant in place for a retry and member reads are
already on the primary when the row goes. Members are read again after
the delete, best effort, to include someone who joined meanwhile.

The node-delete path returns those members, so ShareService bumps the
same list instead of reading each group again from a replica.
readUserGroupPerms checks the marker without the unused base-key GET.

* perf(share): trash and delete read grants from a replica unless the owner shared just now

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-11-12 17:58:05 -05:00
Juan Fernando CastroandDaniel Salazar 2c3b69011f fix(puter-js): unshare lists refused pairs in failed and rejects when all were refused (#4557)
* fix(puter-js): unshare rejects when every revoke was refused

/share/revoke reports refused pairs in a 200 body, and unshare() only
read `revoked`, so a call where every pair was refused resolved as if it
had worked. It now rejects with the first pair's { message, code }, the
same way share() does; a call where some pairs went through still
resolves with { revoked }.

GUI tests drive the SDK's unshare against a refused body and check that
the share dialogs and Remove from Shared show the error and keep the
row. The unshare docs list the per-pair codes.

* fix(puter-js): unshare and share reject with the first refused pair that names a code

A pair the server could not complete carries no code and a generic message,
so it no longer comes ahead of a refusal that says what happened. Both
operations pick the error through one helper. The unshare docs describe which
pair's error is surfaced and the request-level rejections.

* fix(gui): share modal says how many items a person was removed from when some were refused

After removing someone from several items, the refreshed listing is compared
with the items the removal covered, and the status reports the count that
went through instead of all of them.

* test(gui): unshare fixture swaps XMLHttpRequest per call; alert mock cleared in hooks

* feat(puter-js): unshare resolves with the refused pairs; share is as it was

unshare resolves { revoked, failed }, with one failed entry per refused
recipient/item pair. A pair refused because the recipient or the item is gone
counts as nothing to withdraw: the call rejects only when every pair was
refused and at least one for another reason, with the first such refusal that
names a code. paths and recipients are typed and documented.

share() picks its rejection as before; the error choice lives in unshare.

* fix(gui): sharing dialogs report the items an unshare was refused for

The share modal counts refused items from the unshare result across every
run of a large selection, going on past a run refused whole, for removing a
person and for closing the link on several items. The share window and
Remove from Shared show the refusal when the call resolves with the pair
refused.

* fix(gui): sharing dialogs keep the unshare outcome on screen after the listing refresh

The share modal shows the partial count once its refresh has settled, for
removing a person and for closing the link, so a listing that fails for the
refused item does not replace it. The share window does the same when closing
the link.

* feat(puter-js): an unshare rejected for refused pairs lists them in failed; failed[].path is documented as the absolute path

* test(puter-js): API suite covers unshare's refused pairs

* fix(gui): share modal stops at a revoke request that failed and counts only refused items

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-11-12 17:57:59 -05:00
Juan Fernando CastroandDaniel Salazar eefc1f2f2e fix(auth): the session list leaves out expired sessions, and revoking one works (#4573)
* fix(auth): the session list leaves out expired sessions

* test(auth): cover revoking expired sessions and their children

* fix(auth): the session list follows what authentication accepts

A token minted under a session that has expired is left out of the
list along with that session. The check runs in listSessions with the
rule authentication uses, so getByUserId returns expired rows again
and the revoke callers need no option.

* fix(auth): revoke-session answers 404 for another user's session

Missing, already revoked and other users' rows now share one answer.

* fix(auth): type the session list rows instead of casting them

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-11-12 17:57:51 -05:00
Juan Fernando CastroandDaniel Salazar 7e093d2ba7 perf(puter-js): reading the user at load joins the boot lookup (#4574)
* perf(puter-js): reading the user at load joins the boot lookup

* fix(puter-js): keep the token fallback to the user lookup resend

The fallback bearer is opt-in on initXhr, so other requests and their
replays send no bearer after sign-out, as before. A failed join (the
lookup or the copy) falls back to sending the request. Adds tests for
the legacy callback form and a resend after a network failure.

* fix(puter-js): join the boot user lookup only at the same API origin

A user lookup sent after setAPIOrigin() joined the boot /whoami still in
flight for the old origin and resolved its user instead of asking the new
one. The in-flight marker now records the origin too.

* fix(puter-js): a joined user read signs in from the boot lookup's answer and leaves on its first retry

- The boot lookup keeps one in-flight record (token, origin, user, refusal), made and cleared in cacheWhoami_.
- getUser(), puter.getUser() and whoami() share one join. A refused boot lookup drives the sign-in from its own response, so the token is not sent again; a sign-out meanwhile fails with 401 and sends nothing.
- The join ends when the boot lookup first has to retry, so the caller's own request goes out at once (new fetchUrl onRetry option).
- The joined user is copied with a JSON round trip; initXhr is back to its previous signature.

* fix(puter-js): whoami() keeps its refused-request error when it joined the boot lookup

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-11-12 17:56:42 -05:00
velzie bd7614372a fix(peer): grant forgery bug and stale comment 2026-11-12 17:48:10 -05:00
Daniel Salazar 61b5aa4900 fix(fs): treat path-less entries found by uid or id as missing (#4611)
A uid or id lookup can return a legacy row with no path when its parent
chain is broken. resolveNode now reports it as not found, so readdir,
stat and the other uid-addressed routes answer 404 instead of crashing
in the ACL check.
2026-11-12 15:44:14 -07:00
Wei-Lun Li a6e75b46cb fix(install): turn off plan gates in the Windows installer config (#4599)
install.sh writes "meteringEnforcement": { "subscriptions": false } into
config.json because a self-hosted install has no paid plans, so with the
gates on the OpenAI/Anthropic-compatible AI endpoints answer 402
subscription_required for every account. install.ps1 never got that
key, so a Windows install made with the README one-liner still has the
gates on. Write the same key from install.ps1.
2026-11-12 22:43:22 +00:00
Daniel Salazar dd32c7f9b2 fix(auth): a token whose lookup fails gets the outage error, not token_auth_failed (#4586)
The auth probe used to mark a token as failed whenever authenticate threw,
so a database error while checking a valid token came back as 401
token_auth_failed, which clients read as "discard this token".

The probe now records the thrown error on the request instead. Routes
that require auth hand it to the error handler (503 db_unavailable with
Retry-After for a database outage, a generic 500 otherwise); routes that
don't require auth serve the request anonymously, as before. Only a token
that authenticate reports invalid still gets 401 token_auth_failed.

The periodic socket re-check likewise keeps a connection up when its
lookup fails, instead of disconnecting it.
2026-11-12 15:39:51 -07:00
Nariman Jelveh aaa5c82236 Redirect /show/* to the dashboard and remove leftover desktop code (#4610)
* Redirect /show/* to the dashboard's Files tab

/show/<path> redirects to /dashboard#files/<path> with its query intact,
instead of booting the desktop and opening Explorer there.

Also removes what only that route used: the shell's launch options, the
launch_options GUI param, and the GUI service that ran them.

* Remove the unused component window and Flexer

Nothing opens UIComponentWindow or uses Flexer, and JustHTML was only the
component window's default body. Also drops the attach() shim UIQRCode kept
for component containers.

* Remove translation keys left by removed features

Drops 36 keys nothing references in every language: the keyboard shortcuts
guide, desktop shortcuts, personalization, the toolbar's fullscreen, GitHub
and refer entries, the referral strings, and the publishing option prompt.

* Inline the toolbar height, which is always zero

The toolbar is gone, so window.toolbar_height only added or subtracted zero
in window sizing and placement.

* Remove window edge snapping

Dragging a window to a screen edge or corner no longer snaps it to half or a
quarter of the screen. Double-clicking the head and the scale button still
maximize.

* Remove the window color theme service

Nothing can set a window theme, so the GUI stops reading the saved theme
file on boot and windows keep the default colors. puter.ui.on() still
accepts themeChanged, which is never sent; its docs entry is removed.

* Remove styles and icons nothing references

Drops the stylesheet rules of the removed Settings window, launch menu,
intro menu and a few other removed features, and 16 icons whose names
appear nowhere in the GUI.

* Remove more translation keys nothing references

Drops 56 keys in every language that no GUI code, extension or backend
message uses, such as the system information labels, the old 2FA setup and
confirm-code steps, and the auth token copy dialog strings.

* Remove the global menubar leftovers and more unused styles

Nothing creates a global menubar, so the window code stops hiding, showing
and removing one. Also drops stylesheet rules for classes nothing uses,
including the old auth dialog, the responsive hidden-* and visible-*
helpers, and two keyframes only those rules animated.
2026-11-12 15:31:38 -07:00
Daniel Salazar 8b68c103c5 fix(auth): mint under a full-access token without re-reading its session row, and look token rows up by uid through their indexes (#4588)
* fix(auth): mint under a full-access token from the row auth loaded, and look up token rows by uid with one index per column

A token minted by a full-access token now parents to the session row that
authentication already loaded and checked for the minting token, instead of
reading it again by token uid. The same applies to the session a relay token
is bound to. Tokens whose claims name no row of their own still look it up.

findActiveByAccessTokenUid now queries access_token_uid first and the legacy
uid only on a miss, each through its own index, instead of one OR across both
columns.

* fix(auth): send both access-token row lookups together, so a miss on the first costs no second round trip
2026-11-12 15:17:45 -07:00
Daniel Salazar 454f94fc54 fix(hosting): serve a launched public app's assets from its billing cookie without re-minting it (#4585)
Same-origin assets of a launched public app carry the launch token in the
Referer. When that token's signature verifies and it names the same user
and session as a valid public billing cookie (and, for an app token, the
same app), the cookie identity is used directly: no re-authentication, no
new cookie, no Set-Cookie. Any other combination resolves exactly as
before. Responses that do set the public cookie now carry
`Cache-Control: private`.
2026-11-12 14:28:35 -07:00
Daniel Salazar 8b7d380de1 fix(metering): a settle whose balance read fails still charges the allowance (#4584)
When the purchased-credit read or the near-allowance exact read fails while
settling a metered call, the call is now settled against the month record it
already has: the share that fits the monthly allowance is charged, and
purchased credit is left untouched since its balance could not be read.
Previously the whole settle was skipped, leaving the cost in the month total
but in neither pool.

Such settles skip the cached-balance update and overuse check, and raise one
info alarm id with the amount credit would have covered.
2026-11-12 14:27:29 -07:00
Daniel Salazar 8052a4287e fix(auth): close a revoked access token's sockets on every node (#4583)
Access-token revocation is announced as outer.auth.access-token.revoked,
so peer clusters evict the token's socket.io connections and realtime
relay sessions as the revoking cluster does. Peer payloads without a
string token_uid are ignored.
2026-11-12 14:27:10 -07:00
Daniel Salazar f114b13306 perf(gui): boot keeps a same-session token and skips /get-gui-token when the page already answers it (#4591)
* perf(gui): keep the stored token when /get-gui-token returns one for the same session

/get-gui-token signs a new string on every call, so every signed-in boot
stored a token that differed from the one it held only in `iat` and passed
it to puter.setAuthToken. That opened a second FS socket, re-sent /whoami
and the cache timestamp, and every other open tab picked the new token up
from storage and did the same.

The boot now keeps the stored token when the returned one carries exactly
the same claims apart from `iat`; any other difference replaces it as
before. A kept token still starts the boot from an empty FS cache, as the
swap did. A boot that keeps the persisted cache (no session cookie) now
waits for the cache timestamp check before the first render, which it
started before reading the user.

* perf(gui): skip /get-gui-token at boot when the page already says what it would return

Every signed-in boot waited on /get-gui-token before it read the user. The
shell is rendered from the same session cookie that route reads, so it now
carries `guiTokenDigest` in gui_params: a digest of the claims (minus
`iat`) of the GUI token the cookie's session would get, or null when the
request has no session cookie. A cookie that doesn't resolve to a user
session leaves it out.

The GUI skips the request when the digest matches its stored token (same
session, user and token type), or when it is null (the route would refuse).
It still asks when the parameter is missing, the digest names another
session, nothing is stored, the page and the route are on different
origins, or Navigation Timing doesn't show this page as freshly served for
this load (a history navigation or restored tab can reuse a page rendered
for an older cookie).
2026-11-12 14:26:09 -07:00
Nariman Jelveh ce70728eeb Remove the desktop's icons and right-click menu, and redirect /desktop (#4609)
* Remove the desktop's icons and right-click menu

The desktop no longer lists the Desktop folder's items, and right-clicking
its background opens no menu. It stays as the surface windows open on.

Also removes what only the icons used: file drops and item drops on the
desktop, rubber-band selection, auto arrange and saved icon positions, and
their two keys in puter.js's GUI boot cache. Clicking the desktop clears the
active item container so keyboard shortcuts stop acting on a window's items.

* Redirect /desktop and /settings to the dashboard

/desktop redirects to the root with its query intact, and /settings to the
dashboard's Home tab. /desktop drops out of the OIDC return_to allowlist,
sign-out returns to the root, and the auth cover page's logo links there.

Also removes eight GUI globals nothing references.

* Remove code paths that only ran for the desktop's item container

The desktop is no longer an item container, so the Trash item that
refresh_item_container added to it, the empty-folder message exemption,
and the context menu parent check for it can't be reached.
2026-11-12 14:00:29 -07:00
Nariman Jelveh 8518023b0b Remove more desktop-only features and entry points (#4607)
* Remove the desktop's Publish Website window

The right-click menu on desktop folders and on an Explorer window's
background no longer has a Publish as Website item. This removes
UIWindowPublishWebsite, the publishAsWebsite helper that opened it, both
menu items, the window's CSS, window.extractProtocol (only the window used
it), and the dir_published_as_website and pick_name_for_website i18n keys.

The dashboard keeps publishing websites through its own dialog.
generateFileContextMenu no longer falls back to the removed window, so it
offers Publish as Website only when the caller passes onPublishWebsite,
which the dashboard's Files tab does. The website badge on desktop items
and the backend hosting API are unchanged.

* Remove the desktop's Hide Desktop Icons toggle

The desktop's right-click menu no longer has a Hide/Show Desktop Icons
item. Without the wallpaper, hiding the icons left an empty page. This
removes the menu item, toggleDesktopIcons/hideDesktopIcons/
showDesktopIcons, the boot-time read of the saved setting, and the
.desktop-icons-hidden CSS rule.

puter.js's GUI boot cache no longer batch-fetches desktop_icons_hidden,
menubar_style or user_preferences.clock_visible, which nothing reads
anymore. Values already saved under those keys stay in KV, unread.

Also drops the desktop's BroadcastChannel, whose message handler was
empty and which nothing else referenced.

* Remove the desktop's ?download= link handler

Opening puter.com/?download=<url> or /desktop?download=<url> no longer
asks to save that remote file to the Desktop. The parameter is ignored,
and a root URL that carries it boots the dashboard like any other root
URL instead of forcing the desktop.

This removes the handler in UIDesktop, its UIWindowProgress import, the
download entry in the GUI's dashboard routing, and the
confirm_download_file_to_desktop, downloading, downloading_file,
uploading_file and error_download_failed i18n keys only it used.

The decision of whether a page load boots the dashboard moves from an
inline block in initgui into helpers/bootsDashboard.js, so it is tested.

* Stop granting Camera and Recorder Desktop access on desktop boot

The desktop no longer grants Camera and Recorder write access to the
user's Desktop folder the first time it loads. Those apps now ask
through the normal permission prompt, as they already did for users
who only used the dashboard. Grants already given stay in place.

puter.js's GUI boot cache no longer batch-fetches the
has_set_default_app_user_permissions flag that kept the grant to one
run. Values already saved under it stay in KV, unread.

* Redirect /@username links to the dashboard

puter.com/@<username> no longer opens that user's Public folder on the
desktop. The backend now redirects /@:username to /, so old links land
on the dashboard instead of booting the desktop.

This removes the GUI's /@ handler and the error_invalid_username i18n
key only it used. error_user_or_path_not_found stays, since share links
still use it.

* Redirect /desktop/app links and stop opening share links on the desktop

/desktop/app/<name> now redirects to /app/<name>, keeping its query
string, so the app opens in the dashboard. The backend no longer serves
an app shell there, OIDC sign-in no longer returns to it, and the GUI no
longer strips a leading /desktop from its route segments. The rate-limits
page lists only /app/<name>, the route the limit still applies to.

/desktop?shared=<path> no longer opens the shared item on the desktop.
The desktop ignores ?shared=: it doesn't ask a guest to sign in for it,
doesn't switch to the account a share email names, and OIDC sign-in from
/desktop doesn't carry it along. Share emails link to /?shared=, which
the dashboard handles as before. Opening a share notification on the
desktop still opens the item.

* Remove the desktop's ?app=explorer link handler

?app=explorer[&path=<folder>] no longer boots the desktop and opens an
Explorer window. ?app= is ignored and no longer forces the desktop, so a
root URL that carries it opens the dashboard, and /app/<name>?app=... now
launches its app in the dashboard instead of booting the desktop and
launching nothing.

* Stop ?puter.fullpage= from booting the desktop

The root and /app/<name> with ?puter.fullpage= now open in the dashboard
like a plain /app/<name>, with the app maximized. The dashboard always
shows apps full page, so the parameter no longer overrides that. Iframe
embeds and popups, which still boot the desktop, read it as before.

bootsDashboard no longer takes the query string, since no parameter
decides the interface anymore.
2026-11-12 11:54:40 -07:00
180 changed files with 5474 additions and 7286 deletions

No files matched your search

+7
View File
@@ -190,6 +190,13 @@ S3_BUCKET=puter-local
providers = [ordered]@{
ollama = [ordered]@{ enabled = $false }
}
# Off because a self-hosted install has no paid plans: every account
# is on the free policy, so the plan gates would 402 the surfaces that
# declare one (the OpenAI/Anthropic-compatible AI endpoints) for
# everybody. Same as install.sh.
meteringEnforcement = [ordered]@{
subscriptions = $false
}
trust_proxy = 1
}
$configJson = $config | ConvertTo-Json -Depth 10
-1
View File
@@ -125,7 +125,6 @@ describe('core without a teams registration', () => {
actor: { user: row },
} as never,
{ title: 'Puter' } as never,
{} as never,
);
const params = JSON.parse(
/gui\((\{.*?\})\);/s.exec(html)![1].replaceAll('\\u003c', '<'),
+12 -11
View File
@@ -736,6 +736,8 @@ export type EventMap = {
'outer.permission.flatInvalidated': {
entries: Array<{ holderUserId: number; permission: string }>;
};
/** Links on these nodes were removed; read them from the primary. */
'outer.share.linksRevoked': { fsentryIds: number[]; uuids: string[] };
/**
* A user's subscription set changed, so every process must drop its cached
* "does this user have any subscriptions" answer. Carries the counter the
@@ -874,8 +876,11 @@ export type EventMap = {
session_uids: string[];
};
/** One access token was revoked; only its own connections should drop. */
'auth.access-token.revoked': { token_uid: string };
/**
* One access token was revoked; only its own connections should drop.
* `outer.*` for the same reason as `outer.auth.sessions.revoked`.
*/
'outer.auth.access-token.revoked': { token_uid: string };
/** Same-cluster eviction for raw realtime WebSockets. */
'pubsub.realtime.auth-revoked': {
@@ -1083,11 +1088,10 @@ export type EventKey = keyof EventMap & string;
// Generates a wildcard for every non-final dot-separated prefix of K.
export type WildcardPrefixes<K extends string> =
K extends `${infer Head}.${infer Tail}`
?
| `${Head}.*`
| (Tail extends `${string}.${string}`
? `${Head}.${WildcardPrefixes<Tail>}`
: never)
? | `${Head}.*`
| (Tail extends `${string}.${string}`
? `${Head}.${WildcardPrefixes<Tail>}`
: never)
: never;
export type ListenKey = EventKey | WildcardPrefixes<EventKey>;
@@ -1098,10 +1102,7 @@ export type MatchingEvents<P extends ListenKey> = P extends `${infer Prefix}.*`
/** Acked, not acked, no socket anywhere, or sockets only in a peer region. */
export type NotifDeliveryOutcome =
| 'received'
| 'unreceived'
| 'no-socket'
| 'remote-only';
'received' | 'unreceived' | 'no-socket' | 'remote-only';
/** One socket's receipt for a live notification. */
export interface NotifDeliveryResponder {
@@ -23,6 +23,7 @@ import { makeActor } from '../../core/actor.js';
import { runWithContext } from '../../core/context.js';
import { createSecret as otpCreateSecret } from '../../services/auth/OTPUtil.js';
import { FULL_API_ACCESS } from '../../services/permission/consts.js';
import { tokenClaimsDigest } from '../../../gui/src/helpers/guiToken.js';
import {
createTestUser,
setupPuterTestEnv,
@@ -714,4 +715,67 @@ describe('session token helpers over HTTP', () => {
'puter_auth_token=',
);
});
describe("the shell's guiTokenDigest", () => {
/** The session cookie `/session/sync-cookie` sets for `token`. */
const sessionCookie = async (token: string) => {
const sync = await get('/session/sync-cookie', token);
expect(sync.status).toBe(204);
const value = /puter_auth_token=([^;]+)/.exec(
sync.headers.get('set-cookie') ?? '',
)?.[1];
expect(value).toBeTruthy();
return `puter_auth_token=${value}`;
};
/** What the shell at `path` renders for `guiTokenDigest`. */
const shellDigest = async (path: string, cookie?: string) => {
const res = await fetch(new URL(path, env.origin), {
headers: cookie ? { cookie } : {},
});
expect(res.status).toBe(200);
const html = await res.text();
const match = /"guiTokenDigest":(null|"[0-9a-f]{32}")/.exec(html);
if (!match) {
expect(html).not.toContain('guiTokenDigest');
return undefined;
}
return JSON.parse(match[1]) as string | null;
};
it("names the token /get-gui-token hands over for the session cookie", async () => {
const { token } = await signupTemp();
const cookie = await sessionCookie(token);
const gui = await fetch(new URL('/get-gui-token', env.origin), {
headers: { cookie },
});
expect(gui.status).toBe(200);
const { token: guiToken } = (await gui.json()) as { token: string };
const digest = await shellDigest('/', cookie);
expect(digest).toBe(await tokenClaimsDigest(guiToken));
// The token the browser stored at sign-up is for the same session.
expect(await tokenClaimsDigest(token)).toBe(digest);
});
it('is null without a session cookie, even with a token in the URL', async () => {
const { token } = await signupTemp();
expect(await shellDigest('/')).toBe(null);
expect(
await shellDigest(`/?auth_token=${encodeURIComponent(token)}`),
).toBe(null);
});
it('is left out when the session cookie does not resolve to a session', async () => {
const { token } = await signupTemp();
const cookie = await sessionCookie(token);
await env.server.services.auth.revokeSession(claims(token).session_uid);
expect(await shellDigest('/', cookie)).toBe(undefined);
expect(await shellDigest('/', 'puter_auth_token=garbage')).toBe(
undefined,
);
});
});
});
@@ -8293,11 +8293,10 @@ describe('AuthController session endpoints', () => {
).rejects.toMatchObject({ statusCode: 400 });
});
it('revoke-session: 403 when revoking someone else’s session', async () => {
it('revoke-session: 404 when revoking someone else’s session', async () => {
const { user: u1 } = await makeUserAndActor();
const { actor: a2 } = await makeUserAndActor();
// Create a real session for u1 so the lookup succeeds, then attempt
// to revoke it as a2 — must 403.
// A real session of u1, revoked as a2: answers as a missing one.
const sessionRes = await server.services.auth.createSessionToken(
u1,
{},
@@ -8310,7 +8309,7 @@ describe('AuthController session endpoints', () => {
),
makeRes(),
),
).rejects.toMatchObject({ statusCode: 403 });
).rejects.toMatchObject({ statusCode: 404 });
});
it('rename-session: 400 when uuid param is missing', async () => {
@@ -10082,6 +10081,77 @@ describe('AuthController.handleRevokeSession additional branches', () => {
expect(Array.isArray(body.sessions)).toBe(true);
});
const expiredSessionOf = async (user: { id: number }) => {
const row = await server.stores.session.create(user.id, {
expires_at: Math.floor(Date.now() / 1000) - 1,
});
return row.uuid as string;
};
it('revokes an expired session the caller owns', async () => {
const { user, actor } = await makeUserAndActor();
const uuid = await expiredSessionOf(user);
const res = makeRes();
await controller.handleRevokeSession(makeReq({ uuid }, { actor }), res);
const body = res.body as { sessions: Array<{ uuid: string }> };
expect(body.sessions.map((s) => s.uuid)).not.toContain(uuid);
const rows = await server.clients.db.read(
'SELECT `revoked_at` FROM `sessions` WHERE `uuid` = ?',
[uuid],
);
expect(rows[0].revoked_at).not.toBeNull();
});
it('revoking an expired session ends its live child token', async () => {
const { user, actor } = await makeUserAndActor();
const parent = await expiredSessionOf(user);
const child = await server.stores.session.getOrCreateGodmodeToken(
user.id,
{
parentSessionUid: parent,
appUid: `app-${uuidv4()}`,
expiresAt: Math.floor(Date.now() / 1000) + 3600,
maxAgeSeconds: 3600,
label: 'Godmode app',
auth_id: user.uuid,
},
);
const childUuid = child!.row.uuid as string;
expect(await server.stores.session.getByUuid(childUuid)).toBeTruthy();
await controller.handleRevokeSession(
makeReq({ uuid: parent }, { actor }),
makeRes(),
);
expect(await server.stores.session.getByUuid(childUuid)).toBeNull();
});
it('answers 404 for an expired session of another user', async () => {
const { user: owner } = await makeUserAndActor();
const { actor } = await makeUserAndActor();
const uuid = await expiredSessionOf(owner);
await expect(
controller.handleRevokeSession(
makeReq({ uuid }, { actor }),
makeRes(),
),
).rejects.toMatchObject({ statusCode: 404 });
});
it('answers 404 for a session that is already revoked', async () => {
const { user, actor } = await makeUserAndActor();
const row = await server.stores.session.create(user.id);
await server.stores.session.removeByUuid(row.uuid);
await expect(
controller.handleRevokeSession(
makeReq({ uuid: row.uuid }, { actor }),
makeRes(),
),
).rejects.toMatchObject({ statusCode: 404 });
});
it('refuses to revoke the caller’s OWN current session row (400)', async () => {
// Invariant: a self-revoke leaves the client in an ambiguous
// identity state because the response can't write fresh auth
+8 -11
View File
@@ -3585,21 +3585,18 @@ export class AuthController extends PuterController {
{ legacyCode: 'bad_request' },
);
}
// `getByUuid` returns null when the row is missing, already
// soft-revoked, or past `expires_at` — surface as 404 so a stale
// manage-sessions UI doesn't 500 when it clicks revoke on a row
// that already went away.
const session = await this.stores.session.getByUuid(uuid);
if (!session) {
// Missing, already revoked and other users' rows all answer 404; an
// expired row is still revoked so its children go with it.
const session = await this.stores.session.getByUuidAny(uuid);
if (
!session ||
session.revoked_at != null ||
session.user_id !== req.actor!.user.id
) {
throw new HttpError(404, 'Session not found', {
legacyCode: 'not_found',
});
}
if (session.user_id !== req.actor!.user.id) {
throw new HttpError(403, 'Can only revoke your own sessions', {
legacyCode: 'unauthorized',
});
}
await this.services.auth.revokeSession(uuid);
const sessions = await this.services.auth.listSessions(req.actor!);
res.json({ sessions });
@@ -154,6 +154,26 @@ describe('GET /fs/readdir over HTTP', () => {
).toEqual(['a', 'a/b']);
});
it('answers 404 for a directory whose parent chain is broken', async () => {
const { username, token } = env.users.user;
const path = `/${username}/Documents/http-orphan-${Date.now()}`;
const created = await fetch(new URL('/fs/mkdir', env.apiOrigin), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path, auth_token: token }),
});
expect(created.status).toBe(200);
const { uid } = (await created.json()) as { uid: string };
await env.server.clients.db.write(
'UPDATE fsentries SET path = NULL, parent_uid = ? WHERE uuid = ?',
['does-not-exist', uid],
);
await env.server.stores.fsEntry.invalidateEntryCacheByUuid(uid);
const response = await fetch(readdirUrl({ uid, auth_token: token }));
expect(response.status).toBe(404);
});
it('mkdir does not return internal ids, storage columns or tokens', async () => {
const { username, token } = env.users.user;
const response = await fetch(new URL('/fs/mkdir', env.apiOrigin), {
@@ -79,6 +79,7 @@ interface CapturedResponse {
statusCode: number;
body: unknown;
contentType?: string;
location?: string;
}
const makeReq = (init: {
@@ -87,6 +88,7 @@ const makeReq = (init: {
actor?: Actor;
hostname?: string;
protocol?: string;
originalUrl?: string;
}): Request => {
return {
body: {},
@@ -94,6 +96,7 @@ const makeReq = (init: {
headers: {},
params: init.params ?? {},
path: init.path ?? '/',
originalUrl: init.originalUrl ?? init.path ?? '/',
hostname: init.hostname ?? 'test.local',
protocol: init.protocol ?? 'http',
actor: init.actor,
@@ -131,6 +134,11 @@ const makeRes = () => {
captured.contentType = value;
return res;
}),
redirect: vi.fn((location: string) => {
captured.statusCode = 302;
captured.location = location;
return res;
}),
};
return { res: res as unknown as Response, captured };
};
@@ -214,23 +222,72 @@ describe('HomepageController shell routes', () => {
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
});
it('serves the shell on /settings, /dashboard, /desktop, /action, /@:username', async () => {
for (const path of [
'/settings',
'/settings/*splat',
'/dashboard',
'/dashboard/',
'/desktop',
'/desktop/',
'/action/*splat',
'/@:username',
]) {
it('leaves guiTokenDigest out for a session cookie that is not a user session', async () => {
const { actor } = await makeUser();
const appActor = {
...actor,
app: { id: 1, uid: 'app-test' },
session: { uid: uuidv4() },
} as unknown as Actor;
const req = Object.assign(makeReq({ path: '/', actor: appActor }), {
tokenSource: 'cookie',
cookies: { puter_token_v2: 'legacy' },
});
const { res, captured } = makeRes();
await callRoute('get', '/', req, res);
expect(String(captured.body)).not.toContain('guiTokenDigest');
});
it('serves the shell on /dashboard and /action', async () => {
for (const path of ['/dashboard', '/dashboard/', '/action/*splat']) {
const { res, captured } = makeRes();
await callRoute('get', path, makeReq({ path }), res);
expect(typeof captured.body).toBe('string');
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
}
});
it('redirects /desktop to the root, keeping the query', async () => {
for (const path of ['/desktop', '/desktop/']) {
const { res, captured } = makeRes();
await callRoute(
'get',
path,
makeReq({ path, originalUrl: `${path}?ref=abc&x=1` }),
res,
);
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe('/?ref=abc&x=1');
expect(captured.body).toBeUndefined();
}
const { res, captured } = makeRes();
await callRoute('get', '/desktop', makeReq({ path: '/desktop' }), res);
expect(captured.location).toBe('/');
});
it('redirects /settings to the dashboard Home tab', async () => {
for (const path of ['/settings', '/settings/*splat']) {
const { res, captured } = makeRes();
await callRoute('get', path, makeReq({ path }), res);
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe('/dashboard#home');
expect(captured.body).toBeUndefined();
}
});
it('redirects /@:username to the dashboard', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/@:username',
makeReq({ path: '/@alice', params: { username: 'alice' } }),
res,
);
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe('/');
expect(captured.body).toBeUndefined();
});
});
// ── /app/:name ──────────────────────────────────────────────────────
@@ -360,47 +417,21 @@ describe('HomepageController GET /app/:name', () => {
expect(html).not.toContain('owner_user_id');
});
it('serves the same app shell under /desktop/app/:name', async () => {
const { userId } = await makeUser();
const name = `desk-${Math.random().toString(36).slice(2, 10)}`;
await server.stores.app.create(
{
name,
title: 'Desktop App',
description: 'opens on the desktop instead of the dashboard',
index_url: `https://example.com/${name}/`,
approved_for_listing: 1,
},
{ ownerUserId: userId },
);
const { res, captured } = makeRes();
await callRoute(
'get',
'/desktop/app/:name',
makeReq({ params: { name }, path: `/desktop/app/${name}` }),
res,
);
expect(captured.statusCode).toBe(200);
const html = String(captured.body);
expect(html).toMatch(/<!DOCTYPE html>/i);
expect(html).toContain('Desktop App');
});
it('returns 404 under /desktop/app/:name when the app is unknown', async () => {
it('redirects /desktop/app/:name to /app/:name, keeping the query', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/desktop/app/:name',
makeReq({
params: { name: 'no-such-app' },
path: '/desktop/app/no-such-app',
params: { name: 'editor' },
path: '/desktop/app/editor',
originalUrl: '/desktop/app/editor?file=%2Falice%2Fa.txt&x=1',
}),
res,
);
expect(captured.statusCode).toBe(404);
expect(String(captured.body)).toMatch(/<!DOCTYPE html>/i);
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe('/app/editor?file=%2Falice%2Fa.txt&x=1');
expect(captured.body).toBeUndefined();
});
it('omits index_url even for a public app — the shell is not the launch authority', async () => {
@@ -434,40 +465,39 @@ describe('HomepageController GET /app/:name', () => {
// -- app landing rate limit --
describe('HomepageController app landing rate limit', () => {
it('rate-limits /app/:name and /desktop/app/:name per network', () => {
for (const path of ['/app/:name', '/desktop/app/:name']) {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === path,
);
if (!route) throw new Error(`No GET ${path} route`);
expect(route.options.rateLimit).toEqual({
scope: 'app-landing',
limit: 600,
window: 60_000,
key: 'ip',
});
}
it('rate-limits /app/:name per network', () => {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === '/app/:name',
);
if (!route) throw new Error('No GET /app/:name route');
expect(route.options.rateLimit).toEqual({
scope: 'app-landing',
limit: 600,
window: 60_000,
key: 'ip',
});
});
});
// ── /show/* ─────────────────────────────────────────────────────────
describe('HomepageController GET /show/*splat', () => {
it('emits a launch_app explorer call with the post-/show path', async () => {
it('redirects to the path in the dashboard Files tab, keeping the query', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/show/*splat',
makeReq({ path: '/show/alice/Documents' }),
makeReq({
path: '/show/alice/My%20Documents',
originalUrl: '/show/alice/My%20Documents?ref=abc',
}),
res,
);
// The launch payload is JSON-serialized into the rendered HTML.
// We assert the rendered shell included the explorer launch hint
// pointing at the expected (slashed) path.
const html = String(captured.body);
expect(html).toContain('launch_app');
expect(html).toContain('explorer');
expect(html).toContain('/alice/Documents');
expect(captured.statusCode).toBe(302);
expect(captured.location).toBe(
'/dashboard?ref=abc#files/alice/My%20Documents',
);
expect(captured.body).toBeUndefined();
});
});
@@ -20,6 +20,7 @@
import express from 'express';
import path from 'node:path';
import { PuterController } from '../types.js';
import { isPlainUserActor } from '../../core/actor.js';
import { toAppShellView } from '../../util/appShellView.js';
import type { PuterRouter } from '../../core/http/PuterRouter';
import {
@@ -27,11 +28,12 @@ import {
subdomainLabelOf,
} from '../../core/http/middleware/hostRedirects.js';
import type { IConfig } from '../../types';
import type { UserRow } from '../../stores/user/UserStore';
import type {
PuterHomepageService,
PageMeta,
LaunchOptions,
PopupFrame,
ShellContext,
} from '../../services/homepage/PuterHomepageService';
/**
@@ -170,7 +172,6 @@ export class HomepageController extends PuterController {
req: express.Request,
res: express.Response,
metaOverrides: Partial<PageMeta> = {},
launch: LaunchOptions = {},
popupFrame?: PopupFrame,
) => {
const meta = { ...defaultMeta(req), ...metaOverrides };
@@ -180,7 +181,16 @@ export class HomepageController extends PuterController {
actor?: Parameters<typeof homepage.send>[0]['actor'];
}
).actor ?? null;
await homepage.send({ req, res, actor }, meta, launch, popupFrame);
await homepage.send(
{
req,
res,
actor,
guiTokenDigest: this.#guiTokenDigest(req, actor),
},
meta,
popupFrame,
);
};
// -- Root + path-aliased shell routes ------------------------
@@ -252,7 +262,6 @@ export class HomepageController extends PuterController {
req,
res,
{},
{},
{
hostOrigin: embedHostOrigin(
this.config,
@@ -263,23 +272,42 @@ export class HomepageController extends PuterController {
});
}
router.get('/settings', {}, (req, res) => sendShell(req, res));
router.get('/settings/*splat', {}, (req, res) => sendShell(req, res));
// Old settings links land on the dashboard's Home tab.
router.get('/settings', {}, (_req, res) =>
res.redirect('/dashboard#home'),
);
router.get('/settings/*splat', {}, (_req, res) =>
res.redirect('/dashboard#home'),
);
router.get('/dashboard', {}, (req, res) => sendShell(req, res));
router.get('/dashboard/', {}, (req, res) => sendShell(req, res));
router.get('/desktop', {}, (req, res) => sendShell(req, res));
router.get('/desktop/', {}, (req, res) => sendShell(req, res));
const queryOf = (req: express.Request) => {
const separator = req.originalUrl.indexOf('?');
return separator === -1 ? '' : req.originalUrl.slice(separator);
};
// Old desktop links land on the dashboard, query intact.
router.get('/desktop', {}, (req, res) =>
res.redirect(`/${queryOf(req)}`),
);
router.get('/desktop/', {}, (req, res) =>
res.redirect(`/${queryOf(req)}`),
);
router.get('/action/*splat', {}, (req, res) => sendShell(req, res));
router.get('/@:username', {}, (req, res) => sendShell(req, res));
// Old links to a user's public folder land on the dashboard.
router.get('/@:username', {}, (_req, res) => res.redirect('/'));
// Old desktop app links open the app in the dashboard, query intact.
router.get('/desktop/app/:name', {}, (req, res) => {
const name = encodeURIComponent(String(req.params.name ?? ''));
res.redirect(`/app/${name}${queryOf(req)}`);
});
// -- /app/:name - app metadata baked into the shell ----------
// `/desktop/app/:name` is the same landing booted on the desktop
// instead of the dashboard; the GUI strips the prefix and treats the
// rest of the path identically, so both render the same shell.
const sendAppShell = async (
req: express.Request,
@@ -334,26 +362,11 @@ export class HomepageController extends PuterController {
{ rateLimit: APP_LANDING_LIMIT },
sendAppShell,
);
router.get(
'/desktop/app/:name',
{ rateLimit: APP_LANDING_LIMIT },
sendAppShell,
);
// -- /show/* - launch explorer with the requested file path --
// Old /show links open the path in the dashboard's Files tab, query intact.
router.get('/show/*splat', {}, (req, res) => {
const filePath = req.path.slice('/show'.length);
const launch: LaunchOptions = {
on_initialized: [
{
$: 'window-call',
fn_name: 'launch_app',
args: [{ name: 'explorer', path: filePath }],
},
],
};
return sendShell(req, res, {}, launch);
res.redirect(`/dashboard${queryOf(req)}#files${filePath}`);
});
// -- /sw.js - the service worker, scoped to the whole origin --
@@ -382,6 +395,38 @@ export class HomepageController extends PuterController {
);
}
}
/**
* Lets the GUI skip `/get-gui-token`, which reads the session cookie: the
* digest of the token it would hand over, null when there is no session
* cookie (either name the auth probe reads), and undefined (the GUI asks)
* when a cookie didn't resolve to a session.
*/
#guiTokenDigest(
req: express.Request,
actor: ShellContext['actor'],
): string | null | undefined {
if (req.tokenSource === 'cookie') {
if (!actor || !isPlainUserActor(actor) || !actor.session?.uid) {
return undefined;
}
return this.services.auth.guiTokenDigest(
actor.user as UserRow,
actor.session.uid,
);
}
const cookies = (req.cookies ?? {}) as Record<string, unknown>;
const hasSessionCookie = [
this.config.cookie_name,
'puter_token_v2',
].some(
(name) =>
!!name &&
typeof cookies[name] === 'string' &&
cookies[name] !== '',
);
return hasSessionCookie ? undefined : null;
}
}
const safeJsonParse = (s: string): Record<string, unknown> | null => {
@@ -372,26 +372,6 @@ describe('OIDCController GET /auth/oidc/:provider/start', () => {
);
});
it('bakes a whitelisted desktop app landing (/desktop/app/<name>) into the state redirect_uri', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/auth/oidc/:provider/start',
makeReq({
params: { provider: 'custom' },
query: { return_to: '/desktop/app/my-App_2' },
}),
res,
);
const state = new URL(captured.redirectUrl ?? '').searchParams.get(
'state',
);
const decoded = oidc().verifyState(state!);
expect(String(decoded?.redirect_uri)).toBe(
`${TEST_ORIGIN}/desktop/app/my-App_2`,
);
});
it('ignores a non-whitelisted return_to', async () => {
const bad_values = [
'/app/evil/extra',
@@ -400,6 +380,8 @@ describe('OIDCController GET /auth/oidc/:provider/start', () => {
'//evil.test',
'/settings',
`/app/${'a'.repeat(101)}`,
'/desktop',
'/desktop/app/my-App_2',
'/desktop/app/evil/extra',
'/desktop/app/',
'/dashboard/app/name',
@@ -476,11 +458,11 @@ describe('OIDCController GET /auth/oidc/:provider/start', () => {
sharedPath('b.txt'),
sharedPath('a.txt'),
],
'/desktop',
'/dashboard',
),
);
const url = new URL(uri);
expect(url.origin + url.pathname).toBe(`${TEST_ORIGIN}/desktop`);
expect(url.origin + url.pathname).toBe(`${TEST_ORIGIN}/dashboard`);
expect(url.searchParams.getAll('shared')).toEqual([
sharedPath('a.txt'),
sharedPath('b.txt'),
@@ -102,16 +102,14 @@ function signupOptionsFromState(
}
// GUI pages an OIDC flow may return to: the root (where a share email lands),
// /desktop, /dashboard, and direct app landings (/app/<name> and its
// desktop-booted twin /desktop/app/<name>, mirroring APP_NAME_REGEX in
// AppDriver). Strict whitelist — never a client-supplied URL (no open
// redirect).
// /dashboard, and direct app landings (/app/<name>, mirroring
// APP_NAME_REGEX in AppDriver). Strict whitelist — never a client-supplied URL
// (no open redirect).
function isWhitelistedReturnPath(path: string): boolean {
return (
path === '/' ||
path === '/desktop' ||
path === '/dashboard' ||
/^(\/desktop)?\/app\/[a-zA-Z0-9_-]{1,100}$/.test(path)
/^\/app\/[a-zA-Z0-9_-]{1,100}$/.test(path)
);
}
@@ -438,9 +436,8 @@ export class OIDCController extends PuterController {
let appRedirectUri = flowRedirects[flow] ?? (origin || '/');
// Optional GUI return path so login started from /desktop,
// /dashboard, an /app/<name> landing, or a share link lands
// back there.
// Optional GUI return path so login started from /dashboard,
// an /app/<name> landing, or a share link lands back there.
const rawReturnTo = Array.isArray(req.query.return_to)
? req.query.return_to[0]
: req.query.return_to;
@@ -314,8 +314,8 @@ describe('OIDC account second-factor login', () => {
it('preserves ordinary OIDC login for accounts without 2FA', async () => {
await account(false);
const response = await callback('login', { return_to: '/desktop' });
expect(response.headers.get('location')).toBe(`${env.origin}/desktop`);
const response = await callback('login', { return_to: '/dashboard' });
expect(response.headers.get('location')).toBe(`${env.origin}/dashboard`);
expect(
response.headers.get('set-cookie')?.includes('puter_auth_token='),
).toBe(true);
+20 -13
View File
@@ -24,11 +24,7 @@ import { computeNetworkFingerprint } from '../../core/http/middleware/rateLimit.
import type { PuterRouter } from '../../core/http/PuterRouter.js';
import { PuterController } from '../types.js';
import { PEER_COSTS } from './costs.js';
import {
readClaimedGrantIdentifier,
signGuestGrant,
verifyGuestGrant,
} from './guestGrant.js';
import { signGuestGrant, verifyGuestGrant } from './guestGrant.js';
import {
DEFAULT_FREE_SUBSCRIPTION,
DEFAULT_TEMP_SUBSCRIPTION,
@@ -191,19 +187,30 @@ export class PeerController extends PuterController {
// guests share one bucket and no host can be relayed for by
// more guests per minute than this — the only ceiling on guest
// spend we can apply before the bytes are already spent.
// A grant that doesn't parse can't name a bucket, so those
// requests fall back to the caller's own network.
// The limiter counts a request when it admits it, so only a
// grant that would redeem names a host; otherwise anyone
// holding the host's identifier could drain the bucket and
// lock out every real guest. Anything else - forged, expired,
// malformed, or no secret configured - is charged to the
// caller's own network.
rateLimit: {
scope: 'peer-guest-turn',
limit: 60,
window: 60_000,
key: (req: Request) => {
const claimed = readClaimedGrantIdentifier(
(req.body as { grant?: unknown } | undefined)
?.grant,
);
return claimed
? `host:${claimed}`
const secret =
this.config.peers?.guest_turn?.grant_secret;
const verified = secret
? verifyGuestGrant({
grant: (
req.body as
{ grant?: unknown } | undefined
)?.grant,
secret,
})
: null;
return verified?.status === 'ok'
? `host:${verified.customIdentifier}`
: `net:${computeNetworkFingerprint(req)}`;
},
},
+1 -1
View File
@@ -19,7 +19,7 @@
import { toMicroCents } from '../../services/metering/utils';
// Microcents per byte of TURN egress ($0.05/GB).
// Microcents per byte of TURN egress ($0.10/GB).
export const PEER_COSTS = {
'turn:egress-bytes': toMicroCents(0.1 / 1000 ** 3),
} as const;
@@ -1,7 +1,6 @@
import { createHmac } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import {
readClaimedGrantIdentifier,
signGuestGrant,
verifyGuestGrant,
} from './guestGrant.js';
@@ -243,59 +242,3 @@ describe('signGuestGrant / verifyGuestGrant', () => {
});
});
});
describe('readClaimedGrantIdentifier', () => {
it('reads the identifier from a valid grant', () => {
const { grant } = signGuestGrant({
customIdentifier: USER_ID,
ttlSeconds: 60,
secret: SECRET,
});
expect(readClaimedGrantIdentifier(grant)).toBe(USER_ID);
});
it('reads the claimed identifier without checking the signature', () => {
// Bucketing runs before verification, so this is expected: a forged
// grant still names a bucket, and the handler still rejects it.
const grant = forgeGrant(
{ id: USER_ID, exp: 9_999_999_999, n: 'x' },
{ secret: 'wrong-secret' },
);
expect(readClaimedGrantIdentifier(grant)).toBe(USER_ID);
});
it('reads an expired grant, which the handler then rejects', () => {
const { grant } = signGuestGrant({
customIdentifier: USER_ID,
ttlSeconds: 60,
secret: SECRET,
now: 1_000_000_000_000,
});
expect(readClaimedGrantIdentifier(grant)).toBe(USER_ID);
expect(verifyGuestGrant({ grant, secret: SECRET })).toEqual({
status: 'expired',
});
});
it.each([
['a non-string', 42],
['undefined', undefined],
['a wrong-shaped string', 'not-a-grant'],
['an unknown version', 'pg2.abc.def'],
['an over-long string', `pg1.${'a'.repeat(600)}.sig`],
[
'a non-JSON payload',
`pg1.${Buffer.from('x').toString('base64url')}.sig`,
],
])('returns null for %s', (_label, grant) => {
expect(readClaimedGrantIdentifier(grant)).toBeNull();
});
it('returns null for an identifier of the wrong shape', () => {
const grant = forgeGrant({ id: 'nope', exp: 9_999_999_999 });
expect(readClaimedGrantIdentifier(grant)).toBeNull();
});
});
@@ -171,37 +171,3 @@ export const verifyGuestGrant = ({
expiresAt: payload.exp,
};
};
/**
* Read the claimed identifier out of a grant _without_ verifying it, for
* rate-limit bucketing only.
*
* Bucketing has to happen before the handler runs, and a forged grant is
* rejected there without reaching the upstream API — so an unverified read is
* enough to put a host's guests in one bucket, and the worst a forger achieves
* is choosing which bucket their own rejections land in. Never use this to
* decide attribution.
*
* @returns The claimed identifier, or null if the grant doesn't parse.
*/
export const readClaimedGrantIdentifier = (grant: unknown): string | null => {
if (typeof grant !== 'string' || grant.length > MAX_GRANT_LENGTH) {
return null;
}
const parts = grant.split('.');
if (parts.length !== 3 || parts[0] !== GRANT_VERSION) return null;
try {
const payload = JSON.parse(
Buffer.from(parts[1]!, 'base64url').toString('utf8'),
) as { id?: unknown };
if (
typeof payload?.id !== 'string' ||
!IDENTIFIER_RE.test(payload.id)
) {
return null;
}
return payload.id;
} catch {
return null;
}
};
@@ -243,6 +243,33 @@ describe('WispController', () => {
expect(await verifyStatus(token)).toBe(403);
});
it('binds a token minted by an access token to that token while the replica lags', async () => {
const { sessionActor, apiTokenActor, apiToken } = await freshUser();
const db = server.clients.db;
const original = db.read.bind(db);
const spy = vi
.spyOn(db, 'read')
.mockImplementation(async (sql: string, params?: unknown[]) =>
sql.includes("FROM `sessions` WHERE `kind` = 'access_token'")
? []
: original(sql, params),
);
let token: string;
try {
token = await relayTokenFor(apiTokenActor);
} finally {
spy.mockRestore();
}
expect(await verifyStatus(token)).toBe(200);
await server.services.auth.revokeAccessToken(
sessionActor,
apiToken,
);
expect(await verifyStatus(token)).toBe(403);
});
it('applies the account checks to a token with no session claim', async () => {
const { row } = await freshUser();
const token = server.services.token.sign(
@@ -151,11 +151,12 @@ export class WispController extends PuterController {
/**
* The session a relay token lives no longer than. An access token's is its
* own session row; the actor doesn't carry it.
* own session row.
*/
async #sessionUidFor(actor: Actor): Promise<string | undefined> {
if (actor.session?.uid) return actor.session.uid;
if (!actor.accessToken) return undefined;
if (actor.accessToken.sessionUid) return actor.accessToken.sessionUid;
const row = await this.stores.session.findActiveByAccessTokenUid(
actor.accessToken.uid,
);
+5
View File
@@ -47,6 +47,11 @@ export interface ActorAccessToken {
* reach while revokes, audits and gate hooks can still name the app.
*/
godmodeApp?: ActorApp | null;
/**
* The token's own session row, checked live when it authenticated. Unset
* when the token carries no `session_uid` naming its row.
*/
sessionUid?: string;
}
export interface Actor {
@@ -50,6 +50,13 @@ declare global {
tokenAuthFailed?: boolean;
/**
* What `authenticate` threw while checking the token (a database
* failure, say). The token may be fine; gates rethrow this instead
* of answering 401.
*/
tokenAuthError?: unknown;
/**
* Set when a token authenticated but its app is on the origin
* blocklist. The auth probe leaves `actor` unset; gates translate
@@ -0,0 +1,110 @@
/*
* 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 { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { setupPuterTestEnv, type PuterTestEnv } from '../../../testUtil.js';
const loadShed = () =>
Object.assign(new Error('Database operation failed'), {
code: 'dbBatchFailed',
});
/**
* A token whose lookup fails is not a dead token: clients discard a token on
* 401 `token_auth_failed`, so that answer is kept for tokens that checked out
* invalid.
*/
describe('auth probe when the token lookup fails', () => {
let env: PuterTestEnv;
beforeAll(async () => {
env = await setupPuterTestEnv();
}, 120_000);
afterAll(async () => {
await env?.shutdown();
});
const get = (path: string, token: string) =>
fetch(new URL(path, env.apiOrigin), {
headers: { authorization: `Bearer ${token}` },
});
/** Run `fn` while the next user lookup rejects with `error`. */
const withFailedUserLookup = async <T>(
error: Error,
fn: () => Promise<T>,
): Promise<T> => {
const spy = vi
.spyOn(env.server.stores.user, 'getByUuid')
.mockRejectedValueOnce(error);
try {
return await fn();
} finally {
spy.mockRestore();
}
};
it.each([
['a session token', () => env.users.user.token],
['an access token', () => env.users.user.apiToken],
])(
'answers %s with 503 db_unavailable during a database outage',
async (_kind, tokenOf) => {
const token = tokenOf();
const res = await withFailedUserLookup(loadShed(), () =>
get('/whoami', token),
);
expect(res.status).toBe(503);
expect(res.headers.get('retry-after')).toBe('5');
expect(await res.json()).toEqual({
error: 'Service temporarily unavailable',
message: 'Service temporarily unavailable',
code: 'db_unavailable',
});
expect((await get('/whoami', token)).status).toBe(200);
},
);
it('answers an unexpected lookup failure with a generic 500, not a 401', async () => {
const res = await withFailedUserLookup(new Error('boom'), () =>
get('/whoami', env.users.user.token),
);
expect(res.status).toBe(500);
expect((await res.json()).code).toBe('internal_error');
});
it('serves a route that does not require auth anonymously', async () => {
const res = await withFailedUserLookup(loadShed(), () =>
get('/version', env.users.user.token),
);
expect(res.status).toBe(200);
});
it('still answers an invalid token with 401 token_auth_failed', async () => {
const res = await get('/whoami', 'not-a-real-jwt');
expect(res.status).toBe(401);
expect(await res.json()).toEqual({
error: 'Authentication failed',
message: 'Authentication failed',
code: 'token_auth_failed',
});
});
});
@@ -555,17 +555,18 @@ describe('createAuthProbe — actor attachment + failure tracking', () => {
expect(req.tokenAuthFailed).toBe(true);
});
it('never rejects — sets tokenAuthFailed even when AuthService throws', async () => {
it('never rejects — records the error, not tokenAuthFailed, when AuthService throws', async () => {
const stub = makeStubAuth();
stub.setNext('throw');
const probe = createAuthProbe({ authService: stub.service });
const { req, next } = await runProbe(
probe,
makeReq({ headers: { authorization: 'Bearer bad-tok' } }),
makeReq({ headers: { authorization: 'Bearer some-tok' } }),
);
// Critical invariant: the probe NEVER rejects, no matter what.
expect(next).toHaveBeenCalledWith();
expect(req.tokenAuthFailed).toBe(true);
expect(req.tokenAuthFailed).toBeUndefined();
expect(req.tokenAuthError).toBeInstanceOf(Error);
expect(req.actor).toBeUndefined();
});
@@ -880,4 +881,27 @@ describe('createAuthProbe (integration) — real session token → real actor',
expect(req.actor).toBeUndefined();
expect(req.tokenAuthFailed).toBe(true);
});
it('records a failed user lookup on a valid token without marking it invalid', async () => {
const user = await makeUser();
const { token } = await authService.createSessionToken(user);
const lookupError = Object.assign(new Error('db down'), {
code: 'dbBatchFailed',
});
const spy = vi
.spyOn(server.stores.user, 'getByUuid')
.mockRejectedValueOnce(lookupError);
try {
const probe = createAuthProbe({ authService });
const { req } = await runProbe(
probe,
makeReq({ headers: { authorization: `Bearer ${token}` } }),
);
expect(req.actor).toBeUndefined();
expect(req.tokenAuthFailed).toBeUndefined();
expect(req.tokenAuthError).toBe(lookupError);
} finally {
spy.mockRestore();
}
});
});
@@ -45,9 +45,9 @@ interface AuthProbeOptions {
* and valid — attaches an `Actor` to `req.actor`.
*
* Key property: this middleware **never rejects**. Missing tokens, malformed
* tokens, expired tokens, tokens pointing at deleted users — all result in
* `req.actor` being left undefined. Per-route gates decide whether absence is
* acceptable.
* tokens, expired tokens, tokens pointing at deleted users, and lookups that
* fail outright all result in `req.actor` being left undefined. Per-route gates
* decide whether absence is acceptable.
*
* Token lookup order:
*
@@ -153,8 +153,10 @@ export const createAuthProbe = (opts: AuthProbeOptions): RequestHandler => {
} else if (result.invalid) {
req.tokenAuthFailed = true;
}
} catch {
req.tokenAuthFailed = true;
} catch (err) {
// Not a verdict on the token: routes that require auth answer
// with this error, routes that don't serve the request anonymously.
req.tokenAuthError = err;
}
next();
};
@@ -288,6 +288,22 @@ describe('requireAuthGate', () => {
});
expectHttpError(got, 401, 'reauth_required');
});
it('passes on the error when the token could not be checked', () => {
const lookupError = Object.assign(new Error('down'), {
code: 'dbBatchFailed',
});
const got = runGate(requireAuthGate(), { tokenAuthError: lookupError });
expect(got).toBe(lookupError);
});
it('still answers token_auth_failed when a check found the token invalid', () => {
const got = runGate(requireAuthGate(), {
tokenAuthFailed: true,
tokenAuthError: new Error('down'),
});
expectHttpError(got, 401, 'token_auth_failed');
});
});
// ── requireUserActorGate ────────────────────────────────────────────
@@ -330,6 +346,14 @@ describe('requireUserActorGate', () => {
expectHttpError(got, 401, 'token_missing');
});
it('passes on the error when the token could not be checked', () => {
const lookupError = new Error('down');
const got = runGate(requireUserActorGate(), {
tokenAuthError: lookupError,
});
expect(got).toBe(lookupError);
});
it('rejects a FULL-ACCESS access token too — account routes stay closed', () => {
// The account wall is actor-type based: even a full-access PAT (which
// the resource wall lets through) is rejected here, so it can never
+4 -1
View File
@@ -50,7 +50,7 @@ import { assertVerifiedEmail } from '../verifiedEmail';
// Make sure the `Express.Request.actor` augmentation is in scope.
import '../expressAugmentation';
const rejectAuth = (req: Request): HttpError => {
const rejectAuth = (req: Request): unknown => {
if (req.requiresReauth) {
return new HttpError(401, 'Re-authentication required', {
legacyCode: 'reauth_required',
@@ -71,6 +71,9 @@ const rejectAuth = (req: Request): HttpError => {
legacyCode: 'token_auth_failed',
});
}
// The token couldn't be checked, so a 401 would wrongly tell the client
// to discard it; the error handler answers (503 for a database outage).
if (req.tokenAuthError !== undefined) return req.tokenAuthError;
return new HttpError(401, 'Missing authentication token', {
legacyCode: 'token_missing',
});
@@ -18,7 +18,7 @@
*/
import type { Request } from 'express';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { v4 as uuidv4 } from 'uuid';
import { makeActor } from '../../actor';
import {
@@ -1132,14 +1132,150 @@ describe('resolvePublicHostedIdentity', () => {
const reqOf = (init: {
cookies?: Record<string, string>;
actor?: unknown;
headers?: Record<string, string>;
query?: Record<string, string>;
}): Request =>
({
cookies: init.cookies ?? {},
actor: init.actor,
headers: {},
query: {},
headers: init.headers ?? {},
query: init.query ?? {},
}) as unknown as Request;
describe('with the launch token in the Referer', () => {
const host = 'launch.site.puter.localhost';
const cookieName = HOSTED_ASSET_COOKIES.public.name;
const launch = async () => {
const user = await makeUser();
const sub = `launch-${uuidv4().slice(0, 8)}`;
const app = await server.stores.app.create(
{ name: sub, title: sub, index_url: `http://${host}/` },
{ ownerUserId: user.id },
);
const token = await authService.getUserAppToken(
{ user } as unknown as Parameters<
typeof authService.getUserAppToken
>[0],
app.uid,
);
const actor = (await authService.authenticateFromToken(token))!;
const cookie = await authService.createHostedAssetToken('public', {
appUid: app.uid,
userUid: user.uuid,
sessionUuid: actor.session?.uid,
subdomain: 'launch',
host,
});
return { user, appUid: app.uid, token, cookie, actor };
};
const resolve = (
appUid: string,
init: Parameters<typeof reqOf>[0],
expectedHost = host,
) =>
resolvePublicHostedIdentity({
req: reqOf(init),
authService,
sessionCookieName: 'puter_auth_token',
expectedAppUid: appUid,
expectedSubdomain: 'launch',
expectedHost,
});
const refererFor = (token: string) =>
`http://${host}/?puter.auth.token=${encodeURIComponent(token)}`;
it('takes the cookie when the token names its user and session', async () => {
const { user, appUid, token, cookie } = await launch();
const authenticate = vi.spyOn(authService, 'authenticate');
try {
const out = await resolve(appUid, {
cookies: { [cookieName]: cookie },
headers: { referer: refererFor(token) },
});
expect(out).toMatchObject({
source: 'public-cookie',
userUid: user.uuid,
hasValidPublicCookie: true,
});
expect(authenticate).not.toHaveBeenCalled();
} finally {
authenticate.mockRestore();
}
});
it('authenticates a query token even when it names the cookie identity', async () => {
const { user, appUid, token, cookie } = await launch();
const out = await resolve(appUid, {
cookies: { [cookieName]: cookie },
query: { 'puter.auth.token': token },
});
expect(out.source).toBe('query');
expect(out.userUid).toBe(user.uuid);
expect(
(out as { hasValidPublicCookie?: boolean })
.hasValidPublicCookie,
).toBeUndefined();
});
it('authenticates the token when the cookie was minted for another host', async () => {
const { user, appUid, token, cookie } = await launch();
const out = await resolve(
appUid,
{
cookies: { [cookieName]: cookie },
headers: { referer: refererFor(token) },
},
'other.site.puter.localhost',
);
expect(out.source).toBe('referrer');
expect(out.userUid).toBe(user.uuid);
});
it('authenticates a token that names another app under the same session', async () => {
const { user, appUid, cookie, actor } = await launch();
const otherAppToken = server.services.token.sign('auth', {
type: 'app-under-user',
version: '2',
user_uid: user.uuid,
app_uid: `app-${uuidv4()}`,
session_uid: actor.session!.uid,
});
const authenticate = vi.spyOn(authService, 'authenticate');
try {
const out = await resolve(appUid, {
cookies: { [cookieName]: cookie },
headers: { referer: refererFor(otherAppToken) },
});
expect(authenticate).toHaveBeenCalledTimes(1);
expect(out.source).toBe('public-cookie');
} finally {
authenticate.mockRestore();
}
});
it('never resolves a scoped access token, with or without the cookie', async () => {
const { user, appUid, cookie } = await launch();
const scoped = await authService.createAccessToken(
makeActor({
user: { id: user.id, uuid: user.uuid, username: user.username },
}),
[[`user:${user.uuid}:email:read`]],
);
const withCookie = await resolve(appUid, {
cookies: { [cookieName]: cookie },
headers: { referer: refererFor(scoped) },
});
expect(withCookie.source).toBe('public-cookie');
const withoutCookie = await resolve(appUid, {
headers: { referer: refererFor(scoped) },
});
expect(withoutCookie.source).toBe('none');
});
});
it('returns the cookie identity when present and valid', async () => {
const user = await makeUser();
const appUid = `app-${uuidv4()}`;
@@ -86,6 +86,10 @@ export interface PrivateIdentity {
hasValidPrivateCookie?: boolean;
}
type PublicCookieClaims = Awaited<
ReturnType<AuthService['verifyHostedAssetToken']>
>;
interface SubdomainLike {
user_id?: number | null;
}
@@ -533,8 +537,63 @@ export async function resolvePublicHostedIdentity(opts: {
}
}
const { name: publicCookieNameV2, legacyName: publicCookieNameLegacy } =
HOSTED_ASSET_COOKIES.public;
const publicCookieToken =
(typeof cookies?.[publicCookieNameV2] === 'string'
? cookies[publicCookieNameV2]
: null) ??
(typeof cookies?.[publicCookieNameLegacy] === 'string'
? cookies[publicCookieNameLegacy]
: null);
let publicCookieClaims: Promise<PublicCookieClaims | null> | undefined;
const verifyPublicCookie = () =>
(publicCookieClaims ??= (async () => {
if (!publicCookieToken) return null;
try {
return await authService.verifyHostedAssetToken(
'public',
publicCookieToken,
{
appUid: expectedAppUid,
subdomain: expectedSubdomain,
host: expectedHost,
},
);
} catch {
// v1-signed cookies land here and get re-minted.
return null;
}
})());
const publicCookieIdentity = (claims: PublicCookieClaims) => ({
source: 'public-cookie' as const,
userUid: claims.userUid,
sessionUuid: claims.sessionUuid,
hasValidPublicCookie: true,
});
const bootstrap = getBootstrapToken(req);
if (bootstrap) {
// A launched app's own assets carry its launch token in the Referer.
// When that token names the cookie's user and session, the cookie
// already stands for it and nothing needs re-authenticating or minting.
if (
bootstrap.source === 'referrer' &&
publicCookieToken &&
expectedAppUid
) {
const named = authService.signedSessionClaims(bootstrap.token);
if (named && (!named.appUid || named.appUid === expectedAppUid)) {
const claims = await verifyPublicCookie();
if (
claims &&
claims.userUid === named.userUid &&
claims.sessionUuid === named.sessionUuid
) {
return publicCookieIdentity(claims);
}
}
}
try {
const actor = await authService.authenticateFromToken(
bootstrap.token,
@@ -554,36 +613,8 @@ export async function resolvePublicHostedIdentity(opts: {
}
}
const { name: publicCookieNameV2, legacyName: publicCookieNameLegacy } =
HOSTED_ASSET_COOKIES.public;
const publicCookieToken =
(typeof cookies?.[publicCookieNameV2] === 'string'
? cookies[publicCookieNameV2]
: null) ??
(typeof cookies?.[publicCookieNameLegacy] === 'string'
? cookies[publicCookieNameLegacy]
: null);
if (publicCookieToken) {
try {
const claims = await authService.verifyHostedAssetToken(
'public',
publicCookieToken,
{
appUid: expectedAppUid,
subdomain: expectedSubdomain,
host: expectedHost,
},
);
return {
source: 'public-cookie',
userUid: claims.userUid,
sessionUuid: claims.sessionUuid,
hasValidPublicCookie: true,
};
} catch {
/* fall through — v1-signed cookies land here and get re-minted */
}
}
const claims = await verifyPublicCookie();
if (claims) return publicCookieIdentity(claims);
return { source: 'none' };
}
@@ -2763,6 +2763,321 @@ describe('public hosted asset billing identity', () => {
});
});
describe('public hosted assets requested with the launch token in the Referer', () => {
const cookieName = HOSTED_ASSET_COOKIES.public.name;
const makeLaunchedApp = async () => {
const owner = await makeUserWithHome();
const home = (await server.stores.fsEntry.getEntryByPath(
`/${owner.username}`,
))!;
const sub = `ref-${uuidv4().slice(0, 8)}`;
const host = `${sub}.site.puter.localhost`;
await server.stores.subdomain.create({
userId: owner.id,
subdomain: sub,
rootDirId: home.id,
});
await writeFile(
owner.id,
`/${owner.username}/index.html`,
Buffer.from('<html></html>'),
);
await writeFile(
owner.id,
`/${owner.username}/app.css`,
Buffer.from('body{}'),
);
const app = await server.stores.app.create(
{ name: sub, title: sub, index_url: `http://${host}/` },
{ ownerUserId: owner.id },
);
return { owner, sub, host, appUid: app.uid };
};
const cookieFor = async (
token: string,
site: { sub: string; host: string; appUid: string },
) => {
const actor = (await server.services.auth.authenticateFromToken(
token,
))!;
return server.services.auth.createHostedAssetToken('public', {
appUid: site.appUid,
userUid: actor.user.uuid,
sessionUuid: actor.session?.uid,
subdomain: site.sub,
host: site.host,
});
};
const refererFor = (host: string, token: string) =>
`http://${host}/?puter.app_instance_id=x&puter.auth.token=${encodeURIComponent(token)}`;
const serve = async (
host: string,
init: {
path?: string;
cookies?: Record<string, string>;
headers?: Record<string, string>;
query?: Record<string, string>;
} = {},
) => {
const req = makeReq({ hostname: host, path: '/app.css', ...init });
const { res, out } = makeRes();
await buildMiddleware()(req, res, vi.fn());
await new Promise<void>((resolve) => setImmediate(resolve));
expect(out.statusCode).toBe(200);
return { req, out };
};
const claimsOf = (cookie: string, appUid: string, host: string) =>
server.services.auth.verifyHostedAssetToken('public', cookie, {
appUid,
host,
});
const REDIS_METHODS = [
'get',
'mget',
'exists',
'hget',
'hgetall',
'smembers',
'set',
'del',
'expire',
'incr',
'incrby',
'hset',
'sadd',
'pipeline',
'multi',
];
/** Redis calls, JWT signs and full authentications made by `fn`. */
const measure = async <T>(fn: () => Promise<T>) => {
const redis = server.clients.redis as unknown as Record<
string,
unknown
>;
const redisSpies = REDIS_METHODS.filter(
(m) => typeof redis[m] === 'function',
).map((m) => [m, vi.spyOn(redis as never, m as never)] as const);
const sign = vi.spyOn(server.services.token, 'sign');
const authenticate = vi.spyOn(server.services.auth, 'authenticate');
try {
const result = await fn();
const redisCalls: Record<string, number> = {};
for (const [m, spy] of redisSpies) {
const n = (spy as unknown as { mock: { calls: unknown[] } })
.mock.calls.length;
if (n) redisCalls[m] = n;
}
return {
result,
redisCalls,
signs: sign.mock.calls.length,
authentications: authenticate.mock.calls.length,
};
} finally {
for (const [, spy] of redisSpies) spy.mockRestore();
sign.mockRestore();
authenticate.mockRestore();
}
};
it('costs the same as the cookie alone when the token names the cookie user and session', async () => {
const site = await makeLaunchedApp();
const visitor = await makeUser();
const token = await server.services.auth.getUserAppToken(
actorFor(visitor),
site.appUid,
);
const cookies = { [cookieName]: await cookieFor(token, site) };
const headers = { referer: refererFor(site.host, token) };
// Warm the caches both paths read.
await serve(site.host, { cookies });
await serve(site.host, { cookies, headers });
const cookieOnly = await measure(() => serve(site.host, { cookies }));
const withReferer = await measure(() =>
serve(site.host, { cookies, headers }),
);
expect(withReferer.result.req.egressActor?.user?.uuid).toBe(
visitor.uuid,
);
expect(withReferer.result.out.cookies).toEqual({});
expect(withReferer.signs).toBe(0);
expect(withReferer.authentications).toBe(0);
expect(withReferer.redisCalls).toEqual(cookieOnly.redisCalls);
expect(cookieOnly.signs).toBe(0);
});
it('bills the token account when the launch could not replace an older cookie', async () => {
const site = await makeLaunchedApp();
const previous = await makeUser();
const current = await makeUser();
const previousToken = await server.services.auth.getUserAppToken(
actorFor(previous),
site.appUid,
);
const currentToken = await server.services.auth.getUserAppToken(
actorFor(current),
site.appUid,
);
const oldCookies = {
[cookieName]: await cookieFor(previousToken, site),
};
const mint = vi
.spyOn(server.services.auth, 'createHostedAssetToken')
.mockRejectedValueOnce(new Error('mint failed'));
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
let launch;
try {
launch = await serve(site.host, {
path: '/index.html',
cookies: oldCookies,
query: { 'puter.auth.token': currentToken },
});
} finally {
mint.mockRestore();
warn.mockRestore();
}
expect(launch.out.cookies).toEqual({});
expect(launch.req.egressActor?.user?.uuid).toBe(current.uuid);
const asset = await serve(site.host, {
cookies: oldCookies,
headers: { referer: refererFor(site.host, currentToken) },
});
expect(asset.req.egressActor?.user?.uuid).toBe(current.uuid);
const replaced = asset.out.cookies[cookieName];
expect(replaced).toBeTruthy();
expect((await claimsOf(replaced, site.appUid, site.host)).userUid).toBe(
current.uuid,
);
});
it('bills the token account when a cached page of another account loads assets', async () => {
// The document never reaches the server (served from an app's own
// cache), so only the assets show which account launched it.
const site = await makeLaunchedApp();
const previous = await makeUser();
const current = await makeUser();
const previousToken = await server.services.auth.getUserAppToken(
actorFor(previous),
site.appUid,
);
const currentToken = await server.services.auth.getUserAppToken(
actorFor(current),
site.appUid,
);
const oldCookies = {
[cookieName]: await cookieFor(previousToken, site),
};
for (const path of ['/app.css', '/index.html']) {
const asset = await serve(site.host, {
path,
cookies: oldCookies,
headers: { referer: refererFor(site.host, currentToken) },
});
expect(asset.req.egressActor?.user?.uuid).toBe(current.uuid);
const replaced = asset.out.cookies[cookieName];
expect(
(await claimsOf(replaced, site.appUid, site.host)).userUid,
).toBe(current.uuid);
}
});
it('re-mints the cookie when the token names the same user under another session', async () => {
const site = await makeLaunchedApp();
const visitor = await makeUser();
const appToken = await server.services.auth.getUserAppToken(
actorFor(visitor),
site.appUid,
);
const cookies = { [cookieName]: await cookieFor(appToken, site) };
const { session, token: sessionToken } =
await server.services.auth.createSessionToken(visitor as never);
const asset = await serve(site.host, {
cookies,
headers: { referer: refererFor(site.host, sessionToken) },
});
expect(asset.req.egressActor?.user?.uuid).toBe(visitor.uuid);
const replaced = asset.out.cookies[cookieName];
expect(replaced).toBeTruthy();
expect(
(await claimsOf(replaced, site.appUid, site.host)).sessionUuid,
).toBe(session.uuid);
});
it('falls back to the cookie when the Referer token does not verify', async () => {
const site = await makeLaunchedApp();
const visitor = await makeUser();
const token = await server.services.auth.getUserAppToken(
actorFor(visitor),
site.appUid,
);
const cookies = { [cookieName]: await cookieFor(token, site) };
const tampered = `${token.slice(0, -4)}AAAA`;
const asset = await serve(site.host, {
cookies,
headers: { referer: refererFor(site.host, tampered) },
});
expect(asset.req.egressActor?.user?.uuid).toBe(visitor.uuid);
expect(asset.out.cookies).toEqual({});
});
it('bills the site owner once the shared session is revoked', async () => {
const site = await makeLaunchedApp();
const visitor = await makeUser();
const token = await server.services.auth.getUserAppToken(
actorFor(visitor),
site.appUid,
);
const cookies = { [cookieName]: await cookieFor(token, site) };
await server.services.auth.revokeAllSessionsForUserId(visitor.id);
const asset = await serve(site.host, {
cookies,
headers: { referer: refererFor(site.host, token) },
});
expect(asset.req.egressActor?.user?.uuid).toBe(site.owner.uuid);
expect(asset.out.cookies).toEqual({});
});
it('keeps responses that set the cookie out of shared caches', async () => {
const site = await makeLaunchedApp();
const visitor = await makeUser();
const token = await server.services.auth.getUserAppToken(
actorFor(visitor),
site.appUid,
);
const launch = await serve(site.host, {
path: '/index.html',
query: { 'puter.auth.token': token },
});
const cookie = launch.out.cookies[cookieName];
expect(cookie).toBeTruthy();
expect(launch.out.headers['Cache-Control']).toBe('private');
const asset = await serve(site.host, {
cookies: { [cookieName]: cookie },
headers: { referer: refererFor(site.host, token) },
});
expect(asset.out.cookies).toEqual({});
expect(asset.out.headers['Cache-Control']).toBeUndefined();
});
});
describe('site rooted in the owner tree, root moved to Trash', () => {
it('stops serving a trashed folder and resumes when restored', async () => {
const owner = await makeUserWithHome();
@@ -548,6 +548,8 @@ export const createPuterSiteMiddleware = (
requestHostname: host,
}),
);
// A shared cache must not hand this visitor's cookie to others.
res.set('Cache-Control', 'private');
}
} catch (e) {
// Best-effort — don't block the public file serve.
+357 -1
View File
@@ -186,6 +186,96 @@ describe('AuthService (integration)', () => {
});
});
describe('signedSessionClaims', () => {
it('names the user and session of a session token', async () => {
const user = await makeUser();
const { token, session } = await authService.createSessionToken(
user,
{},
);
expect(authService.signedSessionClaims(token)).toEqual({
userUid: user.uuid,
sessionUuid: (session as { uuid: string }).uuid,
});
});
it('names the app too for an app token', async () => {
const user = await makeUser();
const appUid = `app-${uuidv4()}`;
const sessionUuid = uuidv4();
const token = server.services.token.sign('auth', {
type: 'app-under-user',
version: '2',
user_uid: user.uuid,
app_uid: appUid,
session_uid: sessionUuid,
});
expect(authService.signedSessionClaims(token)).toEqual({
userUid: user.uuid,
sessionUuid,
appUid,
});
});
it('reads the session from `uuid` on a token without `session_uid`', () => {
const [userUid, sessionUuid] = [uuidv4(), uuidv4()];
const token = server.services.token.sign('auth', {
type: 'gui',
version: '0.0.0',
uuid: sessionUuid,
user_uid: userUid,
});
expect(authService.signedSessionClaims(token)).toEqual({
userUid,
sessionUuid,
});
});
it('returns null for worker, access, expired, tampered and session-less tokens', async () => {
const user = await makeUser();
const accessToken = await authService.createAccessToken(
{
user: {
id: user.id,
uuid: user.uuid,
username: user.username,
},
} as Actor,
[[`user:${user.uuid}:email:read`]],
);
const sign = (claims: Record<string, unknown>, expiresIn?: number) =>
server.services.token.sign(
'auth',
claims,
expiresIn === undefined ? undefined : { expiresIn },
);
const sessionUuid = uuidv4();
const session = {
type: 'session',
version: '2',
uuid: sessionUuid,
session_uid: sessionUuid,
user_uid: user.uuid,
};
const valid = sign(session);
for (const token of [
accessToken,
sign({ ...session, worker: true, worker_name: 'w' }),
sign({
type: 'app-under-user',
version: '2',
user_uid: user.uuid,
app_uid: `app-${uuidv4()}`,
}),
sign(session, -120),
`${valid.slice(0, -4)}AAAA`,
'not-a-jwt',
]) {
expect(authService.signedSessionClaims(token)).toBeNull();
}
});
});
// ── Rich `authenticate()` result shape ──────────────────────────
describe('authenticate (reauth signal)', () => {
@@ -650,6 +740,60 @@ describe('AuthService (integration)', () => {
).toBeFalsy();
});
describe('listSessions and expiry', () => {
const nowS = () => Math.floor(Date.now() / 1000);
const listedUuids = async (user: { id: number }) =>
(await authService.listSessions({ user } as Actor)).map(
(r) => (r as { uuid: string }).uuid,
);
it.each(['web', 'app', 'access_token'])(
'leaves out an expired %s session and lists a live one',
async (kind) => {
const user = await makeUser();
const sessions = server.stores.session;
const live = await sessions.create(user.id, {
kind,
expires_at: nowS() + 3600,
});
const expired = await sessions.create(user.id, {
kind,
expires_at: nowS() - 1,
});
const uuids = await listedUuids(user);
expect(uuids).toContain(live.uuid);
expect(uuids).not.toContain(expired.uuid);
},
);
it('leaves out a token whose parent session has expired or is gone', async () => {
const user = await makeUser();
const sessions = server.stores.session;
const token = (parent: string) =>
sessions.create(user.id, {
kind: 'access_token',
parent_session_id: parent,
expires_at: nowS() + 3600,
});
const liveParent = await sessions.create(user.id);
const expiredParent = await sessions.create(user.id, {
expires_at: nowS() - 1,
});
const listed = await token(liveParent.uuid);
const underExpired = await token(expiredParent.uuid);
const underMissing = await token(uuidv4());
const uuids = await listedUuids(user);
expect(uuids).toContain(liveParent.uuid);
expect(uuids).toContain(listed.uuid);
expect(uuids).not.toContain(expiredParent.uuid);
expect(uuids).not.toContain(underExpired.uuid);
expect(uuids).not.toContain(underMissing.uuid);
});
});
it('listSessions excludes kind="asset" rows', async () => {
// Asset rows are per-cookie children of `web` rows, revoked
// transitively via the cascade — surfacing them in the
@@ -3099,7 +3243,7 @@ describe('AuthService (integration)', () => {
const emit = vi.spyOn(server.clients.event, 'emit');
const announced = () =>
emit.mock.calls.filter(
(c) => c[0] === 'auth.access-token.revoked',
(c) => c[0] === 'outer.auth.access-token.revoked',
).length;
const scoped = await authService.createAccessToken(actor, [
@@ -3117,6 +3261,35 @@ describe('AuthService (integration)', () => {
emit.mockRestore();
});
it('announces a desktop app token it replaces past its max age', async () => {
const user = await makeUser();
const { session } = await authService.createSessionToken(user);
const actor = makeActor({
user: { id: user.id, uuid: user.uuid, username: user.username },
session: { uid: String(session.uuid), kind: 'web' },
});
const app = { uid: `app-${uuidv4()}`, title: 'Retire probe' };
const { token } = await authService.getGodmodeAppToken(actor, app);
const { token_uid } = server.services.token.verify<{
token_uid: string;
}>('auth', token);
const emit = vi.spyOn(server.clients.event, 'emit');
const later = Date.now() + 8 * 24 * 60 * 60 * 1000;
vi.spyOn(Date, 'now').mockReturnValue(later);
try {
await authService.getGodmodeAppToken(actor, app);
expect(emit).toHaveBeenCalledWith(
'outer.auth.access-token.revoked',
{ token_uid },
{},
);
} finally {
vi.mocked(Date.now).mockRestore();
emit.mockRestore();
}
});
it('revokeAccessToken rejects with 404 when the token belongs to another user', async () => {
const u1 = await makeUser();
const u2 = await makeUser();
@@ -3725,6 +3898,163 @@ describe('AuthService (integration)', () => {
).rejects.toMatchObject({ statusCode: 404 });
expect(await authService.authenticateFromToken(jwt)).toBeTruthy();
});
const migratedTokenRow = async (userId: number) => {
const legacyUid = uuidv4();
const row = await server.stores.session.create(userId, {
kind: 'access_token',
legacy_token_uid: legacyUid,
created_via: 'legacy_backfill',
});
return { legacyUid, rowUuid: row.uuid as string };
};
it('soft-revokes a migrated token row named by its legacy token uid', async () => {
const user = await makeUser();
const actor = {
user: { id: user.id, uuid: user.uuid, username: user.username },
} as Actor;
const { legacyUid, rowUuid } = await migratedTokenRow(user.id);
await authService.revokeAccessToken(actor, legacyUid);
expect(await server.stores.session.getByUuid(rowUuid)).toBeNull();
});
it('404s for a raw uid that names no token row', async () => {
const user = await makeUser();
const actor = {
user: { id: user.id, uuid: user.uuid, username: user.username },
} as Actor;
await expect(
authService.revokeAccessToken(actor, uuidv4()),
).rejects.toMatchObject({ statusCode: 404 });
});
it("404s when another user names a migrated token's legacy uid", async () => {
const owner = await makeUser();
const other = await makeUser();
const otherActor = {
user: {
id: other.id,
uuid: other.uuid,
username: other.username,
},
} as Actor;
const { legacyUid, rowUuid } = await migratedTokenRow(owner.id);
await expect(
authService.revokeAccessToken(otherActor, legacyUid),
).rejects.toMatchObject({ statusCode: 404 });
expect(
await server.stores.session.getByUuid(rowUuid),
).toBeTruthy();
});
});
describe('tokens minted by a full-access token', () => {
const fullAccessToken = async () => {
const user = await makeUser();
const userActor = makeActor({
user: { id: user.id, uuid: user.uuid, username: user.username },
});
const jwt = await authService.createAccessToken(userActor, [
[FULL_API_ACCESS],
]);
const decoded = server.services.token.verify('auth', jwt) as {
token_uid: string;
session_uid: string;
auth_id: string;
};
return { user, userActor, jwt, decoded };
};
const parentOf = async (token: string) => {
const { session_uid } = server.services.token.verify(
'auth',
token,
) as { session_uid: string };
const rows = (await server.clients.db.read(
'SELECT `parent_session_id` FROM `sessions` WHERE `uuid` = ?',
[session_uid],
)) as Array<{ parent_session_id: string | null }>;
return rows[0]?.parent_session_id;
};
/** A replica that has not seen any access-token row yet. */
const lagTokenRows = () => {
const db = server.clients.db;
const original = db.read.bind(db);
const spy = vi
.spyOn(db, 'read')
.mockImplementation(async (sql: string, params?: unknown[]) =>
sql.includes("FROM `sessions` WHERE `kind` = 'access_token'")
? []
: original(sql, params),
);
return () => spy.mockRestore();
};
it('parents the child to the minting token row while the replica lags, and revoking it takes the child', async () => {
const { user, userActor, jwt, decoded } = await fullAccessToken();
const minter = await authService.authenticateFromToken(jwt);
const restore = lagTokenRows();
let child: string;
try {
child = await authService.createAccessToken(minter!, [
[`user:${user.uuid}:email:read`],
]);
} finally {
restore();
}
expect(await parentOf(child)).toBe(decoded.session_uid);
expect(await authService.authenticateFromToken(child)).toBeTruthy();
await authService.revokeAccessToken(userActor, jwt);
expect(await authService.authenticateFromToken(child)).toBeNull();
});
it('carries the row whether auth read it from the cache or the database', async () => {
const { jwt, decoded } = await fullAccessToken();
const key = `sessions:v2:uuid:${decoded.session_uid}`;
expect(await server.clients.redis.get(key)).toBeTruthy();
const cached = await authService.authenticateFromToken(jwt);
await server.clients.redis.del(key);
const fromDb = await authService.authenticateFromToken(jwt);
expect(cached?.accessToken?.sessionUid).toBe(decoded.session_uid);
expect(fromDb?.accessToken?.sessionUid).toBe(decoded.session_uid);
});
it('looks the row up by token uid when the claim names no row of its own', async () => {
const { user, decoded } = await fullAccessToken();
const otherSession = await authService.createSessionToken(user, {});
const claims = {
type: 'access-token',
version: '2',
token_uid: decoded.token_uid,
user_uid: user.uuid,
auth_id: decoded.auth_id,
full_access: true,
};
const unclaimed = server.services.token.sign('auth', claims);
const misclaimed = server.services.token.sign('auth', {
...claims,
session_uid: (otherSession.session as { uuid: string }).uuid,
});
for (const token of [unclaimed, misclaimed]) {
const minter = await authService.authenticateFromToken(token);
expect(minter?.accessToken?.sessionUid).toBeUndefined();
const child = await authService.createAccessToken(minter!, [
[`user:${user.uuid}:email:read`],
]);
expect(await parentOf(child)).toBe(decoded.session_uid);
}
});
});
describe('revokeSession on access-token rows', () => {
@@ -4025,6 +4355,32 @@ describe('AuthService (integration)', () => {
},
);
it.each(revokers)(
'%s revokes an expired session and its live children',
async (_name, revoke) => {
const user = await makeUser();
const sessions = server.stores.session;
const now = Math.floor(Date.now() / 1000);
const web = await sessions.create(user.id, {
expires_at: now - 1,
});
const child = await sessions.create(user.id, {
kind: 'access_token',
parent_session_id: web.uuid,
expires_at: now + 3600,
});
await revoke(user);
const rows = await server.clients.db.read(
'SELECT `uuid`, `revoked_at` FROM `sessions` WHERE `uuid` IN (?, ?)',
[web.uuid, child.uuid],
);
expect(rows).toHaveLength(2);
for (const row of rows) expect(row.revoked_at).not.toBeNull();
},
);
it('a password reset leaves workers and standalone access tokens; a forced sign-out takes them', async () => {
const user = await makeUser();
const sessions = server.stores.session;
@@ -216,6 +216,10 @@ const sequentialAuthenticate = async (
if (!app || !isGodmodeApp(app)) return { invalid: true };
godmodeApp = { uid: app.uid, id: app.id };
}
const ownRow =
session?.kind === 'access_token' &&
(session.access_token_uid === d.token_uid ||
session.legacy_token_uid === d.token_uid);
const actor = makeActor({
user: actorUser(user),
accessToken: {
@@ -224,6 +228,7 @@ const sequentialAuthenticate = async (
authorized: null,
fullAccess: !d.app_uid && d.full_access === true,
...(godmodeApp ? { godmodeApp } : {}),
...(ownRow ? { sessionUid: session!.uuid } : {}),
},
});
applyHandlerDepth(actor);
+114 -19
View File
@@ -106,6 +106,15 @@ const HOSTED_ASSET_LABELS = {
export type ReauthReason = 'session_revoked' | 'session_expired';
/** Worker claims a session/gui token can carry. */
interface SessionTypeTokenOptions {
worker?: boolean;
workerName?: string;
workerUid?: string;
workerSiteUid?: string;
workerSite?: string;
}
/**
* Request metadata for `authenticate`. `touch: false` checks the token without
* recording activity on its session, for re-checks no user made.
@@ -367,6 +376,22 @@ export class AuthService extends PuterService {
);
}
/**
* Digest of the claims `createGuiToken` signs for this session, which
* differ between two of its tokens only in `iat`.
*/
guiTokenDigest(user: UserRow, sessionUuid: string): string {
return this.services.token.claimsDigest(
'auth',
this.#sessionTypeClaims(
'gui',
user,
sessionUuid,
this.#authIdFor(user),
),
);
}
/** Sign a session token for an existing session (upgrade from GUI token). */
createSessionTokenForSession(user: UserRow, sessionUuid: string): string {
return this.#signSessionTypeToken(
@@ -386,14 +411,21 @@ export class AuthService extends PuterService {
user: UserRow,
sessionUuid: string,
authId: string,
opts: {
worker?: boolean;
workerName?: string;
workerUid?: string;
workerSiteUid?: string;
workerSite?: string;
} = {},
opts: SessionTypeTokenOptions = {},
): string {
return this.services.token.sign(
'auth',
this.#sessionTypeClaims(type, user, sessionUuid, authId, opts),
);
}
#sessionTypeClaims(
type: 'session' | 'gui',
user: UserRow,
sessionUuid: string,
authId: string,
opts: SessionTypeTokenOptions = {},
): Record<string, unknown> {
const claims: Record<string, unknown> = {
type,
version: '2',
@@ -410,7 +442,7 @@ export class AuthService extends PuterService {
if (opts.workerUid) claims.worker_uid = opts.workerUid;
if (opts.workerSiteUid) claims.workerSiteUid = opts.workerSiteUid;
if (opts.workerSite) claims.workerSite = opts.workerSite;
return this.services.token.sign('auth', claims);
return claims;
}
/**
@@ -743,9 +775,22 @@ export class AuthService extends PuterService {
const rows = (await this.stores.session.getByUserId(
actor.user.id,
)) as Array<Record<string, unknown>>;
)) as SessionRow[];
const visible = rows.filter((row) => row.kind !== 'asset');
// Listed while authentication still accepts it: not expired, and for
// a token minted under another session, that session live as well.
const live = new Map(
rows
.filter((row) => !this.#endedSession(row))
.map((row) => [row.uuid, row]),
);
const visible = [...live.values()].filter(
(row) =>
row.kind !== 'asset' &&
(row.kind !== 'access_token' ||
!row.parent_session_id ||
live.has(row.parent_session_id)),
);
const appUids = [
...new Set(
@@ -785,7 +830,7 @@ export class AuthService extends PuterService {
const enriched = visible.map((row) => {
const meta =
(typeof row.meta === 'string'
? JSON.parse(row.meta as string)
? JSON.parse(row.meta)
: row.meta) ?? {};
const isCurrent = actor.session?.uid === row.uuid;
const appUid = typeof row.app_uid === 'string' ? row.app_uid : null;
@@ -1889,7 +1934,7 @@ export class AuthService extends PuterService {
}
if (row.access_token_uid) {
this.clients.event?.emit(
'auth.access-token.revoked',
'outer.auth.access-token.revoked',
{ token_uid: row.access_token_uid },
{},
);
@@ -2051,6 +2096,43 @@ export class AuthService extends PuterService {
};
}
/**
* User, session and app a session, GUI or app token names, checked against
* its signature and expiry only: nothing is read from the stores, so this
* says nothing about whether the session or user is still live. Null for
* worker and access tokens, and for anything that doesn't verify.
*/
signedSessionClaims(
token: string,
): { userUid: string; sessionUuid: string; appUid?: string } | null {
let decoded: AnyTokenPayload;
try {
decoded = this.services.token.verify<AnyTokenPayload>(
'auth',
token,
);
} catch {
return null;
}
if (decoded.type === 'session' || decoded.type === 'gui') {
if (decoded.worker) return null;
const sessionUuid = decoded.session_uid ?? decoded.uuid;
if (!decoded.user_uid || !sessionUuid) return null;
return { userUid: decoded.user_uid, sessionUuid };
}
if (decoded.type === 'app-under-user') {
if (decoded.worker) return null;
if (!decoded.user_uid || !decoded.session_uid || !decoded.app_uid)
return null;
return {
userUid: decoded.user_uid,
sessionUuid: decoded.session_uid,
appUid: decoded.app_uid,
};
}
return null;
}
#verifyHostedAssetToken(
token: string,
expectedKind: 'private' | 'public',
@@ -2218,18 +2300,21 @@ export class AuthService extends PuterService {
let parent_session_id =
issuingApp && actor.session ? actor.session.uid : null;
if (mintingToken) {
const mintingRow =
await this.stores.session.findActiveByAccessTokenUid(
mintingToken.uid,
);
if (!mintingRow) {
const mintingRowUuid =
mintingToken.sessionUid ??
(
await this.stores.session.findActiveByAccessTokenUid(
mintingToken.uid,
)
)?.uuid;
if (!mintingRowUuid) {
throw new HttpError(
403,
'Access tokens may not create access tokens',
{ legacyCode: 'forbidden' },
);
}
parent_session_id = mintingRow.uuid;
parent_session_id = mintingRowUuid;
}
const tokenSession = await this.stores.session.create(
@@ -2511,7 +2596,7 @@ export class AuthService extends PuterService {
// Only a token the handshake admits has a socket to drop.
if (mayBeFullAccess) {
this.clients.event?.emit(
'auth.access-token.revoked',
'outer.auth.access-token.revoked',
{ token_uid: tokenUid },
{},
);
@@ -2796,6 +2881,15 @@ export class AuthService extends PuterService {
if (session) void this.#touchSession(session.uuid, user.id, ctx);
// The row `findActiveByAccessTokenUid` would return, already checked
// live above, so tokens this one mints can parent to it without a read.
const ownRow =
session?.kind === 'access_token' &&
(session.access_token_uid === decoded.token_uid ||
session.legacy_token_uid === decoded.token_uid)
? session
: null;
const actor = makeActor({
user: this.#actorUserFromRow(user),
accessToken: {
@@ -2808,6 +2902,7 @@ export class AuthService extends PuterService {
// claim on one is ignored here.
fullAccess: !decoded.app_uid && decoded.full_access === true,
...(godmodeApp ? { godmodeApp } : {}),
...(ownRow ? { sessionUid: ownRow.uuid } : {}),
},
});
this.#applyHandlerDepth(actor, decoded);
@@ -20,6 +20,7 @@
import { createHmac } from 'node:crypto';
import jwt from 'jsonwebtoken';
import { describe, expect, it } from 'vitest';
import { tokenClaimsDigest } from '../../../gui/src/helpers/guiToken.js';
import { isTokenForAnotherUser } from '../../../gui/src/helpers/tokenUser.js';
import { TokenService } from './TokenService.js';
@@ -403,3 +404,35 @@ describe('session token read by the desktop', () => {
expect(isTokenForAnotherUser(token, { uuid: otherUid })).toBe(true);
});
});
describe('TokenService.claimsDigest', () => {
const claims = {
type: 'gui',
version: '2',
uuid: '6f1e2d3c-0000-4000-8000-000000000001',
session_uid: '6f1e2d3c-0000-4000-8000-000000000001',
user_uid: '5d4adce0-a381-4982-9c02-6e2540026238',
auth_id: '5d4adce0-a381-4982-9c02-6e2540026238',
};
it('is what the desktop computes over a token signed with those claims', async () => {
const svc = createTokenService();
const digest = svc.claimsDigest('auth', claims);
expect(digest).toMatch(/^[0-9a-f]{32}$/);
expect(await tokenClaimsDigest(svc.sign('auth', claims))).toBe(digest);
});
it('differs for another session or token type', () => {
const svc = createTokenService();
const digest = svc.claimsDigest('auth', claims);
expect(
svc.claimsDigest('auth', {
...claims,
session_uid: 'b0b0b0b0-0000-4000-8000-000000000002',
}),
).not.toBe(digest);
expect(svc.claimsDigest('auth', { ...claims, type: 'session' })).not.toBe(
digest,
);
});
});
+19
View File
@@ -17,6 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createHash } from 'node:crypto';
import jwt, { type SignOptions } from 'jsonwebtoken';
import { PuterService } from '../types';
@@ -268,6 +269,24 @@ export class TokenService extends PuterService {
});
}
/**
* Digest of the claims `sign(scope, payload)` writes, minus `iat`: SHA-256
* over the claims as key-sorted `[key, value]` pairs in JSON, first 32 hex
* chars. The GUI computes the same over a stored token
* (`gui/src/helpers/guiToken.js`), so the two must stay in step.
*/
claimsDigest(scope: string, payload: Record<string, unknown>): string {
const claims = this.#compressPayload(COMPRESSION[scope], payload);
const pairs = Object.keys(claims)
.filter((key) => key !== 'iat')
.sort()
.map((key) => [key, claims[key]]);
return createHash('sha256')
.update(JSON.stringify(pairs))
.digest('hex')
.slice(0, 32);
}
/**
* Verify and decompress. Only v2 tokens (`kid: 'v2'`) verify; any other
* token — including the retired v1 format — is rejected as invalid, with no
+4
View File
@@ -126,8 +126,12 @@ export interface SessionRow {
expires_at?: number | null;
app_uid?: string | null;
legacy_token_uid?: string | null;
access_token_uid?: string | null;
created_via?: string | null;
auth_id?: string | null;
label?: string | null;
last_ip?: string | null;
last_user_agent?: string | null;
}
export {};
@@ -124,6 +124,21 @@ describe('resolveNode', () => {
expect(error.message).toContain('uuid=ghost');
});
it('treats a path-less row found by uid or id as missing', async () => {
const orphan = makeEntry({ path: null as unknown as string });
const store = makeStore({
getEntryByUuid: vi.fn(async () => orphan),
getEntryById: vi.fn(async () => orphan),
});
await expect(resolveNode(store, { uid: 'uuid-7' })).resolves.toBeNull();
await expectHttpError(
() => resolveNode(store, { id: 7 }, { required: true }),
404,
'subject_does_not_exist',
);
});
it('falls back to id lookup when uid is blank', async () => {
const entry = makeEntry();
const store = makeStore({ getEntryById: vi.fn(async () => entry) });
+4 -2
View File
@@ -62,10 +62,12 @@ export async function resolveNode(
): Promise<FSEntry | null> {
if (ref.entry) return ref.entry;
// A uid/id lookup can return a legacy row with no path when its parent
// chain is broken. Nothing can authorize or address it, so it's a miss.
const uuid = ref.uid ?? ref.uuid;
if (isNonEmptyString(uuid)) {
const entry = await fsEntryStore.getEntryByUuid(uuid);
if (entry) return entry;
if (entry?.path) return entry;
return notFoundOrNull(
options.required,
`Entry not found: uuid=${uuid}`,
@@ -80,7 +82,7 @@ export async function resolveNode(
});
}
const entry = await fsEntryStore.getEntryById(numericId);
if (entry) return entry;
if (entry?.path) return entry;
return notFoundOrNull(
options.required,
`Entry not found: id=${numericId}`,
@@ -137,7 +137,6 @@ const render = async (
service: PuterHomepageService,
req: Request = makeReq(),
meta: Record<string, unknown> = { title: 'Puter' },
launchOptions: Record<string, unknown> = {},
actor: unknown = null,
): Promise<string> => {
let sent = '';
@@ -149,7 +148,6 @@ const render = async (
await service.send(
{ req, res, actor } as never,
meta as never,
launchOptions as never,
);
return sent;
};
@@ -292,7 +290,6 @@ describe('PuterHomepageService — gui() parameters', () => {
asset_dir: '/dist',
title: 'Editor',
app: { name: 'editor' },
launch_options: {},
});
// No `config.origin`: fall back to the request's protocol + domain.
expect(params.app_origin).toBe('http://puter.test');
@@ -338,7 +335,7 @@ describe('PuterHomepageService — gui() parameters', () => {
const staff = { user: { id: 7, email: '[email protected]' } };
expect(
guiParamsOf(await render(service, makeReq(), undefined, {}, staff))
guiParamsOf(await render(service, makeReq(), undefined, staff))
.teams_ui,
).toBe(true);
expect(teamsAvailableTo).toHaveBeenCalledWith(7, '[email protected]');
@@ -349,7 +346,7 @@ describe('PuterHomepageService — gui() parameters', () => {
teamsAvailableTo.mockResolvedValueOnce(false);
expect(
guiParamsOf(
await render(service, makeReq(), undefined, {}, {
await render(service, makeReq(), undefined, {
user: { id: 9, email: '[email protected]' },
}),
).teams_ui,
@@ -420,22 +417,6 @@ describe('PuterHomepageService — gui() parameters', () => {
expect(html).toContain('\\u003c/script>');
expect(guiParamsOf(html).injected).toBe('</script><img src=x>');
});
it('passes launch options straight through', async () => {
const params = guiParamsOf(
await render(
makeService(),
makeReq(),
{ title: 'Puter' },
{
on_initialized: [{ do: 'thing' }],
},
),
);
expect(params.launch_options).toEqual({
on_initialized: [{ do: 'thing' }],
});
});
});
describe('PuterHomepageService — extension hooks', () => {
@@ -44,10 +44,6 @@ export interface PageMeta {
app?: { name?: string; [k: string]: unknown } | null;
}
export interface LaunchOptions {
on_initialized?: Array<Record<string, unknown>>;
}
/**
* A GUI popup a first-party page frames at `/embed/<action>`. `hostOrigin` is
* that page, read from the referrer and pinned with frame-ancestors; null when
@@ -57,6 +53,17 @@ export interface PopupFrame {
hostOrigin: string | null;
}
export interface ShellContext {
req: Request;
res: Response;
actor?: Actor | null;
/**
* `AuthService.guiTokenDigest` for the request's session cookie, or null
* when it carries none. Omitted when the caller doesn't work it out.
*/
guiTokenDigest?: string | null;
}
interface PuterGuiAddonsEvent {
req: Request;
path: string;
@@ -309,12 +316,11 @@ export class PuterHomepageService extends PuterService {
* called on the happy path.
*/
async send(
ctx: { req: Request; res: Response; actor?: Actor | null },
ctx: ShellContext,
meta: PageMeta,
launchOptions: LaunchOptions = {},
popupFrame?: PopupFrame,
): Promise<void> {
const { req, res, actor } = ctx;
const { req, res, actor, guiTokenDigest } = ctx;
// Easter egg: puter-in-puter detection → render error page instead.
if (
@@ -334,9 +340,8 @@ export class PuterHomepageService extends PuterService {
}
const html = await this.#renderShell(
{ req, actor: actor ?? null },
{ req, actor: actor ?? null, guiTokenDigest },
meta,
launchOptions,
popupFrame,
);
res.send(html);
@@ -345,12 +350,13 @@ export class PuterHomepageService extends PuterService {
// -- Internals ----------------------------------------------------
async #renderShell(
ctx: { req: Request; actor: Actor | null },
ctx: Pick<ShellContext, 'req' | 'guiTokenDigest'> & {
actor: Actor | null;
},
meta: PageMeta,
launchOptions: LaunchOptions,
popupFrame?: PopupFrame,
): Promise<string> {
const { req, actor } = ctx;
const { req, actor, guiTokenDigest } = ctx;
const env = this.config.env ?? 'prod';
const bundled = env !== 'dev' || this.config.use_bundled_gui === true;
const assetDir = env === 'dev' ? '/src' : '/dist';
@@ -393,10 +399,13 @@ export class PuterHomepageService extends PuterService {
// instead of the socket wire.
eventsNotifications: notificationsFoldInEnabled(this.config),
...meta,
launch_options: launchOptions,
// After `meta`, so nothing page-specific can name the opener.
...(popupFrame ? { embed_host_origin: popupFrame.hostOrigin } : {}),
};
// Only ever this request's; without one the GUI asks for its token as
// it always has.
if (guiTokenDigest === undefined) delete guiParams.guiTokenDigest;
else guiParams.guiTokenDigest = guiTokenDigest;
const event: PuterGuiAddonsEvent = {
req,
@@ -4579,6 +4579,209 @@ describe('MeteringService', () => {
});
});
describe('settling when a balance read fails', () => {
const monthKey = (a: Actor) =>
`${METRICS_V2_PREFIX}:actor:${a.user!.uuid}:${currentMonthString()}`;
/** Rejects the next `times` reads `match` picks; the rest go through. */
const failReads = (
match: (args: {
key: unknown;
consistentRead?: boolean;
}) => boolean,
times = Infinity,
) => {
const kv = server.stores.kv;
const realGet = kv.get.bind(kv);
let left = times;
return vi
.spyOn(kv, 'get')
.mockImplementation(
async (...args: Parameters<typeof realGet>) => {
if (left > 0 && match(args[0] as never)) {
left--;
throw new Error(
'ProvisionedThroughputExceededException',
);
}
return realGet(...args);
},
);
};
const isAddonsRead = ({ key }: { key: unknown }) =>
typeof key === 'string' && key.endsWith(':addons');
const pools = async (a: Actor) => {
await server.stores.meteringBuffer.flushCycle();
const { usage } = await target.getActorCurrentMonthUsageDetails(a);
const addons = await target.getActorAddons(a, {
consistentRead: true,
});
return {
total: usage.total,
allowanceUsed: usage.allowanceUsed ?? 0,
consumed: addons.consumedPurchaseCredits ?? 0,
};
};
it('charges the allowance when the purchased-credit read fails', async () => {
await target.updateAddonCredit(actor.user.uuid!, 1_000_000);
await target.incrementUsage(actor, 'ai:chat', 1, 1000);
const before = await target.getAllowedUsage(actor);
const get = failReads(isAddonsRead);
const result = await target.incrementUsage(
actor,
'ai:chat',
1,
5000,
);
get.mockRestore();
expect(result.total).toBe(6000);
expect(await pools(actor)).toEqual({
total: 6000,
allowanceUsed: 6000,
consumed: 0,
});
const after = await target.getAllowedUsage(actor);
expect(before.remaining - after.remaining).toBe(5000);
});
it('charges only the allowance share past the allowance, and nothing later charges the rest', async () => {
const { monthUsageAllowance: allowance } =
await target.getActorSubscription(actor);
await target.updateAddonCredit(actor.user.uuid!, 1_000_000);
await target.incrementUsage(actor, 'ai:chat', 1, allowance - 100);
expect(await target.hasAnyUsageCached(actor)).toBe(true);
const alarm = vi.spyOn(server.clients.alarm, 'create');
const emit = vi.spyOn(server.clients.event, 'emit');
const get = failReads(isAddonsRead);
await target.incrementUsage(actor, 'ai:chat', 1, 1000);
get.mockRestore();
// 100 fits the allowance; the 900 credit would cover isn't drawn.
expect(await pools(actor)).toEqual({
total: allowance + 900,
allowanceUsed: allowance,
consumed: 0,
});
expect(alarm).toHaveBeenCalledWith(
'metering_settle_read_failed',
expect.any(String),
expect.objectContaining({
userId: actor.user.uuid,
unchargedCost: 900,
}),
'info',
);
expect(
alarm.mock.calls.some(([id]) =>
String(id).startsWith('metering service error'),
),
).toBe(false);
// The unread credit isn't taken as spent.
expect(
emit.mock.calls.some(
([name]) => name === 'metering.credit-state',
),
).toBe(false);
expect(await target.hasAnyUsageCached(actor)).toBe(true);
alarm.mockRestore();
emit.mockRestore();
// The next settle charges its own cost once, and only that.
await target.incrementUsage(actor, 'ai:chat', 1, 700);
expect(await pools(actor)).toEqual({
total: allowance + 1600,
allowanceUsed: allowance,
consumed: 700,
});
});
it('charges the allowance from the buffered total when the exact read fails', async () => {
const Service = target.constructor as typeof MeteringService;
const interval = Service.EXACT_READ_MIN_INTERVAL_MS;
Service.EXACT_READ_MIN_INTERVAL_MS = 0;
try {
const { monthUsageAllowance: allowance } =
await target.getActorSubscription(actor);
await target.incrementUsage(
actor,
'ai:chat',
1,
allowance - 3000,
);
await server.stores.meteringBuffer.flushCycle();
const key = monthKey(actor);
const alarm = vi.spyOn(server.clients.alarm, 'create');
const get = failReads(
(args) => args.key === key && !!args.consistentRead,
);
const result = await target.incrementUsage(
actor,
'ai:chat',
1,
1000,
);
const failedReads = get.mock.calls.length;
get.mockRestore();
expect(failedReads).toBeGreaterThan(0);
expect(result.total).toBe(allowance - 2000);
expect(await pools(actor)).toEqual({
total: allowance - 2000,
allowanceUsed: allowance - 2000,
consumed: 0,
});
expect(alarm).toHaveBeenCalledWith(
'metering_settle_read_failed',
expect.any(String),
expect.objectContaining({ unchargedCost: 0 }),
'info',
);
alarm.mockRestore();
} finally {
Service.EXACT_READ_MIN_INTERVAL_MS = interval;
}
});
it('charges each of two racing calls once when one of their reads fails', async () => {
await target.updateAddonCredit(actor.user.uuid!, 1_000_000);
await target.incrementUsage(actor, 'ai:chat', 1, 1000);
const get = failReads(isAddonsRead, 1);
await Promise.all([
target.incrementUsage(actor, 'ai:chat', 1, 2000),
target.incrementUsage(actor, 'ai:chat', 1, 3000),
]);
get.mockRestore();
expect(await pools(actor)).toEqual({
total: 6000,
allowanceUsed: 6000,
consumed: 0,
});
});
it('charges a failed call and the calls after it exactly once each', async () => {
await target.updateAddonCredit(actor.user.uuid!, 1_000_000);
const costs = [1000, 2000, 3000, 4000];
for (const [i, cost] of costs.entries()) {
const get = failReads(isAddonsRead, i % 2 === 0 ? 1 : 0);
await target.incrementUsage(actor, 'ai:chat', 1, cost);
get.mockRestore();
}
expect(await pools(actor)).toEqual({
total: 10_000,
allowanceUsed: 10_000,
consumed: 0,
});
});
});
// ── Resolver registration ────────────────────────────────────────
describe('resolver registration', () => {
@@ -342,6 +342,9 @@ export class MeteringService extends PuterService {
/** Bumped on every drop, so a read that straddles one isn't cached. */
#spentAddonsDrops = 0;
/** Running sum reported by `#alarmSettleReadFailed`. */
#unchargedSinceStart = 0;
/**
* Uuid → until when a near-allowance read bypasses the exact-read throttle.
* Set on a credits change (a purchase, an admin correction): for a short
@@ -675,49 +678,84 @@ export class MeteringService extends PuterService {
appCallCount: usages.length,
});
// The usage is already being recorded, so a failed balance read
// must not skip settling it.
let settleReadError: Error | null = null;
const [usageResult, subscription, actorAddons] = await Promise.all([
usageResultPromise,
this.#actorSubscriptionWithStatus(actor),
this.#addonsForSettle(actor),
(async () => {
try {
return await this.#addonsForSettle(actor);
} catch (e) {
settleReadError = e as Error;
return null;
}
})(),
]);
const { policy: actorSubscription, provisionalUntil } =
subscription;
const actorUsages = await this.exactUsageNearAllowance(
userId,
actorUsageKey,
usageResult,
actorSubscription.monthUsageAllowance,
);
let actorUsages: UsageByType;
try {
actorUsages = await this.exactUsageNearAllowance(
userId,
actorUsageKey,
usageResult,
actorSubscription.monthUsageAllowance,
);
} catch (e) {
settleReadError ??= e as Error;
actorUsages = usageResult.res as unknown as UsageByType;
}
// After a failed read only the allowance share is charged:
// purchased credit is never drawn against an unread balance.
const readAddons = settleReadError ? null : actorAddons;
const settledAllowanceUsed = await this.settleIncrementCharges(
userId,
actorUsageKey,
actorUsages,
actorSubscription,
actorAddons,
readAddons ?? ({} as UsageAddons),
totalBatchCost,
);
// Before any hold this usage stands for is released.
await this.stores.creditHold.bump(userId);
this.maybeAlertOveruse({
actor,
userId,
actorUsages,
actorSubscription,
actorAddons,
incrementCost: totalBatchCost,
batchUsages: usages,
});
if (!readAddons) {
const usedBefore = MeteringService.allowanceUsedBefore(
actorUsages,
actorSubscription.monthUsageAllowance,
totalBatchCost,
);
this.#alarmSettleReadFailed(
actor,
settleReadError,
Math.max(
0,
totalBatchCost - (settledAllowanceUsed - usedBefore),
),
);
} else {
this.maybeAlertOveruse({
actor,
userId,
actorUsages,
actorSubscription,
actorAddons,
incrementCost: totalBatchCost,
batchUsages: usages,
});
this.rememberRemainingCredits(
userId,
settledAllowanceUsed,
actorSubscription,
actorAddons,
provisionalUntil,
);
this.rememberRemainingCredits(
userId,
settledAllowanceUsed,
actorSubscription,
actorAddons,
provisionalUntil,
);
}
const own = this.#withDetail(actorUsages, usageResult.detail);
const charged = await this.applyMonthlyCharges(
@@ -2957,6 +2995,31 @@ export class MeteringService extends PuterService {
return usedBefore + allowanceCharge;
}
/**
* One alarm id for every actor, so a store brownout is a single alarm with
* a count. `unchargedCost` is what credit would have covered, had any been
* left; nothing charges it later.
*/
#alarmSettleReadFailed(
actor: Actor,
error: Error | null,
unchargedCost: number,
): void {
this.#unchargedSinceStart += unchargedCost;
this.clients.alarm.create(
'metering_settle_read_failed',
'Metering settled usage to the allowance only: a balance read failed',
{
userId: actor.user?.uuid,
appId: actor.effectiveApp?.uid,
unchargedCost,
unchargedSinceStart: this.#unchargedSinceStart,
error: error ?? undefined,
},
'info',
);
}
private maybeAlertOveruse(ctx: {
actor: Actor;
userId: string;
@@ -55,10 +55,7 @@ import type { IConfig } from '../../types.js';
*/
export type NotifWire =
| 'notif.message'
| 'notif.unreads'
| 'notif.ack'
| 'notif.removed';
'notif.message' | 'notif.unreads' | 'notif.ack' | 'notif.removed';
export const NOTIF_DELIVERY_EVENT = 'outer.notif.delivery';
@@ -200,7 +197,7 @@ export class NotificationSocketAdapter {
});
}
/** One notification, in the shape `UIDesktop` has always received. */
/** One notification, in the shape the GUI's socket listeners receive. */
message(userId: number, uid: string, notification: unknown): void {
const response = { uid, notification };
if (this.#dispatched(userId, 'notif.message', response)) return;
@@ -17,6 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import MockRedis from 'ioredis-mock';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { v4 as uuidv4 } from 'uuid';
import { makeActor, type Actor } from '../../core/actor.js';
@@ -27,6 +28,16 @@ import { generateDefaultFsentries } from '../../util/userProvisioning.js';
import { kv } from '../../util/kvSingleton.js';
import { PermissionService } from './PermissionService.js';
// The servers here share one redis mock; start each on an empty one.
const setupFreshServer = async (
...args: Parameters<typeof setupTestServer>
): Promise<PuterServer> => {
const redis = new MockRedis();
await redis.flushall();
redis.disconnect();
return setupTestServer(...args);
};
/** `default_temp_group` from config.default.json. */
const DEFAULT_TEMP_GROUP_UID = 'b7220104-7905-4985-b996-649fdcdb3c8f';
@@ -190,7 +201,7 @@ describe('PermissionService (integration)', () => {
let permService: PermissionService;
beforeAll(async () => {
server = await setupTestServer();
server = await setupFreshServer();
permService = server.services
.permission as unknown as PermissionService;
});
@@ -1641,7 +1652,7 @@ describe('PermissionService — scan paths', () => {
let permService: PermissionService;
beforeAll(async () => {
server = await setupTestServer();
server = await setupFreshServer();
permService = server.services
.permission as unknown as PermissionService;
}, 60_000);
@@ -1898,6 +1909,77 @@ describe('PermissionService — scan paths', () => {
expect(await permService.check(originActor, permission)).toBe(true);
expect(await permService.check(sharerActor, permission)).toBe(true);
}, 20_000);
it('does not read a revoked group grant back from a lagging replica', async () => {
const { row: issuer } = await makeGroupedUser();
const { row: member, actor: memberActor } = await makeGroupedUser();
const groupUid = uuidv4();
await server.clients.db.write(
'INSERT INTO `group` (`uid`, `owner_user_id`, `extra`, `metadata`) ' +
'VALUES (?, ?, ?, ?)',
[groupUid, issuer.id, '{}', '{}'],
);
const [group] = await server.clients.db.read(
'SELECT `id` FROM `group` WHERE `uid` = ?',
[groupUid],
);
await server.stores.group.addUsers(groupUid, [member.username]);
const permission = `zztest:lag-${uuidv4()}:ii:read`;
await server.stores.permission.setFlatUserPerm(
issuer.id,
permission,
{
permission,
deleted: false,
issuer_user_id: issuer.id,
} as never,
);
await server.clients.db.write(
'INSERT INTO `user_to_group_permissions` ' +
'(`user_id`, `group_id`, `permission`, `extra`) VALUES (?, ?, ?, ?)',
[issuer.id, group.id, permission, '{}'],
);
expect(await permService.check(memberActor, permission)).toBe(true);
await server.stores.permission.deleteUserGroupPerm(
Number(group.id),
issuer.id,
permission,
);
await permService.bumpPermissionCacheForUsernames([
member.username,
]);
// The replica still returns the row; the primary has deleted it.
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi
.spyOn(db, 'pread')
.mockImplementation((sql, params) => primaryRead(sql, params));
const read = vi
.spyOn(db, 'read')
.mockImplementation(async (sql, params) =>
String(sql).includes('user_to_group_permissions')
? [
{
permission,
user_id: issuer.id,
group_id: group.id,
extra: '{}',
},
]
: primaryRead(sql, params),
);
try {
expect(await permService.check(memberActor, permission)).toBe(
false,
);
} finally {
read.mockRestore();
pread.mockRestore();
}
});
});
describe('app-under-user grants', () => {
@@ -2606,7 +2688,7 @@ describe('PermissionService — default user permissions vs. group config', () =
// Self-hosted deployments may run without default groups. The floor
// is not group-derived, so it applies regardless — a deployment that
// clears both no longer has every driver call fail closed.
const bare = await setupTestServer({
const bare = await setupFreshServer({
default_user_group: '',
default_temp_group: '',
} as never);
@@ -1155,9 +1155,13 @@ export class PermissionService extends PuterService {
}
/** Batched: one event for the whole group, not one per member. */
async #bumpGroupCacheGeneration(groupId: number): Promise<void> {
async #bumpGroupCacheGeneration(
groupId: number,
memberUuids?: string[],
): Promise<void> {
const uuids =
await this.stores.permission.listGroupMemberUuids(groupId);
memberUuids ??
(await this.stores.permission.listGroupMemberUuids(groupId));
if (uuids.length === 0) return;
await this.stores.permission.bumpCacheGenerations(
uuids.map((uuid) => `user:${uuid}`),
@@ -1238,11 +1242,12 @@ export class PermissionService extends PuterService {
await this.#assertCanManage(actor, permission);
const revoked = await this.stores.permission.deleteUserGroupPerm(
groupId,
issuerId,
permission,
);
const { removed: revoked, members } =
await this.stores.permission.deleteUserGroupPerm(
groupId,
issuerId,
permission,
);
this.#audit(
this.stores.permission.auditUserGroupPerm({
@@ -1257,15 +1262,18 @@ export class PermissionService extends PuterService {
);
// Bumped even when nothing matched: a cached allow must not survive.
await this.#bumpGroupCacheGeneration(groupId);
await this.#bumpGroupCacheGeneration(
groupId,
members
.map((member) => member.uuid)
.filter((uuid): uuid is string => Boolean(uuid)),
);
// Nothing but the membership names the holders, so without this their
// watches outlive the revoke.
if (revoked) {
for (const memberId of await this.stores.permission.listGroupMemberIds(
groupId,
)) {
this.#announceRevoked(memberId, null, permission);
for (const member of members) {
this.#announceRevoked(member.id, null, permission);
}
}
return revoked;
@@ -2354,6 +2354,35 @@ describe('OpenAIRealtimeRelayService relay', () => {
b.ws.close();
});
it('evicts an access token revoked on another node', async () => {
const row = await server.stores.user.getByUsername(user.username);
const actor = makeActor({ user: row! });
const token = await server.services.auth.createAccessToken(actor, [
[FULL_API_ACCESS],
]);
const { token_uid } = server.services.token.verify<{
token_uid: string;
}>('auth', token);
const c = open(`${relayUrl}?auth_token=${token}`);
await c.waitFor('session.created');
// As a peer cluster delivers it, after a malformed payload it ignores.
server.clients.event.emit(
'outer.auth.access-token.revoked',
{ token_uid: 42 } as never,
{ from_outside: true },
);
server.clients.event.emit(
'outer.auth.access-token.revoked',
{ token_uid },
{ from_outside: true },
);
expect(await c.waitFor('error')).toMatchObject({
error: { code: 'invalid_api_key' },
});
await c.closed;
});
it('closes with a retryable error after a sustained verification outage', async () => {
const c = open(`${relayUrl}?auth_token=${user.token}`);
await c.waitFor('session.created');
@@ -838,13 +838,19 @@ export class OpenAIRealtimeRelayService extends PuterService {
{},
);
});
this.clients.event.on('auth.access-token.revoked', (_key, data) => {
this.clients.event.emit(
'pubsub.realtime.auth-revoked',
{ tokenUid: data.token_uid },
{},
);
});
this.clients.event.on(
'outer.auth.access-token.revoked',
(_key, data) => {
const tokenUid = (data as { token_uid?: unknown } | null)
?.token_uid;
if (typeof tokenUid !== 'string' || !tokenUid) return;
this.clients.event.emit(
'pubsub.realtime.auth-revoked',
{ tokenUid },
{},
);
},
);
// Raw WebSockets do not participate in socket.io's cluster adapter.
this.clients.event.on('pubsub.realtime.auth-revoked', (_key, data) => {
const revoked = data.sessionUids
@@ -1270,9 +1270,13 @@ describe('ShareService', () => {
expect(listByFsentry).not.toHaveBeenCalled();
expect(getEntriesByIds).not.toHaveBeenCalled();
const prefixes = [`fs:${file.uuid}`, `manage:fs:${file.uuid}`];
expect(revokeUserGrants).toHaveBeenCalledWith(prefixes);
expect(revokeGroupGrants).toHaveBeenCalledWith(prefixes);
expect(deleteRows).toHaveBeenCalledWith([file.id]);
expect(revokeUserGrants).toHaveBeenCalledWith(prefixes, {
primary: true,
});
expect(revokeGroupGrants).toHaveBeenCalledWith(prefixes, {
primary: true,
});
expect(deleteRows).toHaveBeenCalledWith([file.id], [file.uuid]);
// Grants go before the rows that record them.
expect(
revokeUserGrants.mock.invocationCallOrder[0]!,
@@ -19,7 +19,7 @@
import { dirname as pathDirname } from 'node:path/posix';
import { v4 as uuidv4 } from 'uuid';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import type { Actor } from '../../core/actor.js';
import { runWithContext } from '../../core/context.js';
import { PuterServer } from '../../server.js';
@@ -240,6 +240,161 @@ describe('ShareService: deleting a shared item', () => {
);
});
it('reads no grants or shares from the primary for an owner with nothing shared', async () => {
const owner = await makeUser();
const { dir } = await makeDirWithFile(owner.user);
const trash = await dirAt(`/${owner.user.username}/Trash`);
const pread = vi.spyOn(server.clients.db, 'pread');
try {
await move(owner, dir, trash);
const retireReads = pread.mock.calls
.map(([sql]) => String(sql))
.filter((sql) =>
/`user_to_user_permissions`|`user_to_group_permissions`|FROM `share`/u.test(
sql,
),
);
expect(retireReads).toEqual([]);
} finally {
pread.mockRestore();
}
});
it('withdraws a share made just now that the replica has not seen', async () => {
const owner = await makeUser();
const recipient = await makeUser();
const { dir, file } = await makeDirWithFile(owner.user);
await share(owner.actor, {
uid: dir.uuid,
recipient: { username: recipient.user.username },
mode: 'read',
});
expect(await canRead(recipient.actor, file.path)).toBe(true);
const trash = await dirAt(`/${owner.user.username}/Trash`);
// The replica has neither the grant nor the share row yet.
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi.spyOn(db, 'pread').mockImplementation(primaryRead);
const read = vi
.spyOn(db, 'read')
.mockImplementation(async (sql, params) =>
/`user_to_user_permissions`|FROM `share`/u.test(String(sql))
? []
: primaryRead(sql, params),
);
let moved;
try {
moved = await move(owner, dir, trash);
} finally {
read.mockRestore();
pread.mockRestore();
}
expect(
await canRead(recipient.actor, `${moved.path}/${file.name}`),
).toBe(false);
expect(
await server.stores.share.listAllByFsentrySubtree(dir.id),
).toEqual([]);
});
it("does not honour a lagging replica's copy of a link the delete removed", async () => {
const owner = await makeUser();
const stranger = await makeUser();
const { dir, file } = await makeDirWithFile(owner.user);
// The owner's plan covers link sharing.
const plan = vi
.spyOn(server.services.metering, 'getActorSubscription')
.mockResolvedValue({ id: 'business' } as never);
await server.stores.share.upsertAnyone({
issuerUserId: owner.user.id,
fsentryId: dir.id,
mode: 'read',
});
expect(await canRead(stranger.actor, file.path)).toBe(true);
const trash = await dirAt(`/${owner.user.username}/Trash`);
const moved = await move(owner, dir, trash);
// The replica still has the link row the primary just deleted.
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi.spyOn(db, 'pread').mockImplementation(primaryRead);
const read = vi
.spyOn(db, 'read')
.mockImplementation(async (sql, params) =>
String(sql).includes('`share`.`anyone` = 1')
? [
{
mode: 'read',
entry_uuid: dir.uuid,
owner_user_id: owner.user.id,
},
]
: primaryRead(sql, params),
);
try {
expect(
await canRead(stranger.actor, `${moved.path}/${file.name}`),
).toBe(false);
} finally {
read.mockRestore();
pread.mockRestore();
plan.mockRestore();
}
});
it("drops a team member's cached access when the replica lacks them", async () => {
const owner = await makeUser();
const member = await makeUser();
const file = await makeFile(owner.user);
const groupUid = uuidv4();
await server.clients.db.write(
'INSERT INTO `group` (`uid`, `owner_user_id`, `kind`, `name`, ' +
'`extra`, `metadata`) VALUES (?, ?, ?, ?, ?, ?)',
[groupUid, owner.user.id, 'team', 'Team', '{}', '{}'],
);
const [group] = (await server.clients.db.read(
'SELECT id FROM `group` WHERE uid = ?',
[groupUid],
)) as { id: number }[];
await server.clients.db.write(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[member.user.id, group.id],
);
await server.stores.permission.upsertUserGroupPerm(
Number(group.id),
owner.user.id,
`fs:${file.uuid}:read`,
{},
);
// The replica has not seen the member join yet.
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi.spyOn(db, 'pread').mockImplementation(primaryRead);
const read = vi
.spyOn(db, 'read')
.mockImplementation(async (sql, params) =>
String(sql).includes('jct_user_group')
? []
: primaryRead(sql, params),
);
const bump = vi.spyOn(server.stores.permission, 'bumpCacheGenerations');
try {
await server.services.share.onEntryDeleted(file.uuid);
expect(bump.mock.calls.flat(2)).toContain(
`user:${member.user.uuid}`,
);
} finally {
bump.mockRestore();
read.mockRestore();
pread.mockRestore();
}
});
it('does not answer whether a name is already in the owner\'s Trash', async () => {
const owner = await makeUser();
const recipient = await makeUser();
+59 -20
View File
@@ -292,6 +292,9 @@ export const modeFromEntryPermission = (permission: string): string | null => {
*/
const RETIRE_CHUNK_SIZE = 100;
/** How long after an owner shares the retire reads stay on the primary. */
const RECENT_SHARE_WINDOW_MS = 30_000;
/** Shares one user may create per UTC day, absent a config override. */
export const DEFAULT_DAILY_SHARE_LIMIT = 200;
@@ -397,6 +400,11 @@ export class ShareService extends PuterService {
* fleet-wide; its TTL covers a process the bump missed.
*/
readonly #ownerShares = new SubscriptionCache();
/** Owners who shared just now: a replica may not have the row yet. */
readonly #recentSharers = new SubscriptionCache(
undefined,
RECENT_SHARE_WINDOW_MS,
);
readonly #ownerLookups = new Map<string, Promise<boolean>>();
/**
@@ -619,6 +627,11 @@ export class ShareService extends PuterService {
const chunk = entries.slice(i, i + RETIRE_CHUNK_SIZE);
const removed = await this.onEntryDeleted(
chunk.map((entry) => entry.uuid),
{
primary: this.#sharedRecently(
chunk.map((entry) => entry.userId),
),
},
);
const holdersByEntry = new Map<string, Set<number>>();
@@ -932,6 +945,16 @@ export class ShareService extends PuterService {
this.#ownerShares.generationOf(ownerUserId),
true,
);
this.#recentSharers.write(
ownerUserId,
this.#recentSharers.generationOf(ownerUserId),
true,
);
}
/** Whether this process heard any of these owners share within the window. */
#sharedRecently(ownerUserIds: number[]): boolean {
return ownerUserIds.some((id) => this.#recentSharers.read(id) === true);
}
async #emitGui(
@@ -1555,7 +1578,9 @@ export class ShareService extends PuterService {
// Every row, not just the applied ones: a node whose only share is a
// pending invite or a team grant is exactly what the group and invite
// sweeps ask about.
const rows = await this.stores.share.listAllByFsentrySubtree(entry.id);
const rows = await this.stores.share.listAllByFsentrySubtree(entry.id, {
primary: true,
});
const nodes = await this.stores.fsEntry.getEntriesByIds(
rows.map((row: { fsentry_id: number }) => Number(row.fsentry_id)),
);
@@ -1779,9 +1804,13 @@ export class ShareService extends PuterService {
/**
* Retire the grants pointing at a node that no longer exists. Returns the
* rows removed, which is the only record of who had access — the index rows
* cascade away with the fsentry.
* cascade away with the fsentry. Reads a replica unless `primary` says a
* grant may be too new for one.
*/
async onEntryDeleted(entryUids: string | string[]): Promise<
async onEntryDeleted(
entryUids: string | string[],
{ primary = false }: { primary?: boolean } = {},
): Promise<
Array<{
holder_user_id: number;
issuer_user_id: number;
@@ -1796,6 +1825,7 @@ export class ShareService extends PuterService {
const removed =
await this.stores.permission.deleteUserUserPermsByPermissionPrefixes(
uids.flatMap((uid) => [`fs:${uid}`, `manage:fs:${uid}`]),
{ primary },
);
// Retiring the rows is not enough: a holder's cached scan still answers
@@ -1808,19 +1838,14 @@ export class ShareService extends PuterService {
// Group grants on the same node, and their members' caches: without
// this they outlive the file and keep answering "allowed".
const removedGroups =
const { members } =
await this.stores.permission.deleteUserGroupPermsByPermissionPrefixes(
uids.flatMap((uid) => [`fs:${uid}`, `manage:fs:${uid}`]),
{ primary },
);
const memberUuids = (
await Promise.all(
[...new Set(removedGroups.map((row) => Number(row.group_id)))]
.filter((id) => Number.isFinite(id))
.map((id) =>
this.stores.permission.listGroupMemberUuids(id),
),
)
).flat();
const memberUuids = members
.map((member) => member.uuid)
.filter((uuid): uuid is string => Boolean(uuid));
await this.stores.permission.bumpCacheGenerations([
...new Set([
@@ -1877,15 +1902,23 @@ export class ShareService extends PuterService {
* the subtree stands on its own, and one left behind keeps granting the
* issuer's recipients access under an owner who never agreed to them.
*/
async onEntryOwnerChanged(entry: FSEntry): Promise<void> {
async onEntryOwnerChanged(
entry: FSEntry,
{ primary = true }: { primary?: boolean } = {},
): Promise<void> {
// A file's share rows can only name the file itself, so there is
// nothing to list or hydrate.
if (!entry.isDir) {
await this.onEntryDeleted([entry.uuid]);
await this.stores.share.deleteByFsentryIds([entry.id]);
await this.onEntryDeleted([entry.uuid], { primary });
await this.stores.share.deleteByFsentryIds(
[entry.id],
[entry.uuid],
);
return;
}
const rows = await this.stores.share.listAllByFsentrySubtree(entry.id);
const rows = await this.stores.share.listAllByFsentrySubtree(entry.id, {
primary,
});
const fsentryIds = [
...new Set([
entry.id,
@@ -1897,8 +1930,8 @@ export class ShareService extends PuterService {
const nodes = await this.stores.fsEntry.getEntriesByIds(fsentryIds);
const uuids = [...nodes.values()].map((node) => node.uuid);
if (uuids.length > 0) await this.onEntryDeleted(uuids);
await this.stores.share.deleteByFsentryIds(fsentryIds);
if (uuids.length > 0) await this.onEntryDeleted(uuids, { primary });
await this.stores.share.deleteByFsentryIds(fsentryIds, uuids);
}
/**
@@ -1913,7 +1946,11 @@ export class ShareService extends PuterService {
async onEntryTrashed(entry: FSEntry): Promise<void> {
// The same sweep as a change of owner: every kind of row in the
// subtree, since a link share deeper down grants access on its own.
await this.onEntryOwnerChanged(entry);
// Nearly every trashed entry has no shares, so the reads stay off the
// primary unless its owner shared just now.
await this.onEntryOwnerChanged(entry, {
primary: this.#sharedRecently([entry.userId]),
});
}
// -- Reads --------------------------------------------------------
@@ -3015,6 +3052,7 @@ export class ShareService extends PuterService {
mode,
issuerAppUid: this.#actingAppUid(actor),
});
this.#ownerShared(entry.userId);
return {
...this.#resolve(row, entry, actor, { username: null }),
anyone: true,
@@ -3314,6 +3352,7 @@ export class ShareService extends PuterService {
mode,
issuerAppUid: this.#actingAppUid(actor),
});
this.#ownerShared(entry.userId);
return {
...this.#resolve(row, entry, actor, { username: null }),
pending: true,
@@ -428,6 +428,43 @@ describe('SocketService (live socket.io)', () => {
sessionSocket.disconnect();
});
it('drops a token`s socket on a revocation that reached it from elsewhere', async () => {
const row = await server.stores.user.getByUsername(user.username);
const actor = makeActor({ user: row as never });
const doomed = await runWithContext({ actor }, () =>
server.services.auth.createAccessToken(actor, [[FULL_API_ACCESS]], {
label: 'revoke-fanout-probe',
}),
);
const { token_uid } = server.services.token.verify<{
token_uid: string;
}>('auth', doomed);
const tokenSocket = await connect({ auth_token: doomed });
expect(tokenSocket.connected).toBe(true);
// A malformed peer payload is ignored.
for (const data of [null, {}, { token_uid: 42 }]) {
server.clients.event.emit(
'outer.auth.access-token.revoked',
data as never,
{ from_outside: true },
);
}
await new Promise((r) => setTimeout(r, 200));
expect(tokenSocket.connected).toBe(true);
// As a peer cluster delivers it: the token was revoked on another node.
server.clients.event.emit(
'outer.auth.access-token.revoked',
{ token_uid },
{ from_outside: true },
);
await vi.waitFor(() => expect(tokenSocket.connected).toBe(false), {
timeout: 5000,
});
});
it('rejects an app-under-user token while events are off', async () => {
const row = await server.stores.user.getByUsername(user.username);
const appUid = `app-${uuidv4()}`;
@@ -926,6 +963,31 @@ describe('SocketService (live socket.io)', () => {
socket.disconnect();
});
it('keeps a connection up when its re-check lookup fails', async () => {
const user = await createTestUser(server, {
username: 'sock-lookup-down',
password: 'sock-lookup-down-password',
});
const socket = await connect({ auth_token: `Bearer ${user.token}` });
const authenticate = vi
.spyOn(server.services.auth, 'authenticate')
.mockRejectedValue(
Object.assign(new Error('Database operation failed'), {
code: 'dbBatchFailed',
}),
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
await socketService.reauthenticateSockets();
await new Promise((r) => setTimeout(r, 200));
expect(socket.connected).toBe(true);
} finally {
authenticate.mockRestore();
warn.mockRestore();
socket.disconnect();
}
});
it('re-checks without recording session activity', async () => {
const idle = await createTestUser(server, {
username: 'sock-idle',
+18 -9
View File
@@ -982,15 +982,22 @@ export class SocketService extends PuterService {
},
);
const decisions = new Map<string, SocketAuthDecision>();
let unchecked = 0;
checked.forEach((token, i) => {
const outcome = outcomes[i];
decisions.set(
token,
outcome?.status === 'fulfilled'
? outcome.value
: { reject: new Error('socket reauth failed') },
);
// A lookup that failed says nothing about the credential, so its
// sockets stay up until a later sweep gets an answer.
if (outcome?.status === 'fulfilled') {
decisions.set(token, outcome.value);
} else {
unchecked++;
}
});
if (unchecked > 0) {
console.warn(
`[socket] reauth sweep could not check ${unchecked} credential(s)`,
);
}
for (const socket of sockets) {
const decision = socket.authToken
@@ -1175,10 +1182,12 @@ export class SocketService extends PuterService {
);
this.clients.event.on(
'auth.access-token.revoked',
'outer.auth.access-token.revoked',
(_key: string, data: unknown) => {
const { token_uid } = data as { token_uid: string };
this.#evictAccessTokenSockets(token_uid).catch(
const tokenUid = (data as { token_uid?: unknown } | null)
?.token_uid;
if (typeof tokenUid !== 'string') return;
this.#evictAccessTokenSockets(tokenUid).catch(
(err: unknown) => {
console.error('[socket] token eviction failed', err);
},
@@ -64,6 +64,29 @@ describe('PermissionStore', () => {
);
};
/** Replica reads of `table` see `stale`; the primary stays real. */
const lagReplica = (
table: string,
stale: (sql: string) => Record<string, unknown>[],
) => {
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi
.spyOn(db, 'pread')
.mockImplementation((sql, params) => primaryRead(sql, params));
const read = vi
.spyOn(db, 'read')
.mockImplementation(async (sql, params) =>
String(sql).includes(table)
? stale(String(sql))
: primaryRead(sql, params),
);
return () => {
read.mockRestore();
pread.mockRestore();
};
};
// -- Flat KV view --------------------------------------------------
describe('flat user permissions (KV view)', () => {
@@ -911,6 +934,341 @@ describe('PermissionStore', () => {
expect(await store.readUserGroupPerms(user.id, [])).toEqual([]);
});
it('does not read a revoked grant back from a lagging replica', async () => {
const issuer = await makeUser();
const member = await makeUser();
const groupId = await seedGroup(issuer.id);
await server.clients.db.write(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[member.id, groupId],
);
await seedGroupPerm(issuer.id, groupId, 'fs:lag:read');
const [stale] = await store.readUserGroupPerms(member.id, [
'fs:lag:read',
]);
const [staleForHolder] = await store.readUserGroupPermsForHolders(
[member.id],
['fs:lag:read'],
);
await store.deleteUserGroupPerm(groupId, issuer.id, 'fs:lag:read');
// The replica still has the row the primary just deleted.
const restore = lagReplica('user_to_group_permissions', (sql) =>
sql.includes('holder_user_id')
? [staleForHolder]
: [{ ...stale, extra: '{}' }],
);
try {
expect(
await store.readUserGroupPerms(member.id, ['fs:lag:read']),
).toEqual([]);
expect(
await store.readUserGroupPermsForHolders(
[member.id],
['fs:lag:read'],
),
).toEqual([]);
} finally {
restore();
}
});
it('does not read grants removed with their node back from a lagging replica', async () => {
const issuer = await makeUser();
const member = await makeUser();
const groupId = await seedGroup(issuer.id);
await server.clients.db.write(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[member.id, groupId],
);
const node = uuidv4();
await seedGroupPerm(issuer.id, groupId, `fs:${node}:read`);
const [stale] = await store.readUserGroupPerms(member.id, [
`fs:${node}:read`,
]);
await store.deleteUserGroupPermsByPermissionPrefixes([
`fs:${node}`,
]);
const restore = lagReplica('user_to_group_permissions', () => [
{ ...stale, extra: '{}' },
]);
try {
expect(
await store.readUserGroupPerms(member.id, [
`fs:${node}:read`,
]),
).toEqual([]);
} finally {
restore();
}
});
it('removes a grant the replica has not seen yet with its node, when asked to read the primary', async () => {
const issuer = await makeUser();
const groupId = await seedGroup(issuer.id);
const node = uuidv4();
await seedGroupPerm(issuer.id, groupId, `fs:${node}:read`);
const restore = lagReplica('user_to_group_permissions', () => []);
let unasked;
let removed;
try {
unasked = await store.deleteUserGroupPermsByPermissionPrefixes([
`fs:${node}`,
]);
removed = await store.deleteUserGroupPermsByPermissionPrefixes(
[`fs:${node}`],
{ primary: true },
);
} finally {
restore();
}
// Unasked, the replica's answer stands and the primary is left alone.
expect(unasked?.rows).toEqual([]);
expect(removed?.rows).toEqual([
{ group_id: groupId, permission: `fs:${node}:read` },
]);
expect(
await store.queryIssuerGroupPermsByPrefix(
issuer.id,
groupId,
`fs:${node}`,
),
).toEqual([]);
});
it('sends a former member to the primary once membership changes', async () => {
const issuer = await makeUser();
const member = await makeUser();
const groupId = await seedGroup(issuer.id);
await server.clients.db.write(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[member.id, groupId],
);
await seedGroupPerm(issuer.id, groupId, 'fs:left:read');
const [stale] = await store.readUserGroupPerms(member.id, [
'fs:left:read',
]);
await server.clients.db.write(
'DELETE FROM `jct_user_group` WHERE `user_id` = ? AND `group_id` = ?',
[member.id, groupId],
);
const emit = vi.spyOn(server.clients.event, 'emit');
try {
await store.markGroupMembershipChanged([member.id]);
// Only tombstones go out; there is no cached value to drop.
const sent = emit.mock.calls
.filter(([name]) => name === 'outer.cacheUpdate')
.flatMap(
([, data]) => (data as { cacheKey: string[] }).cacheKey,
);
expect(sent).toEqual([
`perms:u2g:${member.id}${CACHE_TOMBSTONE_SUFFIX}`,
]);
} finally {
emit.mockRestore();
}
const restore = lagReplica('user_to_group_permissions', () => [
{ ...stale, extra: '{}' },
]);
try {
expect(
await store.readUserGroupPerms(member.id, ['fs:left:read']),
).toEqual([]);
} finally {
restore();
}
});
const seedMember = async (issuerId: number, permission: string) => {
const member = await makeUser();
const groupId = await seedGroup(issuerId);
await server.clients.db.write(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[member.id, groupId],
);
await seedGroupPerm(issuerId, groupId, permission);
return { member, groupId };
};
const tombstoneSet = async (userId: number) =>
(await server.clients.redis.exists(
`perms:u2g:${userId}${CACHE_TOMBSTONE_SUFFIX}`,
)) > 0;
it('sends member reads to the primary before the grant is deleted', async () => {
const issuer = await makeUser();
const node = uuidv4();
const one = await seedMember(issuer.id, 'fs:order:read');
const many = await seedMember(issuer.id, `fs:${node}:read`);
const db = server.clients.db;
const primaryWrite = db.write.bind(db);
const seen: boolean[] = [];
const write = vi
.spyOn(db, 'write')
.mockImplementation(async (sql, params) => {
if (String(sql).startsWith('DELETE FROM')) {
seen.push(
(await tombstoneSet(one.member.id)) ||
(await tombstoneSet(many.member.id)),
);
}
return primaryWrite(sql, params);
});
try {
await store.deleteUserGroupPerm(
one.groupId,
issuer.id,
'fs:order:read',
);
await store.deleteUserGroupPermsByPermissionPrefixes([
`fs:${node}`,
]);
} finally {
write.mockRestore();
}
expect(seen).toEqual([true, true]);
});
it('leaves the grant in place when the member read fails', async () => {
const issuer = await makeUser();
const node = uuidv4();
const one = await seedMember(issuer.id, 'fs:retry:read');
const many = await seedMember(issuer.id, `fs:${node}:read`);
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi
.spyOn(db, 'pread')
.mockImplementation(async (sql, params) => {
if (String(sql).includes('`jct_user_group` ug')) {
throw new Error('primary unavailable');
}
return primaryRead(sql, params);
});
try {
await expect(
store.deleteUserGroupPerm(
one.groupId,
issuer.id,
'fs:retry:read',
),
).rejects.toThrow('primary unavailable');
await expect(
store.deleteUserGroupPermsByPermissionPrefixes([
`fs:${node}`,
]),
).rejects.toThrow('primary unavailable');
} finally {
pread.mockRestore();
}
// The retry still finds the grants and whose they were.
expect(
await store.deleteUserGroupPerm(
one.groupId,
issuer.id,
'fs:retry:read',
),
).toEqual({
removed: true,
members: [{ id: one.member.id, uuid: expect.any(String) }],
});
expect(
await store.deleteUserGroupPermsByPermissionPrefixes([
`fs:${node}`,
]),
).toEqual({
rows: [
{ group_id: many.groupId, permission: `fs:${node}:read` },
],
members: [{ id: many.member.id, uuid: expect.any(String) }],
});
});
it('includes someone who joined while the grant was deleted', async () => {
const issuer = await makeUser();
const joiner = await makeUser();
const { member, groupId } = await seedMember(
issuer.id,
'fs:joined:read',
);
const db = server.clients.db;
const primaryWrite = db.write.bind(db);
const write = vi
.spyOn(db, 'write')
.mockImplementation(async (sql, params) => {
if (String(sql).startsWith('DELETE FROM')) {
await primaryWrite(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[joiner.id, groupId],
);
}
return primaryWrite(sql, params);
});
let result;
try {
result = await store.deleteUserGroupPerm(
groupId,
issuer.id,
'fs:joined:read',
);
} finally {
write.mockRestore();
}
expect(result.removed).toBe(true);
expect(result.members.map((m) => m.id).sort()).toEqual(
[member.id, joiner.id].sort(),
);
expect(await tombstoneSet(joiner.id)).toBe(true);
});
it('still reports the removal when the second member read fails', async () => {
const issuer = await makeUser();
const { member, groupId } = await seedMember(
issuer.id,
'fs:reread:read',
);
const db = server.clients.db;
const primaryRead = db.read.bind(db);
let memberReads = 0;
const pread = vi
.spyOn(db, 'pread')
.mockImplementation(async (sql, params) => {
if (
String(sql).includes('`jct_user_group` ug') &&
++memberReads > 1
) {
throw new Error('primary unavailable');
}
return primaryRead(sql, params);
});
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
expect(
await store.deleteUserGroupPerm(
groupId,
issuer.id,
'fs:reread:read',
),
).toEqual({
removed: true,
members: [{ id: member.id, uuid: expect.any(String) }],
});
} finally {
pread.mockRestore();
warn.mockRestore();
}
});
it('reads many issuer/group pairs under many prefixes at once', async () => {
const issuer = await makeUser();
const rival = await makeUser();
@@ -1473,6 +1831,41 @@ describe('PermissionStore', () => {
).toHaveLength(1);
});
it('removes a grant the replica has not seen yet with its node, when asked to read the primary', async () => {
const issuer = await makeUser();
const holder = await makeUser();
const node = uuidv4();
await store.upsertUserUserPerm(
holder.id,
issuer.id,
`fs:${node}:read`,
{},
);
const restore = lagReplica('user_to_user_permissions', () => []);
let unasked;
let removed;
try {
unasked = await store.deleteUserUserPermsByPermissionPrefixes([
`fs:${node}`,
]);
removed = await store.deleteUserUserPermsByPermissionPrefixes(
[`fs:${node}`],
{ primary: true },
);
} finally {
restore();
}
// Unasked, the replica's answer stands and the primary is left alone.
expect(unasked).toEqual([]);
expect(removed).toHaveLength(1);
expect(
await store.readLinkedUserUserPermsFromPrimary(holder.id, [
`fs:${node}:read`,
]),
).toEqual([]);
});
it('does not let a wildcard in the prefix widen the match', async () => {
const issuer = await makeUser();
const holder = await makeUser();
+120 -28
View File
@@ -17,7 +17,11 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { PuterStore } from '../types';
import {
CACHE_TOMBSTONE_SUFFIX,
CACHE_TOMBSTONE_TTL_SECONDS,
PuterStore,
} from '../types';
import type { LayerInstances } from '../../types';
import type { puterStores } from '../index';
import { PermissionUtil } from '../../services/permission/permissionUtil';
@@ -98,6 +102,11 @@ type DbRead = (
params: unknown[],
) => Promise<Record<string, unknown>[]>;
export interface GroupMember {
id: number;
uuid: string | null;
}
export interface LinkedUserUserPermRow {
holder_user_id: number;
issuer_user_id: number;
@@ -645,25 +654,40 @@ export class PermissionStore extends PuterStore {
}));
}
/** `primary` when a grant may be too new for a replica to have it. */
#grantRead(primary: boolean): DbRead {
return primary
? this.clients.db.pread.bind(this.clients.db)
: this.clients.db.read.bind(this.clients.db);
}
/** The group analogue: a deleted node's group grants must go with it. */
async deleteUserGroupPermsByPermissionPrefixes(
permissions: string[],
): Promise<Array<{ group_id: number; permission: string }>> {
if (permissions.length === 0) return [];
{ primary = false }: { primary?: boolean } = {},
): Promise<{
rows: Array<{ group_id: number; permission: string }>;
members: GroupMember[];
}> {
if (permissions.length === 0) return { rows: [], members: [] };
const { where, params } = subtreeClause(permissions);
const rows = (await this.clients.db.read(
const rows = (await this.#grantRead(primary)(
'SELECT `group_id`, `permission` FROM `user_to_group_permissions` ' +
`WHERE ${where}`,
params,
)) as Array<{ group_id: number; permission: string }>;
if (rows.length === 0) return [];
if (rows.length === 0) return { rows, members: [] };
await this.clients.db.write(
`DELETE FROM \`user_to_group_permissions\` WHERE ${where}`,
params,
const { members } = await this.#deleteGroupGrants(
rows.map((row) => row.group_id),
() =>
this.clients.db.write(
`DELETE FROM \`user_to_group_permissions\` WHERE ${where}`,
params,
),
);
return rows;
return { rows, members };
}
/**
@@ -678,6 +702,7 @@ export class PermissionStore extends PuterStore {
*/
async deleteUserUserPermsByPermissionPrefixes(
permissions: string[],
{ primary = false }: { primary?: boolean } = {},
): Promise<
Array<{
holder_user_id: number;
@@ -688,7 +713,7 @@ export class PermissionStore extends PuterStore {
if (permissions.length === 0) return [];
const { where, params } = subtreeClause(permissions);
const rows = (await this.clients.db.read(
const rows = (await this.#grantRead(primary)(
'SELECT `holder_user_id`, `issuer_user_id`, `permission` FROM `user_to_user_permissions` ' +
`WHERE ${where}`,
params,
@@ -1332,9 +1357,6 @@ export class PermissionStore extends PuterStore {
}
// -- SQL: user-to-group permissions ------------------------------
//
// Read-only. Group grants are seeded by migration (the admin group's
// unrestricted `driver` access); nothing writes them at runtime.
/**
* Reads group permissions granted to groups the user is a member of, for a
@@ -1351,9 +1373,15 @@ export class PermissionStore extends PuterStore {
if (permissions.length === 0) return [];
let permClause = permissions.map(() => 'p.permission = ?').join(' OR ');
if (permissions.length > 1) permClause = `(${permClause})`;
const tombstoned = await this.isCacheKeyTombstoned([
this.#u2gCacheKey(userId),
]);
const read: DbRead = tombstoned
? this.clients.db.pread.bind(this.clients.db)
: this.clients.db.read.bind(this.clients.db);
// Deletion leaves memberships and grants, so a deleted team would
// otherwise keep resolving access nothing can withdraw.
const rows = await this.clients.db.read(
const rows = await read(
'SELECT p.permission, p.user_id, p.group_id, p.extra FROM `user_to_group_permissions` p ' +
'JOIN `jct_user_group` ug ON p.group_id = ug.group_id ' +
'JOIN `group` g ON g.`id` = ug.group_id ' +
@@ -1387,13 +1415,44 @@ export class PermissionStore extends PuterStore {
.filter((uuid): uuid is string => Boolean(uuid));
}
/** Whose standing access a grant to this group settles. */
async listGroupMemberIds(groupId: number): Promise<number[]> {
const rows = (await this.clients.db.read(
'SELECT `user_id` FROM `jct_user_group` WHERE `group_id` = ?',
[groupId],
)) as { user_id: number }[];
return rows.map((r) => Number(r.user_id));
async #listGroupMembers(groupIds: number[]): Promise<GroupMember[]> {
const ids = [...new Set(groupIds.map(Number))].filter((id) =>
Number.isFinite(id),
);
if (ids.length === 0) return [];
const rows = (await this.clients.db.pread(
'SELECT DISTINCT u.`id`, u.`uuid` FROM `jct_user_group` ug ' +
'JOIN `user` u ON u.`id` = ug.`user_id` ' +
`WHERE ug.\`group_id\` IN (${ids.map(() => '?').join(', ')})`,
ids,
)) as { id: number; uuid: string | null }[];
return rows.map((row) => ({ id: Number(row.id), uuid: row.uuid }));
}
/**
* Runs a delete of these groups' grants with their members' group reads
* already on the primary. Returns the members, later joiners included.
*/
async #deleteGroupGrants<T>(
groupIds: number[],
deleteGrants: () => Promise<T>,
): Promise<{ result: T; members: GroupMember[] }> {
// Before the delete: a failed member read leaves the grants to retry.
const members = await this.#listGroupMembers(groupIds);
await this.markGroupMembershipChanged(members.map((m) => m.id));
const result = await deleteGrants();
try {
const known = new Set(members.map((m) => m.id));
const joined = (await this.#listGroupMembers(groupIds)).filter(
(m) => !known.has(m.id),
);
await this.markGroupMembershipChanged(joined.map((m) => m.id));
members.push(...joined);
} catch (e) {
// The grants are gone; only someone who joined meanwhile is missed.
console.warn('[permission] group members not re-read:', e);
}
return { result, members };
}
/** Batched `readUserGroupPerms`, tagged with the user each row reached. */
@@ -1406,7 +1465,14 @@ export class PermissionStore extends PuterStore {
const holders = [...new Set(userIds)];
const perms = [...new Set(permissions)];
if (holders.length === 0 || perms.length === 0) return [];
const rows = await this.clients.db.read(
const changed = await this.tombstonedCacheKeys(
holders.map((holder) => this.#u2gCacheKey(holder)),
);
const read: DbRead =
changed.size > 0
? this.clients.db.pread.bind(this.clients.db)
: this.clients.db.read.bind(this.clients.db);
const rows = await read(
'SELECT ug.`user_id` AS `holder_user_id`, p.`permission`, p.`user_id` ' +
'FROM `user_to_group_permissions` p ' +
'JOIN `jct_user_group` ug ON p.`group_id` = ug.`group_id` ' +
@@ -1492,13 +1558,34 @@ export class PermissionStore extends PuterStore {
groupId: number,
issuerUserId: number,
permission: string,
): Promise<boolean> {
const result = await this.clients.db.write(
'DELETE FROM `user_to_group_permissions` ' +
'WHERE `group_id` = ? AND `user_id` = ? AND `permission` = ?',
[groupId, issuerUserId, permission],
): Promise<{ removed: boolean; members: GroupMember[] }> {
const { result, members } = await this.#deleteGroupGrants(
[groupId],
() =>
this.clients.db.write(
'DELETE FROM `user_to_group_permissions` ' +
'WHERE `group_id` = ? AND `user_id` = ? AND `permission` = ?',
[groupId, issuerUserId, permission],
),
);
return result.anyRowsAffected;
return { removed: result.anyRowsAffected, members };
}
/** Group reads of these users go to the primary; for leaves and deletes. */
async markGroupMembershipChanged(userIds: number[]): Promise<void> {
const ids = [...new Set(userIds.map(Number))].filter((id) =>
Number.isFinite(id),
);
if (ids.length === 0) return;
// Only the tombstones: nothing is cached under the base key.
await this.publishCacheKeys({
keys: ids.map(
(id) => this.#u2gCacheKey(id) + CACHE_TOMBSTONE_SUFFIX,
),
serializedData: '1',
ttlSeconds: CACHE_TOMBSTONE_TTL_SECONDS,
broadcast: true,
});
}
async auditUserGroupPerm(
@@ -1888,6 +1975,11 @@ export class PermissionStore extends PuterStore {
return `perms:u2u:holder:${holderUserId}`;
}
/** Holds only a tombstone: group reads aren't cached here. */
#u2gCacheKey(userId: number): string {
return `perms:u2g:${userId}`;
}
#u2aCacheKey(userId: number, appId: number): string {
return `perms:u2a:${userId}:${appId}`;
}
+20 -6
View File
@@ -658,12 +658,26 @@ export class SessionStore extends PuterStore {
*/
async findActiveByAccessTokenUid(tokenUid) {
if (!tokenUid) return null;
const now = nowSeconds();
const rows = await this.clients.db.read(
"SELECT * FROM `sessions` WHERE `kind` = 'access_token' AND (`access_token_uid` = ? OR `legacy_token_uid` = ?) AND `revoked_at` IS NULL AND (`expires_at` IS NULL OR `expires_at` > ?) ORDER BY `id` DESC LIMIT 1",
[tokenUid, tokenUid, now],
);
return this.#normalizeRow(rows[0]);
// One indexed lookup per column: an OR across both can't use either
// index on MySQL. MySQL indexes the legacy uid only through its
// active-row generated column, equal to it while `revoked_at` is NULL.
const legacyColumn = this.clients.db.case({
mysql: 'legacy_token_unique_key',
otherwise: 'legacy_token_uid',
});
const findBy = async (column) => {
const rows = await this.clients.db.read(
`SELECT * FROM \`sessions\` WHERE \`kind\` = 'access_token' AND \`${column}\` = ? AND \`revoked_at\` IS NULL AND (\`expires_at\` IS NULL OR \`expires_at\` > ?) ORDER BY \`id\` DESC LIMIT 1`,
[tokenUid, nowSeconds()],
);
return this.#normalizeRow(rows[0]);
};
// Sent together, so a miss on the first costs no second round trip.
const [own, legacy] = await Promise.all([
findBy('access_token_uid'),
findBy(legacyColumn),
]);
return own ?? legacy;
}
/**
@@ -771,6 +771,77 @@ describe('SessionStore', () => {
});
});
describe('findActiveByAccessTokenUid', () => {
const tokenRow = (userId: number, fields: Record<string, unknown>) =>
target.create(userId, { kind: 'access_token', ...fields });
it('finds a token row by its access_token_uid', async () => {
const user = await makeUser();
const tokenUid = uuidv4();
const row = await tokenRow(user.id, { access_token_uid: tokenUid });
const found = await target.findActiveByAccessTokenUid(tokenUid);
expect(found?.uuid).toBe(row.uuid);
});
it('finds a migrated row by its legacy token uid', async () => {
const user = await makeUser();
const legacyUid = uuidv4();
const row = await tokenRow(user.id, {
legacy_token_uid: legacyUid,
created_via: 'legacy_backfill',
});
const found = await target.findActiveByAccessTokenUid(legacyUid);
expect(found?.uuid).toBe(row.uuid);
});
it('returns null for a uid no token row carries', async () => {
const user = await makeUser();
await tokenRow(user.id, { access_token_uid: uuidv4() });
expect(
await target.findActiveByAccessTokenUid(uuidv4()),
).toBeNull();
});
it('skips revoked and expired rows under either uid', async () => {
const user = await makeUser();
const revokedUid = uuidv4();
const revokedLegacyUid = uuidv4();
const expiredUid = uuidv4();
const revoked = await tokenRow(user.id, {
access_token_uid: revokedUid,
});
const revokedLegacy = await tokenRow(user.id, {
legacy_token_uid: revokedLegacyUid,
});
await tokenRow(user.id, {
access_token_uid: expiredUid,
expires_at: Math.floor(Date.now() / 1000) - 60,
});
await target.removeByUuid(revoked.uuid);
await target.removeByUuid(revokedLegacy.uuid);
for (const uid of [revokedUid, revokedLegacyUid, expiredUid]) {
expect(await target.findActiveByAccessTokenUid(uid)).toBeNull();
}
});
it('ignores a non-token row carrying the uid', async () => {
const user = await makeUser();
const tokenUid = uuidv4();
await target.create(user.id, {
kind: 'web',
access_token_uid: tokenUid,
});
expect(
await target.findActiveByAccessTokenUid(tokenUid),
).toBeNull();
});
});
describe('getOrCreateGodmodeToken', () => {
const nowS = () => Math.floor(Date.now() / 1000);
const mint = (
+90 -25
View File
@@ -48,6 +48,33 @@ const SHARED_IDS_CHUNK_SIZE = 1000;
* and no permission behind it, and is itself what the ACL reads.
*/
export class ShareStore extends PuterStore {
onServerStart() {
// A peer region's link revokes; our own emit already applied here.
this.clients.event.on(
'outer.share.linksRevoked',
async (_key, data, meta) => {
if (!meta?.from_outside) return;
const fsentryIds = Array.isArray(data?.fsentryIds)
? data.fsentryIds.filter((id) => Number.isInteger(id))
: [];
const uuids = Array.isArray(data?.uuids)
? data.uuids.filter(
(uuid) => typeof uuid === 'string' && uuid !== '',
)
: [];
if (fsentryIds.length === 0 && uuids.length === 0) return;
try {
await this.#applyLinksRevoked(fsentryIds, uuids);
} catch (e) {
console.warn(
'[share] remote link-revoke marker not set:',
e,
);
}
},
);
}
// -- Reads --------------------------------------------------------
/** Pass `primary` to read back a row just written; a replica may lag. */
@@ -338,12 +365,17 @@ export class ShareStore extends PuterStore {
* Every share row on a node and everything beneath it, whatever kind —
* user, group and link shares plus unclaimed invites.
* `listByFsentrySubtree` answers the narrower question; this one is for
* retiring the lot.
* retiring the lot. Pass `primary` when a share may be too new for a
* replica.
*
* @param {number} fsentryId
* @param {{ primary?: boolean }} [opts]
*/
async listAllByFsentrySubtree(fsentryId) {
const rows = await this.clients.db.read(
async listAllByFsentrySubtree(fsentryId, { primary = false } = {}) {
const read = primary
? this.clients.db.pread.bind(this.clients.db)
: this.clients.db.read.bind(this.clients.db);
const rows = await read(
this.#subtreeCte() +
'SELECT `share`.* FROM `share` ' +
'JOIN `subtree` ON `share`.`fsentry_id` = `subtree`.`id` ' +
@@ -964,14 +996,19 @@ export class ShareStore extends PuterStore {
* its shares never fires.
*
* @param {number[]} fsentryIds
* @param {string[]} [entryUuids] The nodes' uuids; looked up when omitted.
*/
async deleteByFsentryIds(fsentryIds) {
async deleteByFsentryIds(fsentryIds, entryUuids) {
if (fsentryIds.length === 0) return 0;
const placeholders = fsentryIds.map(() => '?').join(', ');
const result = await this.clients.db.write(
`DELETE FROM \`share\` WHERE \`fsentry_id\` IN (${placeholders})`,
fsentryIds,
);
// Which of these nodes held a link is no longer known, so mark them all.
if (result.anyRowsAffected) {
await this.#markLinksRevoked(fsentryIds, entryUuids);
}
return result.affectedRows;
}
@@ -1216,36 +1253,64 @@ export class ShareStore extends PuterStore {
[fsentryId],
);
const removed = result.anyRowsAffected;
if (removed) await this.#markLinkRevoked(fsentryId, entryUuid);
if (removed) {
await this.#markLinksRevoked(
[fsentryId],
entryUuid ? [entryUuid] : undefined,
);
}
return removed;
}
/** Open the window in which reads of this node's link go to the primary. */
async #markLinkRevoked(fsentryId, entryUuid) {
try {
let uuid = entryUuid;
if (!uuid) {
/** Reads of these nodes' links go to the primary, here and in peers. */
async #markLinksRevoked(fsentryIds, entryUuids) {
const ids = [...new Set(fsentryIds.map(Number))];
let uuids = entryUuids?.length >= ids.length ? entryUuids : null;
if (!uuids) {
try {
const rows = await this.clients.db.pread(
'SELECT `uuid` FROM `fsentries` WHERE `id` = ? LIMIT 1',
[fsentryId],
'SELECT `uuid` FROM `fsentries` WHERE `id` IN ' +
`(${ids.map(() => '?').join(', ')})`,
ids,
);
uuid = rows[0]?.uuid;
uuids = rows.map((row) => String(row.uuid));
} catch (e) {
console.warn('[share] link-revoke uuids not found:', e);
uuids = entryUuids ?? [];
}
const keys = [ShareStore.revokedLinkKey('id', fsentryId)];
if (uuid) keys.push(ShareStore.revokedLinkKey('uuid', uuid));
await Promise.all(
keys.map((key) =>
this.clients.redis.set(
key,
'1',
'EX',
ShareStore.REVOKED_LINK_PRIMARY_WINDOW_SECONDS,
),
),
);
}
try {
await this.#applyLinksRevoked(ids, uuids);
} catch (e) {
console.warn('[share] link-revoke marker not set:', e);
}
// Peers still get the ids when the local half failed.
try {
this.clients.event.emit(
'outer.share.linksRevoked',
{ fsentryIds: ids, uuids },
{},
);
} catch (e) {
console.warn('[share] link-revoke not sent to peers:', e);
}
}
/** Local half of {@link #markLinksRevoked}; never emits. */
async #applyLinksRevoked(fsentryIds, uuids) {
const pipeline = this.clients.redis.pipeline();
for (const key of [
...fsentryIds.map((id) => ShareStore.revokedLinkKey('id', id)),
...uuids.map((uuid) => ShareStore.revokedLinkKey('uuid', uuid)),
]) {
pipeline.set(
key,
'1',
'EX',
ShareStore.REVOKED_LINK_PRIMARY_WINDOW_SECONDS,
);
}
await pipeline.exec();
}
// -- Daily quota --------------------------------------------------
+191
View File
@@ -337,6 +337,176 @@ describe('ShareStore', () => {
);
});
it('does not read back a link removed with its node from a lagging replica', async () => {
const entry = await makeEntry(issuer);
const stale = await store.upsertAnyone({
issuerUserId: issuer.id,
fsentryId: entry.id,
mode: 'read',
});
await store.deleteByFsentryIds([entry.id]);
// The replica still has the link the primary just deleted.
const db = server.clients.db;
const primaryRead = db.read.bind(db);
const pread = vi.spyOn(db, 'pread').mockImplementation(primaryRead);
const read = vi
.spyOn(db, 'read')
.mockImplementation(async (q, p) =>
/FROM `share`/u.test(q)
? [
{
...stale,
data: '{}',
entry_uuid: entry.uuid,
owner_user_id: issuer.id,
},
]
: primaryRead(q, p),
);
try {
expect(await store.getAnyone(entry.id)).toBeNull();
expect(await store.listAnyoneOnFsentries([entry.id])).toEqual(
[],
);
expect(await store.listAnyoneReaching([entry.uuid])).toEqual(
[],
);
} finally {
read.mockRestore();
pread.mockRestore();
}
});
it('tells peer regions when a link is removed', async () => {
const entry = await makeEntry(issuer);
await store.upsertAnyone({
issuerUserId: issuer.id,
fsentryId: entry.id,
mode: 'read',
});
const emit = vi.spyOn(server.clients.event, 'emit');
try {
await store.deleteByFsentryIds([entry.id]);
expect(emit).toHaveBeenCalledWith(
'outer.share.linksRevoked',
{ fsentryIds: [entry.id], uuids: [entry.uuid] },
{},
);
} finally {
emit.mockRestore();
}
});
it('applies a link removal broadcast by a peer region', async () => {
const fsentryId = 900000 + Math.floor(Math.random() * 99999);
const uuid = uuidv4();
server.clients.event.emit(
'outer.share.linksRevoked',
{ fsentryIds: [fsentryId], uuids: [uuid] },
{ from_outside: true },
);
await vi.waitFor(async () => {
expect(
await server.clients.redis.get(
ShareStore.revokedLinkKey('uuid', uuid),
),
).toBe('1');
});
expect(
await server.clients.redis.ttl(
ShareStore.revokedLinkKey('id', fsentryId),
),
).toBeGreaterThan(25);
});
it('still tells peer regions when the local marker cannot be set', async () => {
const entry = await makeEntry(issuer);
await store.upsertAnyone({
issuerUserId: issuer.id,
fsentryId: entry.id,
mode: 'read',
});
const pipeline = vi
.spyOn(server.clients.redis, 'pipeline')
.mockImplementation(() => {
throw new Error('redis unavailable');
});
const emit = vi.spyOn(server.clients.event, 'emit');
try {
await store.deleteByFsentryIds([entry.id], [entry.uuid]);
expect(emit).toHaveBeenCalledWith(
'outer.share.linksRevoked',
{ fsentryIds: [entry.id], uuids: [entry.uuid] },
{},
);
} finally {
emit.mockRestore();
pipeline.mockRestore();
}
});
it('neither marks nor tells peers when nothing was removed', async () => {
const entry = await makeEntry(issuer);
const emit = vi.spyOn(server.clients.event, 'emit');
try {
expect(await store.deleteByFsentryIds([entry.id])).toBe(0);
expect(emit).not.toHaveBeenCalledWith(
'outer.share.linksRevoked',
expect.anything(),
expect.anything(),
);
} finally {
emit.mockRestore();
}
expect(
await server.clients.redis.get(
ShareStore.revokedLinkKey('uuid', entry.uuid),
),
).toBeNull();
});
it("ignores its own region's event and malformed payloads", async () => {
const local = uuidv4();
const sentinel = uuidv4();
const bogus = 900000 + Math.floor(Math.random() * 99999);
const emit = (data, meta) =>
server.clients.event.emit(
'outer.share.linksRevoked',
data,
meta,
);
emit({ fsentryIds: [], uuids: [local] }, {});
for (const data of [
null,
{ fsentryIds: 'x', uuids: 'y' },
{
fsentryIds: [String(bogus), bogus + 0.5, null],
uuids: [bogus, '', null],
},
]) {
emit(data, { from_outside: true });
}
// Handled in order, so once this lands the ones above have too.
emit({ fsentryIds: [], uuids: [sentinel] }, { from_outside: true });
await vi.waitFor(async () => {
expect(
await server.clients.redis.get(
ShareStore.revokedLinkKey('uuid', sentinel),
),
).toBe('1');
});
for (const key of [
ShareStore.revokedLinkKey('uuid', local),
ShareStore.revokedLinkKey('uuid', String(bogus)),
ShareStore.revokedLinkKey('id', bogus),
ShareStore.revokedLinkKey('id', bogus + 0.5),
]) {
expect(await server.clients.redis.get(key)).toBeNull();
}
});
it('reads a link past the replica once one has been withdrawn', async () => {
const entry = await makeEntry(issuer);
await store.upsertAnyone({
@@ -1155,6 +1325,27 @@ describe('ShareStore', () => {
};
};
it('lists a share the replica lacks in a subtree when asked to read the primary', async () => {
const entry = await makeEntry(issuer);
const link = await store.upsertAnyone({
issuerUserId: issuer.id,
fsentryId: entry.id,
mode: 'read',
});
const restore = lagShares([]);
try {
expect(
await store.listAllByFsentrySubtree(entry.id),
).toEqual([]);
const rows = await store.listAllByFsentrySubtree(entry.id, {
primary: true,
});
expect(rows.map((row) => row.uid)).toEqual([link.uid]);
} finally {
restore();
}
});
it('returns the rows it inserts before the replica has them', async () => {
const entry = await makeEntry(issuer);
// A group row written directly: the share only needs its id,
-13
View File
@@ -196,7 +196,6 @@ async function create_app (title, source_path = null, items = null) {
feedbackEnabled: true,
metadata: {
window_resizable: true,
fullpage_on_landing: true,
},
})
.then(async (app) => {
@@ -225,7 +224,6 @@ async function create_app (title, source_path = null, items = null) {
metadata: {
category: null, // default category on creation
window_resizable: true,
fullpage_on_landing: true,
},
}).then(async (app) => {
// refresh app list
@@ -471,11 +469,6 @@ function generate_edit_app_section (app) {
<label for="edit-app-background" style="display: inline;">Run as a background process.</label>
</div>
<div>
<input type="checkbox" id="edit-app-fullpage-on-landing" name="edit-app-fullpage-on-landing" value="true" style="margin-top:30px;" ${app.metadata?.fullpage_on_landing ? 'checked' : ''} ${app.background ? 'disabled' : ''}>
<label for="edit-app-fullpage-on-landing" style="display: inline;">Load in full-page mode when a user lands directly on this app.</label>
</div>
<div>
<input type="checkbox" id="edit-app-maximize-on-start" name="edit-app-maximize-on-start" value="true" style="margin-top:30px;" ${maximize_on_start ? 'checked' : ''} ${app.background ? 'disabled' : ''}>
<label for="edit-app-maximize-on-start" style="display: inline;">Maximize window on start</label>
@@ -593,7 +586,6 @@ function trackOriginalValues () {
resizableWindow: $('#edit-app-window-resizable').is(':checked'),
hideTitleBar: $('#edit-app-hide-titlebar').is(':checked'),
locked: $('#edit-app-locked').is(':checked'),
fullPageOnLanding: $('#edit-app-fullpage-on-landing').is(':checked'),
setTitleToFile: $('#edit-app-set-title-to-file').is(':checked'),
userFeedback: $('#edit-app-user-feedback').is(':checked'),
},
@@ -635,7 +627,6 @@ function hasChanges () {
$('#edit-app-window-resizable').is(':checked') !== originalValues.checkboxes.resizableWindow ||
$('#edit-app-hide-titlebar').is(':checked') !== originalValues.checkboxes.hideTitleBar ||
$('#edit-app-locked').is(':checked') !== originalValues.checkboxes.locked ||
$('#edit-app-fullpage-on-landing').is(':checked') !== originalValues.checkboxes.fullPageOnLanding ||
$('#edit-app-set-title-to-file').is(':checked') !== originalValues.checkboxes.setTitleToFile ||
$('#edit-app-user-feedback').is(':checked') !== originalValues.checkboxes.userFeedback
);
@@ -683,7 +674,6 @@ function resetToOriginalValues () {
$('#edit-app-window-resizable').prop('checked', originalValues.checkboxes.resizableWindow);
$('#edit-app-hide-titlebar').prop('checked', originalValues.checkboxes.hideTitleBar);
$('#edit-app-locked').prop('checked', originalValues.checkboxes.locked);
$('#edit-app-fullpage-on-landing').prop('checked', originalValues.checkboxes.fullPageOnLanding);
$('#edit-app-set-title-to-file').prop('checked', originalValues.checkboxes.setTitleToFile);
$('#edit-app-user-feedback').prop('checked', originalValues.checkboxes.userFeedback);
@@ -1299,7 +1289,6 @@ async function saveEditedApp (mode) {
background: $('#edit-app-background').is(':checked'),
feedbackEnabled: $('#edit-app-user-feedback').is(':checked'),
metadata: {
fullpage_on_landing: $('#edit-app-fullpage-on-landing').is(':checked'),
social_image: socialImageUrl,
category: category || null,
window_size: {
@@ -2583,7 +2572,6 @@ $(document).on('change', '#edit-app-background', function (e) {
function disable_window_settings () {
$('#edit-app-maximize-on-start').prop('disabled', true);
$('#edit-app-fullpage-on-landing').prop('disabled', true);
$('#edit-app-window-width, #edit-app-window-height').prop('disabled', true);
$('#edit-app-window-top, #edit-app-window-left').prop('disabled', true);
$('#edit-app-window-resizable').prop('disabled', true);
@@ -2592,7 +2580,6 @@ function disable_window_settings () {
function enable_window_settings () {
$('#edit-app-maximize-on-start').prop('disabled', false);
$('#edit-app-fullpage-on-landing').prop('disabled', false);
$('#edit-app-window-width, #edit-app-window-height').prop('disabled', false);
$('#edit-app-window-top, #edit-app-window-left').prop('disabled', false);
$('#edit-app-window-resizable').prop('disabled', false);
+49 -5
View File
@@ -41,21 +41,52 @@ An object with the following properties:
| Option | Type | Description |
|--------|------|-------------|
| `path` | `String` | The item. Required when passing options as the only argument. |
| `recipient` | `String \| Object` | Whose access to withdraw. |
| `path` | `String` | The item. Required when passing options as the only argument, unless `paths` or `uid` names it. |
| `paths` | `Array` | Several items to withdraw in one call. |
| `uid` | `String` | The item, by UID. Can be used instead of `path`. |
| `recipient` | `String \| Object \| Array` | Whose access to withdraw. An array withdraws several recipients in one call. |
| `recipients` | `String \| Object \| Array` | Alias for `recipient`. |
## Return value
A `Promise` that resolves to `{ revoked }`, where `revoked` is how many grants were actually removed. It is `0` when there was nothing to withdraw, which is not an error.
A `Promise` that resolves to an object with the following properties:
| Property | Type | Description |
|----------|------|-------------|
| `revoked` | `Number` | How many grants were actually removed. It is `0` when there was nothing to withdraw, which is not an error. |
| `failed` | `Array` | The recipient/item pairs that were refused. Empty when none were. |
Each entry of `failed` has the following properties:
| Property | Type | Description |
|----------|------|-------------|
| `recipient` | `String` | The recipient as the call named it. This is a username, an email address, a team's uid or handle, or `anyone`. |
| `path` | `String` | The item's absolute path, when the call named it by path. A relative path comes back resolved against the app's root directory, and a path that starts with `~` comes back under the user's home directory, such as `/username/report.txt`. |
| `uid` | `String` | The item's UID as the call passed it, when the call named it by UID. |
| `message` | `String` | Why the pair was refused. |
| `code` | `String` | One of the codes below. |
Each recipient/item pair is withdrawn on its own. With several items or recipients, every combination is one pair. A refused pair does not stop the others. The promise resolves, `revoked` counts what the others removed, and `failed` lists the pairs that were refused.
## Errors
A rejection carries `{ message, code }`.
The promise rejects only when every pair was refused, and at least one of them for a reason other than the recipient or the item being gone. A pair refused with `user_does_not_exist` or `subject_does_not_exist` has nothing left to withdraw, so a call made only of those resolves with `revoked: 0` and the pairs listed in `failed`.
That rejection carries `{ message, code, failed }`. The `message` and `code` come from the first refused pair that names a code other than those two. The `failed` array lists every refused pair, with the same properties as in the return value.
A request that fails as a whole also rejects, with the server's error and no `failed`. This happens when a call names no recipient or no item, or names a team by both `team` and `teamHandle` (`bad_request`), when it names more recipients or items than one call allows (`too_many_recipients`, `too_many_items`), and when it's over the [rate limit](/rate-limits-and-quotas/).
The codes a refused pair carries, in `failed` or on a rejection:
| `code` | Meaning |
| --- | --- |
| `team_share` | You tried to leave an item you hold only through a team. That access is the team's grant, not yours to drop; ask whoever shared it with the team, or leave the team. Returned with status `409`. If you also hold a share of your own, leaving drops that one and succeeds. |
| `team_share` | You tried to leave an item you hold only through a team. That access is the team's grant, not yours to drop; ask whoever shared it with the team, or leave the team. If you also hold a share of your own, leaving drops that one and succeeds. |
| `forbidden` | You may not withdraw shares of this item, or you tried to close its "anyone with the link" share, which only the owner may do, in person rather than through an app. |
| `subject_does_not_exist` | No such item, or you cannot see it. It is listed in `failed` and never causes a rejection on its own. |
| `user_does_not_exist` | The username has no account. It is listed in `failed` and never causes a rejection on its own. |
| `team_not_found` | No team has that uid. |
| `cannot_revoke_owner` | The recipient owns the item. |
| `unshare_failed` | No refused pair named a code, as when the server could not complete the request. |
## Who can withdraw what
@@ -96,6 +127,19 @@ Passing an email address that was **invited** but has not yet joined cancels the
</html>
```
### Withdraw several items and see which were refused
```js
const { revoked, failed } = await puter.fs.unshare({
paths: ['report.txt', 'budget.txt', 'notes.txt'],
recipient: 'friend',
});
console.log(`Removed ${revoked} share(s)`);
for (const pair of failed) {
console.log(`${pair.path} was not withdrawn from ${pair.recipient}: ${pair.message} (${pair.code})`);
}
```
### Leave a share someone gave you
```js
-14
View File
@@ -33,20 +33,6 @@ Sent on app startup, and whenever the user's locale on Puter is changed. The val
}
```
#### `themeChanged`
Sent on app startup, and whenever the user's desktop theme on Puter is changed. The value passed to `handler` is:
```js
{
palette: {
primaryHue, // (Float) Hue of the theme color
primarySaturation, // (String) Saturation of the theme color as a percentage, with % sign
primaryLightness, // (String) Lightness of the theme color as a percentage, with % sign
primaryAlpha, // (Float) Opacity of the theme color from 0 to 1
primaryColor, // (String) CSS color value for text
}
}
```
#### `connection`
Sent when another app requests a connection to your app. The value passed to `handler` is:
```js
+1 -1
View File
@@ -418,7 +418,7 @@ For long-lived mounts, sign in with a `-token` username and an API token as the
| ------------------------------------------------------------------ | ------------------------------- | ----------- |
| `nameAvailable` | 60/min | |
| App icon | 12,000/min | Per network |
| App landing page (`/app/<name>`, `/desktop/app/<name>`) | 600/min | Per network |
| App landing page (`/app/<name>`) | 600/min | Per network |
| Names per batch app lookup (`GET /apps/:names`, `POST /query/app`) | 200, up to 200 characters each | |
| `metadata` | 16 KiB, measured as JSON | |
| `filetypeAssociations` | 200 entries, 60 characters each | |
+1 -1
View File
@@ -144,7 +144,7 @@ try {
startServer(1);
app.get(['/', '/app/*splat', '/action/*splat', '/desktop', '/desktop/app/*splat', '/dashboard'], (req, res) => {
app.get(['/', '/app/*splat', '/action/*splat', '/dashboard'], (req, res) => {
res.send(generateDevHtml({
env: env,
api_origin: apiOrigin,
+2 -3
View File
@@ -424,15 +424,14 @@ export const authHeadHtml = (flow, title, { openerNotice = true } = {}) => {
};
/**
* On a cover page, the logo is a way out: desktop users stay on the desktop,
* everyone else goes to the root dashboard.
* On a cover page, the logo is a way out, to the root dashboard.
*
* @param {AuthFlow} flow
* @returns {string} Empty where the logo leads nowhere.
*/
const logoHref = (flow) => {
if ( ! flow.page || window.embedded_in_popup ) return '';
return window.location.pathname === '/desktop' ? '/desktop' : '/';
return '/';
};
/**
-61
View File
@@ -1,61 +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/>.
*/
const Component = use('util.Component');
/**
* Allows a flex layout of composed components to be
* treated as a component.
*/
export default def(class Flexer extends Component {
static ID = 'ui.component.Flexer';
static PROPERTIES = {
children: {},
gap: { value: '20pt' },
};
static CSS = `
:host > div {
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
`;
create_template ({ template }) {
// TODO: The way we handle loading assets doesn't work well
// with web components, so for now it goes in the template.
$(template).html(`
<div><slot name="inside"></slot></div>
`);
}
on_ready ({ listen }) {
for ( const child of this.get('children') ) {
child.setAttribute('slot', 'inside');
child.attach(this);
}
listen('gap', gap => {
$(this.dom_).find('div').first().css('gap', gap);
});
}
});
+3 -5
View File
@@ -204,8 +204,8 @@ async function UIDashboard (options) {
$item.addClass('active').attr('aria-current', 'page');
};
// Remove `?ref=...` from the URL, keeping the path and tab hash (mirrors
// UIDesktop). Replaced, not pushed, so Back leaves the dashboard.
// Remove `?ref=...` from the URL, keeping the path and tab hash.
// Replaced, not pushed, so Back leaves the dashboard.
if ( window.url_query_params?.has('ref') ) {
window.history.replaceState(null, document.title, window.location.pathname + window.location.hash);
}
@@ -272,7 +272,6 @@ async function UIDashboard (options) {
// =========================================================================
// Socket initialization
// In dashboard mode, UIDesktop is never loaded, so we create the socket here.
// This runs inside the function (not at module level) to ensure window.gui_origin
// and window.auth_token are already set.
// =========================================================================
@@ -367,8 +366,7 @@ async function UIDashboard (options) {
// =========================================================================
// Item event handlers
// Incremental DOM updates using UIDashboardFileItem for item creation and
// direct jQuery manipulation for removals/updates. Mirrors UIDesktop's
// approach but adapted for Dashboard's list-view structure.
// direct jQuery manipulation for removals/updates.
// =========================================================================
// A row taken away from elsewhere: keep the footer's count and size in
+55 -7
View File
@@ -672,10 +672,30 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
return created;
};
// Same runs as grant_access. Resolves with the refused items, each with
// its error, and rejects with the first when every item was refused. A
// run that fails otherwise (rate limit, network) ends it there, rejecting
// with that error and the count withdrawn before it as `withdrawn`.
const revoke_access = async (recipient, paths) => {
const failed = [];
let attempted = 0;
for ( const run of chunk(paths, MAX_ITEMS_PER_REQUEST) ) {
await puter.fs.unshare({ paths: run, recipient });
try {
const result = await puter.fs.unshare({ paths: run, recipient });
failed.push(...(result?.failed ?? []));
} catch (err) {
// Only a rejection for refused pairs lists them.
if ( ! Array.isArray(err?.failed) ) {
const withdrawn = attempted - failed.length;
if ( withdrawn && err && typeof err === 'object' ) err.withdrawn = withdrawn;
throw err;
}
failed.push(...err.failed);
}
attempted += run.length;
}
if ( failed.length >= paths.length ) throw failed[0];
return failed;
};
/**
@@ -685,6 +705,8 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
const set_link_access = async (mode, el_control) => {
$link_access.prop('disabled', true);
$link_mode.prop('disabled', true);
// Shown once the refresh settles, so its own notice can't replace it.
let outcome_error = null;
try {
if ( mode ) {
const created = await grant_access({ anyone: true }, mode, target_paths);
@@ -692,26 +714,37 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
link_state = { access: 'anyone', mode };
show_success(i18n(`share_link_on_${mode === 'write' ? 'write' : 'read'}${is_multi ? '_items' : ''}`));
} else {
await revoke_access({ anyone: true }, target_paths);
link_state = { access: 'restricted', mode: null };
show_success(i18n(is_multi ? 'share_link_off_items' : 'share_link_off'));
const failed = await revoke_access({ anyone: true }, target_paths);
if ( failed.length ) {
link_state = { access: 'mixed', mode: null };
outcome_error = `${i18n('share_link_off_partial', { count: total - failed.length, total })}. ${error_html(failed[0])}`;
} else {
link_state = { access: 'restricted', mode: null };
show_success(i18n(is_multi ? 'share_link_off_items' : 'share_link_off'));
}
}
} catch (err) {
// A plan gate gets the flow that clears it, where the deployment
// has one; a refusal is otherwise reported like any other.
if ( is_plan_gate_error(err) ) {
if ( ! open_upgrade_flow() ) show_error(i18n('share_link_requires_plan'));
if ( ! open_upgrade_flow() ) outcome_error = i18n('share_link_requires_plan');
} else if ( err?.withdrawn ) {
// Runs that landed before the failure closed the link all the same.
link_state = { access: 'mixed', mode: null };
outcome_error = `${i18n('share_link_off_partial', { count: err.withdrawn, total })}. ${error_html(err)}`;
} else {
show_error(error_html(err));
outcome_error = error_html(err);
}
} finally {
$link_access.prop('disabled', false);
$link_mode.prop('disabled', false);
}
if ( outcome_error ) show_error(outcome_error);
// The listings are the truth either way, and they put the control
// back; a selection too large to list keeps what was just applied.
invalidate_shared_roots();
await refresh();
if ( outcome_error ) show_error(outcome_error);
render_link_access();
if ( el_control && $(el_control).is(':visible') ) el_control.focus({ preventScroll: true });
else focus_dialog();
@@ -978,7 +1011,22 @@ export default function UIShareModal ({ items, path: item_path, name, owner, fse
const revoke_paths = group.pending ? group.pendingPaths : group.directPaths;
$(this).closest('.share-modal-row-confirm').find('button').prop('disabled', true);
try {
await revoke_access(recipient_of(group), revoke_paths);
const failed = await revoke_access(recipient_of(group), revoke_paths);
// Some items were refused: say how many went through, and stay
// open on what the listing now shows.
if ( failed.length ) {
invalidate_shared_roots();
await refresh();
// After the refresh: a refused item may not list any more,
// and that notice must not replace this one.
show_error(`${i18n('share_access_removed_partial', {
recipient: group.name,
count: revoke_paths.length - failed.length,
total: revoke_paths.length,
})}. ${error_html(failed[0])}`);
focus_list_control('.share-modal-row-mode', key) || focus_dialog();
return;
}
// Leaving takes away the access this list is read with, and the
// items may leave the listing behind it (the Shared view) too.
if ( ! group.teamUid && ! group.pending && group.name === window.user.username ) {
@@ -43,6 +43,7 @@ globalThis.def = globalThis.def ?? (value => value);
globalThis.use = globalThis.use ?? (() => class {});
const { default: UIShareModal } = await import('./UIShareModal.js');
const { unshareAnswering, allRefused, refusing } = await import('../../../tests/fixtures/sdkUnshare.js');
const settle = async () => {
for ( let i = 0; i < 5; i++ ) await new Promise(resolve => setTimeout(resolve, 0));
@@ -82,6 +83,126 @@ describe('UIShareModal general access', () => {
expect($('.share-modal-link-access').val()).toBe('restricted');
});
it('shows the error when closing the link is refused', async () => {
puter.fs.getShares = vi.fn(async () => [{ holder: null, anyone: true, mode: 'read', issuer: 'alice' }]);
puter.fs.unshare = unshareAnswering(allRefused);
UIShareModal({ path: '/alice/a.txt' });
await settle();
expect($('.share-modal-link-access').val()).toBe('anyone');
$('.share-modal-link-access').val('restricted').trigger('change');
await settle();
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe('Held through a team');
expect($('.share-modal-link-access').val()).toBe('anyone');
});
it('says how many items the link was closed on when some were refused', async () => {
puter.fs.getShares = vi.fn(async () => [{ holder: null, anyone: true, mode: 'read', issuer: 'alice' }]);
puter.fs.unshare = unshareAnswering((request) => refusing(
request,
(path) => path === '/alice/f1.txt',
{ code: 'forbidden', message: 'Not allowed' },
));
UIShareModal({ items: items(3) });
await settle();
$('.share-modal-link-access').val('restricted').trigger('change');
await settle();
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe(
'Only people with access can open 2 of 3 items now. Not allowed',
);
});
it('keeps the count on screen when a refused item no longer lists, closing the link', async () => {
let gone = false;
puter.fs.getShares = vi.fn(async (path) => {
if ( gone && path === '/alice/f1.txt' ) throw { message: 'Subject does not exist' };
return [{ holder: null, anyone: true, mode: 'read', issuer: 'alice' }];
});
puter.fs.unshare = unshareAnswering((request) => refusing(
request,
(path) => path === '/alice/f1.txt',
{ code: 'subject_does_not_exist', message: 'Subject does not exist' },
));
UIShareModal({ items: items(3) });
await settle();
gone = true;
$('.share-modal-link-access').val('restricted').trigger('change');
await settle();
expect($('.share-modal-status').text()).toBe(
'Only people with access can open 2 of 3 items now. Subject does not exist',
);
});
it('goes on past a run that was refused whole, and counts every refused item', async () => {
const requests = [];
// Runs of 50: the second is refused whole, the third loses one item.
puter.fs.unshare = unshareAnswering((request) => {
requests.push(request.items.length);
const run = requests.length;
return refusing(
request,
(path) => run === 2 || path === '/alice/f119.txt',
{ code: 'forbidden', message: 'Not allowed' },
);
});
UIShareModal({ items: items(120) });
await settle();
$('.share-modal-link-access').val('restricted').trigger('change');
await settle();
expect(requests).toEqual([50, 50, 20]);
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe(
'Only people with access can open 69 of 120 items now. Not allowed',
);
expect($('.share-modal-link-access')[0].value).toBe('mixed');
});
it('stops at a run the server turned away whole, and counts only what was closed before it', async () => {
const requests = [];
// Runs of 50: the second is rate limited, so the third is never sent.
puter.fs.unshare = unshareAnswering((request, xhr) => {
requests.push(request.items.length);
if ( requests.length === 2 ) {
xhr.status = 429;
return { message: 'Too many requests', code: 'too_many_requests' };
}
return refusing(request, () => false);
});
UIShareModal({ items: items(120) });
await settle();
$('.share-modal-link-access').val('restricted').trigger('change');
await settle();
expect(requests).toEqual([50, 50]);
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe(
'Only people with access can open 50 of 120 items now. Too many requests',
);
expect($('.share-modal-link-access')[0].value).toBe('mixed');
});
it('reports a failed request as it is, with no item counted as refused', async () => {
const requests = [];
puter.fs.unshare = unshareAnswering((request, xhr) => {
requests.push(request.items.length);
xhr.status = 429;
return { message: 'Too many requests', code: 'too_many_requests' };
});
UIShareModal({ items: items(120) });
await settle();
$('.share-modal-link-access').val('restricted').trigger('change');
await settle();
expect(requests).toEqual([50]);
expect($('.share-modal-status').text()).toBe('Too many requests');
expect($('.share-modal-link-access')[0].value).toBe('unchecked');
});
it('shows a listed selection as the listings say', async () => {
UIShareModal({ items: items(2) });
await settle();
@@ -154,6 +275,67 @@ describe('UIShareModal removing access', () => {
expect(puter.fs.unshare).toHaveBeenCalledWith({ paths: ['/alice/a.txt'], recipient: 'bob' });
});
it('keeps the row and shows the error when the removal is refused', async () => {
puter.fs.getShares = vi.fn(async () => [{ holder: 'bob', mode: 'read', issuer: 'alice' }]);
puter.fs.unshare = unshareAnswering(allRefused);
UIShareModal({ path: '/alice/a.txt' });
await settle();
$('.share-modal-row-mode').val('__remove').trigger('change');
$('.share-modal-confirm-remove').trigger('click');
await settle();
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe('Held through a team');
expect($('.share-modal-row-mode').attr('data-key')).toBeTruthy();
expect($('.share-modal-row-mode').val()).toBe('read');
});
it('says how many items a person was removed from when one was refused', async () => {
puter.fs.getShares = vi.fn(async () => [{ holder: 'bob', mode: 'read', issuer: 'alice' }]);
puter.fs.unshare = unshareAnswering((request) => refusing(
request,
(path) => path === '/alice/f2.txt',
{ code: 'forbidden', message: 'Not allowed' },
));
UIShareModal({ items: [0, 1, 2].map((i) => ({ path: `/alice/f${i}.txt` })) });
await settle();
$('.share-modal-row-mode').val('__remove').trigger('change');
$('.share-modal-confirm-remove').trigger('click');
await settle();
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe('Removed bob from 2 of 3 items. Not allowed');
expect($('.share-modal-row-mode').length).toBe(1);
});
it('keeps the count on screen when a refused item no longer lists', async () => {
let removed = false;
puter.fs.getShares = vi.fn(async (path) => {
if ( removed && path === '/alice/f2.txt' ) throw { message: 'Subject does not exist' };
return removed ? [] : [{ holder: 'bob', mode: 'read', issuer: 'alice' }];
});
const answering = unshareAnswering((request) => refusing(
request,
(path) => path === '/alice/f2.txt',
{ code: 'subject_does_not_exist', message: 'Subject does not exist' },
));
puter.fs.unshare = async (...args) => {
removed = true;
return answering(...args);
};
UIShareModal({ items: [0, 1, 2].map((i) => ({ path: `/alice/f${i}.txt` })) });
await settle();
$('.share-modal-row-mode').val('__remove').trigger('change');
$('.share-modal-confirm-remove').trigger('click');
await settle();
expect($('.share-modal-status').hasClass('share-modal-status-error')).toBe(true);
expect($('.share-modal-status').text()).toBe(
'Removed bob from 2 of 3 items. Subject does not exist',
);
expect($('.share-modal-row-mode').length).toBe(0);
});
it('offers cancelling an invitation from its menu', async () => {
puter.fs.getShares = vi.fn(async () => [
{ holder: null, recipientEmail: '[email protected]', pending: true, mode: 'write', issuer: 'alice' },
-47
View File
@@ -1,47 +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 UIWindow from './UIWindow.js';
import Placeholder from '../util/Placeholder.js';
import JustHTML from './Components/JustHTML.js';
/**
* @typedef {Object} UIComponentWindowOptions
* @property {Component} [component] A component to render in the window
* @property {string} [html] HTML string to render in the window (uses JustHTML component)
*/
/**
* Render a UIWindow that contains an instance of Component or HTML string
* @param {UIComponentWindowOptions} options
*/
export default async function UIComponentWindow (options) {
const component = options.component ?? new JustHTML({ html: options.html ?? '' });
const placeholder = Placeholder();
const win = await UIWindow({
...options,
body_content: placeholder.html,
});
component.attach(placeholder);
component.focus();
return win;
}
File diff suppressed because it is too large. Load diff
+6 -54
View File
@@ -25,7 +25,6 @@ import path from '../lib/path.js';
import truncate_filename from '../helpers/truncateFilename.js';
import launch_app from '../helpers/launchApp.js';
import open_item from '../helpers/openItem.js';
import publish_as_website from '../helpers/publishAsWebsite.js';
import { isWeblinkName, weblinkChangeIconMenuItem } from '../helpers/weblink.js';
import { is_owned_by_me } from '../helpers/pathOwner.js';
import { can_rename, can_restructure, invalidate_shared_roots } from '../helpers/sharedAccess.js';
@@ -235,17 +234,6 @@ async function UIItem (options) {
window.update_explorer_footer_item_count(el_window);
}
// manual positioning
if ( !window.is_auto_arrange_enabled &&
options.position &&
// item is on the desktop (must be desktop itself and not a window, hence the '.desktop' class check)
$(el_item).closest('.item-container.desktop').attr('data-path') === window.desktop_path
) {
el_item.style.position = 'absolute';
el_item.style.left = `${options.position.left }px`;
el_item.style.top = `${options.position.top }px`;
}
// --------------------------------------------------------
// Dragster
// allow dragging of local files on this window, if it's is_dir
@@ -330,8 +318,8 @@ async function UIItem (options) {
// Constrain item within desktop bounds
const minLeft = -50;
const maxLeft = window.desktop_width - 50;
const minTop = window.toolbar_height;
const maxTop = window.desktop_height + window.toolbar_height;
const minTop = 0;
const maxTop = window.desktop_height;
// Apply constraints to ui.position
ui.position.left = Math.max(minLeft, Math.min(maxLeft, ui.position.left));
@@ -410,21 +398,6 @@ async function UIItem (options) {
}
},
stop: function (event, ui) {
// Allow rearranging only if item is on desktop, not trash container, auto arrange is disabled and item is not dropped into another item
// the desktop itself, not a window showing the Desktop folder
if ( $(el_item).closest('.item-container').hasClass('desktop') &&
!window.is_auto_arrange_enabled && $(el_item).attr('data-path') !== window.trash_path && !ui.helper.data('dropped') &&
// .desktop clips its overflow, so the whole item has to fit above the bottom edge
window.mouseover_window === undefined && ui.position.top + $(el_item).outerHeight(true) <= window.desktop_height ) {
el_item.style.position = 'absolute';
el_item.style.left = `${ui.position.left }px`;
el_item.style.top = `${ui.position.top }px`;
$('.ui-draggable-dragging').remove();
window.desktop_item_positions[$(el_item).attr('data-uid')] = ui.position;
window.save_desktop_item_positions();
}
$('.item-selected-clone').remove();
$('.draggable-count-badge').remove();
// re-enable all droppable UIItems that are not a dir
@@ -547,11 +520,6 @@ async function UIItem (options) {
else if ( options.is_dir ) {
// a selected folder can be the drop target of its own selection; it stays where it is
const items_to_drop = items_to_move.filter(item => $(item).attr('data-uid') !== $(el_item).attr('data-uid'));
if ( $(el_item).closest('.item-container').attr('data-path') === window.desktop_path ) {
// the items leaving the desktop lose their saved positions, not the folder they land in
items_to_drop.forEach(item => delete window.desktop_item_positions[$(item).attr('data-uid')]);
window.save_desktop_item_positions();
}
window.move_items(items_to_drop, $(el_item).attr('data-shortcut_to_path') !== '' ? $(el_item).attr('data-shortcut_to_path') : $(el_item).attr('data-path'));
}
}
@@ -1242,23 +1210,6 @@ async function UIItem (options) {
}
}
// -------------------------------------------
// Publish As Website
// -------------------------------------------
if ( !is_trashed && !is_trash && options.is_dir ) {
menu_items.push({
html: i18n('publish_as_website'),
disabled: !options.is_dir,
onClick: async function () {
await publish_as_website({
uid: options.uid,
name: $(el_item).attr('data-name'),
path: $(el_item).attr('data-path'),
});
},
});
}
// -------------------------------------------
// Deploy As App
// -------------------------------------------
if ( !is_trashed && !is_trash && options.is_dir ) {
@@ -1466,10 +1417,11 @@ async function UIItem (options) {
html: i18n('share_remove_from_shared'),
onClick: async function () {
try {
await puter.fs.unshare(
const left = await puter.fs.unshare(
$(el_item).attr('data-path'),
window.user.username,
);
if ( left?.failed?.length ) throw left.failed[0];
// Or mode lookups keep answering for a share we
// just walked away from.
invalidate_shared_roots();
@@ -1554,7 +1506,7 @@ async function UIItem (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = $(el_item).position().top + $(el_item).height();
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - window_height) ? (window.innerHeight - window_height) : top;
UIWindowItemProperties(
$(el_item).attr('data-name'),
@@ -1571,7 +1523,7 @@ async function UIItem (options) {
// Create ContextMenu
UIContextMenu({
parent_element: ($(options.appendTo).hasClass('desktop') ? undefined : options.appendTo),
parent_element: options.appendTo,
position: menu_position,
items: menu_items,
});
+48 -48
View File
@@ -29,7 +29,6 @@ vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
vi.mock('./UIAlert.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/openItem.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/publishAsWebsite.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/openWithAI.js', () => ({ default: vi.fn() }));
vi.mock('../helpers/refreshItemContainer.js', () => ({ default: vi.fn() }));
@@ -66,10 +65,13 @@ Object.assign(window, {
const { default: UIItem } = await import('./UIItem.js');
const { default: UIContextMenu } = await import('./UIContextMenu.js');
const { default: UIAlert } = await import('./UIAlert.js');
const { unshareAnswering, allRefused, goneRefused } =
await import('../../tests/fixtures/sdkUnshare.js');
const { default: refresh_item_container } =
await import('../helpers/refreshItemContainer.js');
const menuLabels = async (options) => {
const menuItems = async (options) => {
document.body.innerHTML =
'<div class="window"><div class="item-container"></div></div>';
await UIItem({
@@ -88,9 +90,12 @@ const menuLabels = async (options) => {
UIContextMenu.mockClear();
$('.item').trigger('contextmenu');
await vi.waitFor(() => expect(UIContextMenu).toHaveBeenCalled());
return UIContextMenu.mock.calls[0][0].items.map((item) => item?.html);
return UIContextMenu.mock.calls[0][0].items;
};
const menuLabels = async (options) =>
(await menuItems(options)).map((item) => item?.html);
const removeFromShared = async (options) => {
await menuLabels(options);
await UIContextMenu.mock.calls[0][0].items
@@ -110,6 +115,7 @@ describe('UIItem Remove from Shared', () => {
};
globalThis.puter = window.puter;
refresh_item_container.mockClear();
UIAlert.mockClear();
});
it('is offered on an item shared with the user directly', async () => {
@@ -122,6 +128,29 @@ describe('UIItem Remove from Shared', () => {
expect(labels).not.toContain('share_remove_from_shared');
});
it('keeps the item and shows the error when leaving is refused', async () => {
puter.fs.unshare = unshareAnswering(allRefused);
const items = await menuItems({});
await items
.find((item) => item?.html === 'share_remove_from_shared')
.onClick();
expect(UIAlert).toHaveBeenCalledWith({
message: 'Held through a team',
});
expect($('.item').length).toBe(1);
});
it('keeps the item and shows why when the unshare resolves with the pair refused', async () => {
puter.fs.unshare = unshareAnswering(goneRefused);
await removeFromShared({});
expect(UIAlert).toHaveBeenCalledWith({
message: 'Subject does not exist',
});
expect($('.item').length).toBe(1);
});
it('takes the item away once the user has left it', async () => {
await removeFromShared({});
expect(puter.fs.unshare).toHaveBeenCalledWith('/bob/u-1/Photos', 'alice');
@@ -176,52 +205,23 @@ describe('UIItem Publish as Worker', () => {
});
});
describe('UIItem dropped on the desktop', () => {
let stop;
describe('UIItem Publish as Website', () => {
beforeEach(() => {
window.user = { username: 'alice' };
window.trash_path = '/alice/Trash';
});
beforeEach(async () => {
document.body.innerHTML = '<div class="item-container desktop"></div>';
Object.assign(window, {
user: { username: 'alice' },
trash_path: '/alice/Trash',
desktop_height: 800,
is_auto_arrange_enabled: false,
mouseover_window: undefined,
desktop_item_positions: {},
save_desktop_item_positions: vi.fn(),
it('is not offered, even on a folder the user owns', async () => {
const labels = await menuLabels({
path: '/alice/Site',
name: 'Site',
is_dir: true,
owner: 'alice',
shared_with_me: false,
share_mode: undefined,
shared_by: undefined,
});
const draggable = jQuery.fn.draggable;
jQuery.fn.draggable = function (options) {
if ( typeof options === 'object' ) stop = options.stop;
return this;
};
try {
await UIItem({
appendTo: $('.item-container'),
uid: 'u-2',
path: '/alice/Desktop/Notes',
name: 'Notes',
is_dir: true,
icon: { image: '', type: 'icon' },
});
} finally {
jQuery.fn.draggable = draggable;
}
// jsdom has no stylesheet, so give the item the size style.css does.
$('.item').css({ height: '70px', margin: '15px 5px 30px 5px' });
});
const dropAt = (top) => stop({}, { position: { top, left: 300 }, helper: $('<div>') });
it('moves there when the whole item fits on screen', () => {
dropAt(685);
expect($('.item')[0].style.top).toBe('685px');
expect(window.save_desktop_item_positions).toHaveBeenCalledTimes(1);
});
it('stays put when the item would hang off the bottom edge', () => {
dropAt(735);
expect($('.item')[0].style.top).toBe('');
expect(window.save_desktop_item_positions).not.toHaveBeenCalled();
expect(labels).not.toContain('publish_as_website');
expect(labels).toContain('deploy_as_app');
});
});
-15
View File
@@ -82,21 +82,6 @@ function UIQRCode (options) {
}
}
// Compatibility shim: Component-based containers (e.g. Flexer) call
// `.attach(parent)` on their children. Returning a plain DOM element with
// an `attach` method lets this work without making UIQRCode a Component.
el.attach = function (destination) {
if ( destination instanceof HTMLElement || destination instanceof ShadowRoot ) {
destination.appendChild(el);
return;
}
if ( destination && destination.$ === 'placeholder' ) {
destination.replaceWith(el);
return;
}
throw new Error(`Unknown destination type: ${destination}`);
};
return el;
}
+1 -2
View File
@@ -51,13 +51,12 @@ const headMenuLabels = (el_window) => {
};
beforeEach(() => {
document.body.innerHTML = '<div class="desktop"></div>';
document.body.innerHTML = '';
Object.assign(window, {
global_element_id: 0,
window_counter: 0,
last_window_zindex: 1,
window_stack: [],
toolbar_height: 0,
icons: {},
uuidv4: () => crypto.randomUUID(),
is_dashboard_mode: false,
+36 -348
View File
@@ -28,7 +28,6 @@ import { atPath } from '../helpers/pathElements.js';
import { resolve_typed_path } from '../helpers/expandHomePath.js';
import UIWindowAppFeedback from './UIWindowAppFeedback.js';
import launch_app from '../helpers/launchApp.js';
import publish_as_website from '../helpers/publishAsWebsite.js';
import item_icon from '../helpers/itemIcon.js';
import { parent_path_for, shared_crumbs_for } from '../helpers/sharePaths.js';
@@ -36,7 +35,6 @@ import { has_shared_roots } from '../helpers/sharedAccess.js';
import { is_window_hidden, is_unseen_background_window, user_facing_windows } from '../helpers/windowVisibility.js';
const el_body = document.getElementsByTagName('body')[0];
const SNAP_PLACEHOLDER_DELAY_MS = 600; // delay before showing placeholder in any snap zone
// Above any z-index an ordinary desktop window reaches in practice.
const DESKTOP_BACKDROP_MIN_ZINDEX = 99999;
@@ -178,9 +176,9 @@ async function UIWindow (options) {
if ( isMobile.phone && !options.center && !options.dominant ) {
options.left = 0;
options.top = `${window.toolbar_height }px`;
options.top = 0;
options.width = '100%';
options.height = `calc(100% - ${ window.toolbar_height }px)`;
options.height = '100%';
} else {
options.width += 'px';
options.height += 'px';
@@ -1671,12 +1669,6 @@ async function UIWindow (options) {
});
}
$(el_window_head).mousedown(function () {
if ( window_is_snapped ) {
$(el_window).draggable( 'option', 'cursorAt', { left: width_before_snap / 2 });
}
});
// --------------------------------------------------------
// Click On The `Scale` Button
// (the little rectangle in the window head)
@@ -1772,147 +1764,10 @@ async function UIWindow (options) {
// --------------------------------------------------------
// Draggable
// --------------------------------------------------------
let width_before_snap = 0;
let height_before_snap = 0;
let window_is_snapped = false;
let snap_placeholder_active = false;
let snap_trigger_timeout;
let last_snap_zone;
if ( options.is_draggable ) {
let window_snap_placeholder = $(`<div class="window-snap-placeholder animate__animated animate__zoomIn animate__faster">
<div class="window-snap-placeholder-inner"></div>
</div>`);
const showSnapPlaceholder = (zone) => {
if ( window_is_snapped || !zone ) {
return false;
}
const snapDims = getSnapDimensions();
let css = null;
if ( zone === 'w' ) {
css = {
'display': 'block',
'width': snapDims.available_width / 2,
'height': snapDims.available_height,
'top': snapDims.start_y,
'left': snapDims.start_x,
'z-index': window.last_window_zindex - 1,
};
} else if ( zone === 'nw' ) {
css = {
'display': 'block',
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
'top': snapDims.start_y,
'left': snapDims.start_x,
'z-index': window.last_window_zindex - 1,
};
} else if ( zone === 'ne' ) {
css = {
'display': 'block',
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
'top': snapDims.start_y,
'left': snapDims.start_x + snapDims.available_width / 2,
'z-index': window.last_window_zindex - 1,
};
} else if ( zone === 'e' ) {
css = {
'display': 'block',
'width': snapDims.available_width / 2,
'height': snapDims.available_height,
'top': snapDims.start_y,
'left': snapDims.start_x + snapDims.available_width / 2,
'z-index': window.last_window_zindex - 1,
};
} else if ( zone === 'n' ) {
css = {
'display': 'block',
'width': snapDims.available_width,
'height': snapDims.available_height,
'top': snapDims.start_y,
'left': snapDims.start_x,
'z-index': window.last_window_zindex - 1,
};
} else if ( zone === 'sw' ) {
css = {
'display': 'block',
'top': snapDims.start_y + snapDims.available_height / 2,
'left': snapDims.start_x,
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
'z-index': window.last_window_zindex - 1,
};
} else if ( zone === 'se' ) {
css = {
'display': 'block',
'top': snapDims.start_y + snapDims.available_height / 2,
'left': snapDims.start_x + snapDims.available_width / 2,
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
'z-index': window.last_window_zindex - 1,
};
}
if ( ! css ) {
return false;
}
window_snap_placeholder.css(css);
if ( ! snap_placeholder_active ) {
snap_placeholder_active = true;
$(el_body).append(window_snap_placeholder);
}
width_before_snap = $(el_window).width();
height_before_snap = $(el_window).height();
return true;
};
const hideSnapPlaceholder = () => {
if ( snap_placeholder_active ) {
snap_placeholder_active = false;
window_snap_placeholder.fadeOut(80);
}
};
$(el_window).draggable({
start: function (e, ui) {
window.a_window_is_being_dragged = true;
last_snap_zone = undefined;
if ( snap_trigger_timeout ) {
clearTimeout(snap_trigger_timeout);
snap_trigger_timeout = undefined;
}
hideSnapPlaceholder();
// if window is snapped, unsnap it and reset its position to where it was before snapping
if ( options.is_resizable && window_is_snapped ) {
window_is_snapped = false;
$(el_window).css({
'width': width_before_snap,
'height': `${height_before_snap }px`,
});
// if at any point the window's width is "too small", hide the sidebar
if ( $(el_window).width() < window.window_width_threshold_for_sidebar ) {
if ( width_before_snap >= window.window_width_threshold_for_sidebar && !sidebar_hidden ) {
$(el_window_sidebar).hide();
}
sidebar_hidden = true;
}
// if at any point the window's width is "big enough", show the sidebar
else if ( $(el_window).width() >= window.window_width_threshold_for_sidebar ) {
if ( sidebar_hidden ) {
$(el_window_sidebar).show();
}
sidebar_hidden = false;
}
}
$(el_window).addClass('window-dragging');
// rm window from original_window_position
@@ -1930,50 +1785,9 @@ async function UIWindow (options) {
// maximize icon
$(el_window_head_scale_btn).find('img').attr('src', window.icons['scale.svg']);
}
// --------------------------------------------------------
// Snap to screen edges
// --------------------------------------------------------
if ( options.is_resizable ) {
const activeZone = window.current_active_snap_zone;
if ( activeZone !== last_snap_zone ) {
if ( snap_trigger_timeout ) {
clearTimeout(snap_trigger_timeout);
snap_trigger_timeout = undefined;
}
hideSnapPlaceholder();
last_snap_zone = activeZone;
if ( activeZone ) {
const scheduledZone = activeZone;
snap_trigger_timeout = setTimeout(function () {
snap_trigger_timeout = undefined;
if ( ! $(el_window).hasClass('window-dragging') ) {
return;
}
if ( window.current_active_snap_zone !== scheduledZone ) {
return;
}
showSnapPlaceholder(scheduledZone);
}, SNAP_PLACEHOLDER_DELAY_MS);
}
}
if ( ! activeZone ) {
hideSnapPlaceholder();
}
}
},
stop: function () {
window.a_window_is_being_dragged = false;
if ( snap_trigger_timeout ) {
clearTimeout(snap_trigger_timeout);
snap_trigger_timeout = undefined;
}
last_snap_zone = undefined;
let window_will_snap = false;
$(el_window).draggable( 'option', 'cursorAt', false);
$(el_window).removeClass('window-dragging');
$(el_window).attr({
@@ -1984,114 +1798,24 @@ async function UIWindow (options) {
$(el_window_app_iframe).css('pointer-events', 'all');
$('.window').css('pointer-events', 'initial');
if ( options.is_resizable && snap_placeholder_active && !window_is_snapped ) {
window_will_snap = true;
$(window_snap_placeholder).css('padding', 0);
setTimeout(function () {
const snapDims = getSnapDimensions();
// snap to w
if ( window.current_active_snap_zone === 'w' ) {
$(el_window).css({
'top': snapDims.start_y,
'left': snapDims.start_x,
'width': snapDims.available_width / 2,
'height': snapDims.available_height - 6,
});
}
// snap to nw
else if ( window.current_active_snap_zone === 'nw' ) {
$(el_window).css({
'top': snapDims.start_y,
'left': snapDims.start_x,
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
});
}
// snap to ne
else if ( window.current_active_snap_zone === 'ne' ) {
$(el_window).css({
'top': snapDims.start_y,
'left': snapDims.start_x + snapDims.available_width / 2,
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
});
}
// snap to sw
else if ( window.current_active_snap_zone === 'sw' ) {
$(el_window).css({
'top': snapDims.start_y + snapDims.available_height / 2,
'left': snapDims.start_x,
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
});
}
// snap to se
else if ( window.current_active_snap_zone === 'se' ) {
$(el_window).css({
'top': snapDims.start_y + snapDims.available_height / 2,
'left': snapDims.start_x + snapDims.available_width / 2,
'width': snapDims.available_width / 2,
'height': snapDims.available_height / 2,
});
}
// snap to e
else if ( window.current_active_snap_zone === 'e' ) {
$(el_window).css({
'top': snapDims.start_y,
'left': snapDims.start_x + snapDims.available_width / 2,
'width': snapDims.available_width / 2,
'height': snapDims.available_height - 6,
});
}
// snap to n
else if ( window.current_active_snap_zone === 'n' ) {
window.scale_window(el_window);
}
// snap placeholder is no longer active
snap_placeholder_active = false;
// hide snap placeholder
window_snap_placeholder.css('display', 'none');
window_snap_placeholder.css('padding', '10px');
// mark window as snapped
window_is_snapped = true;
// if at any point the window's width is "too small", hide the sidebar
if ( $(el_window).width() < window.window_width_threshold_for_sidebar ) {
if ( width_before_snap >= window.window_width_threshold_for_sidebar && !sidebar_hidden ) {
$(el_window_sidebar).hide();
}
sidebar_hidden = true;
}
// if at any point the window's width is "big enough", show the sidebar
else if ( $(el_window).width() >= window.window_width_threshold_for_sidebar ) {
if ( sidebar_hidden ) {
$(el_window_sidebar).show();
}
sidebar_hidden = false;
}
}, 100);
}
// if window is dropped outside the available area, move it back in
// the '- 30' is to account for the window head
const maxTop = window.innerHeight - 30;
if ( $(el_window).position().top > maxTop && !window_will_snap ) {
if ( $(el_window).position().top > maxTop ) {
$(el_window).animate({
top: maxTop - 30,
}, 100);
}
// if window is dropped too far to the right, move it left
const maxLeft = window.innerWidth - 50;
if ( $(el_window).position().left > maxLeft && !window_will_snap ) {
if ( $(el_window).position().left > maxLeft ) {
$(el_window).animate({
left: maxLeft,
}, 100);
}
// if window is dropped too far to the left, move it right
const minLeft = -$(el_window).width() + 150;
if ( $(el_window).position().left < minLeft && !window_will_snap ) {
if ( $(el_window).position().left < minLeft ) {
$(el_window).animate({
left: minLeft,
}, 100);
@@ -2107,7 +1831,6 @@ async function UIWindow (options) {
// document mousedown -> focusWindow path, which fires before any
// drag starts.
scroll: false,
containment: '.window-container',
});
}
@@ -2146,10 +1869,10 @@ async function UIWindow (options) {
}
// when resizing the top of the window, make sure the window head is not hidden behind the toolbar
if ( $(el_window).position().top < window.toolbar_height ) {
var difference = window.toolbar_height - $(el_window).position().top;
if ( $(el_window).position().top < 0 ) {
var difference = -$(el_window).position().top;
$(el_window).css({
'top': window.toolbar_height,
'top': 0,
'height': ui.size.height - difference, // Reduce the height by the difference
});
// don't resize
@@ -2216,10 +1939,9 @@ async function UIWindow (options) {
return;
}
const snap_dims = getSnapDimensions();
const head_height = options.has_head ? $(el_window_head).outerHeight() : 0;
const max_body_width = snap_dims.available_width;
const max_body_height = Math.max(0, snap_dims.available_height - head_height);
const max_body_width = window.innerWidth;
const max_body_height = Math.max(0, window.innerHeight - head_height);
if ( max_body_width <= 0 || max_body_height <= 0 ) {
return;
@@ -2238,8 +1960,8 @@ async function UIWindow (options) {
const window_width = Math.max(1, Math.floor(body_width));
const window_height = Math.max(1, Math.floor(body_height + head_height));
const left = snap_dims.start_x + Math.max(0, (snap_dims.available_width - window_width) / 2);
const top = snap_dims.start_y + Math.max(0, (snap_dims.available_height - window_height) / 2);
const left = Math.max(0, (window.innerWidth - window_width) / 2);
const top = Math.max(0, (window.innerHeight - window_height) / 2);
$(el_window).css({
width: `${window_width}px`,
@@ -2268,7 +1990,6 @@ async function UIWindow (options) {
'data-is_maximized': '0',
});
$(el_window_head_scale_btn).find('img').attr('src', window.icons['scale.svg']);
window_is_snapped = false;
};
// --------------------------------------------------------
// Head Context Menu
@@ -2544,20 +2265,6 @@ async function UIWindow (options) {
// -------------------------------------------
menu_items.push('-');
// -------------------------------------------
// Publish As Website
// -------------------------------------------
menu_items.push({
html: i18n('publish_as_website'),
disabled: !options.is_dir,
onClick: async function () {
await publish_as_website({
uid: $(el_window).attr('data-uid'),
name: $(el_window).attr('data-name'),
path: $(el_window).attr('data-path'),
});
},
});
// -------------------------------------------
// Deploy as App
// -------------------------------------------
menu_items.push({
@@ -2592,7 +2299,7 @@ async function UIWindow (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = window.mouseY;
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - window_height) ? (window.innerHeight - window_height) : top;
UIWindowItemProperties(
options.title,
@@ -2770,7 +2477,15 @@ async function UIWindow (options) {
if ( options.is_fullpage ) {
$(el_window).hide();
setTimeout(function () {
window.enter_fullpage_mode(el_window);
$(el_window).find('.window-head').hide();
$('body').addClass('fullpage-mode');
$(el_window).css({
width: '100%',
height: '100%',
top: 0,
left: 0,
'border-radius': 0,
});
$(el_window).show();
}, 50);
}
@@ -2894,10 +2609,10 @@ $(document).on('dblclick', '.window .ui-resizable-handle', function (e) {
// top
else if ( $(this).hasClass('ui-resizable-n') ) {
let height = $(el_window).height() + $(el_window).position().top - window.toolbar_height;
let height = $(el_window).height() + $(el_window).position().top;
$(el_window).css({
height: height,
top: window.toolbar_height,
top: 0,
});
}
// right
@@ -2937,21 +2652,21 @@ $(document).on('dblclick', '.window .ui-resizable-handle', function (e) {
// top right
else if ( $(this).hasClass('ui-resizable-ne') ) {
let width = window.innerWidth - $(el_window).position().left;
let height = $(el_window).height() + $(el_window).position().top - window.toolbar_height;
let height = $(el_window).height() + $(el_window).position().top;
$(el_window).css({
width: width,
height: height,
top: window.toolbar_height,
top: 0,
});
}
// top left
else if ( $(this).hasClass('ui-resizable-nw') ) {
let width = $(el_window).width() + $(el_window).position().left;
let height = $(el_window).height() + $(el_window).position().top - window.toolbar_height;
let height = $(el_window).height() + $(el_window).position().top;
$(el_window).css({
width: width,
height: height,
top: window.toolbar_height,
top: 0,
left: 0,
});
}
@@ -3584,9 +3299,8 @@ $.fn.close = async function (options) {
let window_uuid = $(this).attr('data-element_uuid');
// remove all instances of win_id from window.window_stack
window.window_stack = window.window_stack.filter(id => id !== win_id);
// if a fullpage window is closed, show the desktop
if ( $(this).attr('data-is_fullpage') === '1' ) {
window.exit_fullpage_mode();
$('body').removeClass('fullpage-mode');
}
// FileDialog closed
@@ -3666,9 +3380,6 @@ $.fn.close = async function (options) {
// remove backdrop
$(this).closest('.window-backdrop').remove();
// remove global menubars
$(`.window-menubar-global[data-window-id="${win_id}"]`).remove();
// remove DOM element
if ( options?.shrink_to_target ) {
// get target location
@@ -3707,9 +3418,7 @@ $.fn.close = async function (options) {
document.activeElement.blur();
$('input').blur();
}
// focus back to desktop
$('.desktop').find('.item-blurred').removeClass('item-blurred');
window.active_item_container = $('.desktop.item-container').get(0);
window.active_item_container = null;
}
});
@@ -3990,12 +3699,6 @@ $.fn.showWindow = async function (options) {
};
window.toggle_empty_folder_message = function (el_item_container) {
// if the item container is the desktop, don't show/hide the empty message
if ( $(el_item_container).hasClass('desktop') )
{
return;
}
// if the item container is empty, show the empty message
if ( $(el_item_container).has('.item').length === 0 ) {
$(el_item_container).find('.explorer-empty-message').show();
@@ -4061,11 +3764,6 @@ $.fn.focusWindow = function (event) {
});
}
// hide other global menubars
$('.window-menubar-global').not(`.window-menubar-global[data-window-id="${win_id}"]`).hide();
// show this window's global menubar
$(`.window-menubar-global[data-window-id="${win_id}"]`).show();
// if a menubar or any of its items are clicked, don't focus the iframe. This is important to preserve the focus on the menubar
// and to enable keyboard navigation through the menubar items
if ( $(event?.target).hasClass('window-menubar') || $(event?.target).closest('.window-menubar').length > 0 ) {
@@ -4096,8 +3794,8 @@ $.fn.focusWindow = function (event) {
// remove blurred class from items on this window
$(window.active_item_container).find('.item-blurred').removeClass('item-blurred');
// Update the tab title to the focused window. The URL itself is
// deliberately NOT touched here: on the desktop it stays /desktop
// (apps don't rewrite it), and in dashboard mode the open app owns
// deliberately NOT touched here: on the desktop apps don't rewrite
// it, and in dashboard mode the open app owns
// it through real history entries (push_dashboard_app_url).
if ( ! window.is_dashboard_mode ) {
const update_window_url = $(this).attr('data-update_window_url');
@@ -4107,7 +3805,6 @@ $.fn.focusWindow = function (event) {
}
} else {
$('.window').find('.item-selected').addClass('item-blurred');
$('.desktop').find('.item-blurred').removeClass('item-blurred');
}
return this;
@@ -5391,29 +5088,20 @@ async function saveSidebarOrder (order) {
window.update_maximized_window = function (el_window) {
if ( window.is_fullpage_mode ) {
$(el_window).css({
'top': `${window.toolbar_height }px`,
'top': 0,
'left': '0',
'width': '100%',
'height': `calc(100% - ${window.toolbar_height}px)`,
'height': '100%',
});
return;
}
$(el_window).css({
'top': `${window.toolbar_height }px`,
'top': 0,
'left': '0',
'width': '100%',
'height': `${window.innerHeight - window.toolbar_height - 6 }px`,
'height': `${window.innerHeight - 6 }px`,
});
};
function getSnapDimensions () {
return {
available_width: window.innerWidth,
available_height: window.innerHeight - window.toolbar_height,
start_x: 0,
start_y: window.toolbar_height,
};
}
export default UIWindow;
-136
View File
@@ -1,136 +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 UIWindow from './UIWindow.js';
import { underPath } from '../helpers/pathElements.js';
async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_dir_path) {
let h = '';
h += '<div class="window-publishWebsite-content" style="padding: 20px; border-bottom: 1px solid #ced7e1;">';
// success
h += '<div class="window-publishWebsite-success">';
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:80px; height:80px; display: block; margin:10px auto;">`;
h += `<p style="text-align:center;">${i18n('dir_published_as_website', `<strong>${html_encode(target_dir_name)}</strong>`, false)}<p>`;
h += `<p style="text-align:center;"><a class="publishWebsite-published-link" target="_blank"></a><img class="publishWebsite-published-link-icon" src="${html_encode(window.icons['launch.svg'])}"></p>`;
h += `<button class="button button-normal button-block button-primary publish-window-ok-btn" style="margin-top:20px;">${i18n('ok')}</button>`;
h += '</div>';
// form
h += '<form class="window-publishWebsite-form">';
// error msg
h += '<div class="publish-website-error-msg"></div>';
// Subdomain input
h += '<div class="puter-subdomain-section" style="overflow: hidden; margin-bottom: 20px;">';
h += `<label style="margin-bottom: 10px; display: block;">${i18n('pick_name_for_website')}</label>`;
h += '<div style="font-family: monospace; display: flex; align-items: center; background: #f8f9fa; padding: 8px; border-radius: 6px; border: 1px solid #dee2e6;">';
h += `<span style="color: #666;">${html_encode(window.extractProtocol(window.url))}://</span>`;
h += '<input class="publish-website-subdomain" style="border: none; background: #ffffff; outline: none; padding: 7px !important; " type="text" autocomplete="subdomain" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>';
h += `<span style="color: #666;">.${html_encode(window.hosting_domain)}</span>`;
h += '</div>';
h += '</div>';
// uid
h += `<input class="publishWebsiteTargetDirUID" type="hidden" value="${html_encode(target_dir_uid)}"/>`;
// Publish
h += `<button class="publish-btn button button-action button-block button-normal">${i18n('publish')}</button>`;
h += '</form>';
h += '</div>';
const el_window = await UIWindow({
title: i18n('window_title_publish_website'),
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 450,
dominant: true,
onAppend: function (this_window) {
$(this_window).find('.publish-website-subdomain').val(window.generate_identifier());
$(this_window).find('.publish-website-subdomain').get(0).focus({ preventScroll: true });
},
window_class: 'window-publishWebsite',
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
},
});
$(el_window).find('.publish-btn').on('click', async function (e) {
e.preventDefault();
// disable 'Publish' button
$(el_window).find('.publish-btn').prop('disabled', true);
try {
let subdomain = $(el_window).find('.publish-website-subdomain').val();
if ( ! subdomain.trim() ) {
throw new Error('Please enter a subdomain name');
}
const res = await puter.hosting.create(subdomain, target_dir_path);
let url = `https://${ subdomain }.${ window.hosting_domain }/`;
// Show success
$(el_window).find('.window-publishWebsite-form').hide(100, function () {
$(el_window).find('.publishWebsite-published-link').attr('href', url);
$(el_window).find('.publishWebsite-published-link').text(url);
$(el_window).find('.window-publishWebsite-success').show(100);
$(`.item[data-uid="${target_dir_uid}"] .item-has-website-badge`).show();
});
// find all items whose path starts with target_dir_path
underPath('.item', target_dir_path).each(function () {
// show the link badge
$(this).find('.item-has-website-url-badge').show();
// update item's website_url attribute
$(this).attr('data-website_url', url + $(this).attr('data-path').substring(target_dir_path.length));
});
window.update_sites_cache();
} catch ( err ) {
const errorMessage = err.message || (err.error && err.error.message) || 'An error occurred while publishing';
$(el_window).find('.publish-website-error-msg').html(errorMessage);
$(el_window).find('.publish-website-error-msg').fadeIn();
// re-enable 'Publish' button
$(el_window).find('.publish-btn').prop('disabled', false);
}
});
$(el_window).find('.publish-window-ok-btn').on('click', function () {
$(el_window).close();
});
}
export default UIWindowPublishWebsite;
+6 -1031
View File
File diff suppressed because it is too large. Load diff
+2 -17
View File
@@ -25,12 +25,9 @@ window.window_nav_history_current_position = {};
window.dashboard_nav_history = [];
window.dashboard_nav_history_current_position = 0;
window.progress_tracker = [];
window.upload_item_global_id = 0;
window.app_instance_ids = new Set();
window.menubars = [];
window.download_progress = [];
window.download_item_global_id = 0;
// This is the minimum width of the window for the sidebar to be shown
window.window_width_threshold_for_sidebar = 500;
@@ -113,7 +110,6 @@ if ( window.user_preferences === null ) {
}
window.window_stack = [];
window.toolbar_height = 0;
window.upload_progress_hide_delay = 500;
window.active_uploads = {};
window.copy_progress_hide_delay = 1000;
@@ -128,7 +124,6 @@ window.window_counter = 0;
window.keypress_item_seach_term = '';
window.keypress_item_seach_buffer_timeout = undefined;
window.first_visit_animation = false;
window.show_twitter_link = true;
window.animate_window_opening = true;
window.animate_window_closing = true;
window.desktop_loading_fade_delay = (window.first_visit_ever && window.first_visit_animation ? 6000 : 1000);
@@ -151,9 +146,6 @@ window.launch_apps = [];
window.launch_apps.recent = [];
window.launch_apps.recommended = [];
// Map of { child_instance_id -> { parent_instance_id, launch_msg_id } }
window.child_launch_callbacks = {};
// Is puter being loaded inside an iframe?
if ( window.location !== window.parent.location ) {
window.is_embedded = true;
@@ -162,7 +154,7 @@ if ( window.location !== window.parent.location ) {
}
// calculate desktop height and width
window.desktop_height = window.innerHeight - window.toolbar_height;
window.desktop_height = window.innerHeight;
window.desktop_width = window.innerWidth;
// {id: {left: 0, top: 0}}
@@ -176,7 +168,7 @@ $(window).on( 'resize', function () {
if ( window.a_window_is_resizing ) return;
if ( window.a_window_sidebar_is_resizing ) return;
const new_desktop_height = window.innerHeight - window.toolbar_height;
const new_desktop_height = window.innerHeight;
const new_desktop_width = window.innerWidth;
window.desktop_height = new_desktop_height;
@@ -196,10 +188,6 @@ window.active_element = null;
// The number of recent apps to show in the launch menu
window.launch_recent_apps_count = 10;
// indicated if the mouse is in one of the window snap zones or not
// if yes, which one?
window.current_active_snap_zone = undefined;
//
window.is_fullpage_mode = false;
@@ -216,9 +204,6 @@ window.feature_flags = {
download_directory: true,
};
window.is_auto_arrange_enabled = true;
window.desktop_item_positions = {};
window.reset_item_positions = true; // The variable decides if the item positions should be reset when the user enabled auto arrange
window.file_templates = [];
-104
View File
@@ -2819,10 +2819,6 @@ window.extractSubdomain = function (url) {
return subdomain;
};
window.extractProtocol = function (url) {
var protocol = url.split('://')[0];
return protocol;
};
window.sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
};
@@ -3420,57 +3416,6 @@ window.undo_delete = async (items) => {
}
};
window.store_auto_arrange_preference = (preference) => {
// localStorage still carries it for this device either way.
puter.kv.set('user_preferences.auto_arrange_desktop', preference)
.catch(err => console.warn('Could not save auto_arrange_desktop:', err));
localStorage.setItem('auto_arrange', preference);
};
window.get_auto_arrange_data = async () => {
// Best-effort, like every other preference read: falling back to the
// default keeps the desktop arranging itself rather than not appearing.
const preferenceValue = await puter.kv.get('user_preferences.auto_arrange_desktop').catch(() => null);
window.is_auto_arrange_enabled = preferenceValue === null ? true : preferenceValue;
const positions = await puter.kv.get('desktop_item_positions').catch(() => null);
window.desktop_item_positions = (!positions || typeof positions !== 'object' || Array.isArray(positions)) ? {} : positions;
};
window.clear_desktop_item_positions = async (el_desktop) => {
$(el_desktop).find('.item').each(function () {
const el_item = $(this)[0];
$(el_item).css('position', '');
$(el_item).css('left', '');
$(el_item).css('top', '');
});
if ( window.reset_item_positions ) {
window.delete_desktop_item_positions();
}
};
window.set_desktop_item_positions = async (el_desktop) => {
$(el_desktop).find('.item').each(async function () {
const position = window.desktop_item_positions[$(this).attr('data-uid')];
const el_item = $(this)[0];
if ( position ) {
$(el_item).css('position', 'absolute');
$(el_item).css('left', `${position.left }px`);
$(el_item).css('top', `${position.top }px`);
}
});
};
window.save_desktop_item_positions = () => {
puter.kv.set('desktop_item_positions', window.desktop_item_positions)
.catch(err => console.warn('Could not save desktop_item_positions:', err));
};
window.delete_desktop_item_positions = () => {
window.desktop_item_positions = {};
puter.kv.del('desktop_item_positions')
.catch(err => console.warn('Could not clear desktop_item_positions:', err));
};
// Finds the `.window` element for the given app instance ID
window.window_for_app_instance = (instance_id) => {
return $(`.window[data-element_uuid="${instance_id}"]`).get(0);
@@ -3526,22 +3471,6 @@ window.set_menu_item_prop = (items, item_id, prop, val) => {
}
};
window.countSubstr = (str, substring) => {
if ( substring.length === 0 ) {
return 0;
}
let count = 0;
let pos = str.indexOf(substring);
while ( pos !== -1 ) {
count++;
pos = str.indexOf(substring, pos + 1);
}
return count;
};
// Updates the signed-in user's profile; `username` is kept for callers that
// still pass it.
window.update_profile = function (username, key_vals) {
@@ -3556,44 +3485,11 @@ window.update_profile = function (username, key_vals) {
});
};
window.blob2str = (blob) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsText(blob);
});
};
// Another user's picture is only available while they are on a paid plan.
window.get_profile_picture = async function (username) {
return (await puter.auth.getProfilePicture(username)) ?? undefined;
};
window.format_with_units = (num, { mulUnits, divUnits, precision = 3 }) => {
if ( num === 0 ) return '0';
mulUnits = mulUnits ?? ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
divUnits = divUnits ?? ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y'];
const abs = Math.abs(num);
let exp = Math.floor(Math.log10(abs) / 3);
let symbol = '';
symbol = exp >= 0
? mulUnits[exp]
: divUnits[-exp - 1] ;
if ( ! symbol ) {
symbol = `e${exp * 3}`;
}
const scaled = num / Math.pow(10, exp * 3);
const rounded = Number.parseFloat(scaled.toPrecision(precision));
return `${rounded}${symbol}`;
};
/**
* General-purpose number formatting function with support for decimal places,
* thousand separators, and various formatting options.
+2 -2
View File
@@ -57,8 +57,8 @@ describe('authLogoHeader', () => {
});
it('makes the logo a named link when it leads somewhere', () => {
const h = authLogoHeader({ logoSrc: LOGO, logoHref: '/desktop' });
expect(h).toContain('<a class="auth-logo-link" href="/desktop">');
const h = authLogoHeader({ logoSrc: LOGO, logoHref: '/' });
expect(h).toContain('<a class="auth-logo-link" href="/">');
expect(h).toContain('alt="Puter"');
});
+5 -6
View File
@@ -63,11 +63,11 @@ export const get_auth_redirect_url = () => {
*/
const oidc_return_path = () => {
const pathname = window.location.pathname;
if ( pathname === '/' || pathname === '/desktop' || pathname === '/dashboard' ) {
if ( pathname === '/' || pathname === '/dashboard' ) {
return pathname;
}
// app landing: normalize away a trailing slash to match the backend whitelist
if ( /^(\/desktop)?\/app\/[^/]+\/?$/.test(pathname) ) {
if ( /^\/app\/[^/]+\/?$/.test(pathname) ) {
return pathname.replace(/\/$/, '');
}
return null;
@@ -76,10 +76,9 @@ const oidc_return_path = () => {
/**
* The `return_to` to send along when starting an OIDC flow, or null if the
* current page isn't one the backend will return to. The backend strictly
* whitelists these (never a client-supplied URL): `/desktop`, `/dashboard`,
* and direct app landings (`/app/<name>`, plus the desktop-booted
* `/desktop/app/<name>`), so OIDC login started from an app landing comes back
* to the app — and to the same interface it was opened in.
* whitelists these (never a client-supplied URL): `/dashboard` and direct app
* landings (`/app/<name>`), so OIDC login started from an app landing comes
* back to the app.
*
* A share link (`?shared=`, from an email) is carried along with the path: the
* recipient usually has to sign in before they can see what was shared, and an
+7 -11
View File
@@ -42,7 +42,6 @@ afterEach(() => {
describe('get_oidc_return_to', () => {
it('returns the interface pages the backend whitelists', () => {
expect(at('/desktop')).toBe('/desktop');
expect(at('/dashboard')).toBe('/dashboard');
});
@@ -51,17 +50,12 @@ describe('get_oidc_return_to', () => {
expect(at('/app/editor/')).toBe('/app/editor');
});
it('keeps a desktop app landing on the desktop', () => {
expect(at('/desktop/app/editor')).toBe('/desktop/app/editor');
expect(at('/desktop/app/editor/')).toBe('/desktop/app/editor');
});
it('carries a share link so the item survives the round trip', () => {
expect(at('/', share_search(shared_path('Report.pdf')))).toBe(
`/${share_search(shared_path('Report.pdf'))}`,
);
expect(at('/desktop', share_search(shared_path('Report.pdf')))).toBe(
`/desktop${share_search(shared_path('Report.pdf'))}`,
expect(at('/dashboard', share_search(shared_path('Report.pdf')))).toBe(
`/dashboard${share_search(shared_path('Report.pdf'))}`,
);
expect(
at('/', share_search(shared_path('a.txt'), shared_path('b.txt'))),
@@ -83,10 +77,10 @@ describe('get_oidc_return_to', () => {
expect(at('/', share_search('/alice/Documents/Report.pdf'))).toBe(null);
expect(at('/', '?shared=')).toBe(null);
// other parameters are not ours to carry
expect(at('/desktop', '?app=editor')).toBe('/desktop');
expect(at('/dashboard', '?app=editor')).toBe('/dashboard');
expect(
at('/desktop', `${share_search(shared_path('a.txt'))}&app=editor`),
).toBe(`/desktop${share_search(shared_path('a.txt'))}`);
at('/dashboard', `${share_search(shared_path('a.txt'))}&app=editor`),
).toBe(`/dashboard${share_search(shared_path('a.txt'))}`);
});
it('returns null for anything the backend would reject', () => {
@@ -94,6 +88,8 @@ describe('get_oidc_return_to', () => {
expect(at('/settings')).toBe(null);
expect(at('/action/login')).toBe(null);
expect(at('/app/editor/extra')).toBe(null);
expect(at('/desktop')).toBe(null);
expect(at('/desktop/app/editor')).toBe(null);
expect(at('/desktop/app/editor/extra')).toBe(null);
expect(at('/dashboard/app/editor')).toBe(null);
});
@@ -17,30 +17,20 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const Component = use('util.Component');
/**
* Allows using an HTML string as a component.
* Whether a page load boots the dashboard instead of the desktop. The root
* path and `/app/<name>` boot the dashboard unless the page is a popup, which
* the desktop still handles; `/dashboard` always does. The server matches
* these routes case-insensitively, so this does too.
*
* @param {Object} location
* @param {string} location.pathname
* @param {boolean} location.embeddedInPopup
* @returns {boolean}
*/
export default def(class JustHTML extends Component {
static ID = 'ui.component.JustHTML';
static PROPERTIES = { html: { value: '' } };
create_template ({ template }) {
$(template).html('<span></span>');
}
on_ready ({ listen }) {
listen('html', html => {
$(this.dom_).find('span').html(html);
});
}
_set_dom_based_on_render_mode ({ property_values }) {
if ( property_values.no_shadow ) {
this.dom_ = this;
return;
}
return super._set_dom_based_on_render_mode();
}
});
export function bootsDashboard ({ pathname, embeddedInPopup }) {
if ( /^\/dashboard\/?$/i.test(pathname) ) return true;
const isAppLanding = /^\/app\/[^/]+\/?$/i.test(pathname);
if ( pathname !== '/' && !isAppLanding ) return false;
return !embeddedInPopup;
}
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, it, expect } from 'vitest';
import { bootsDashboard } from './bootsDashboard.js';
const boots = (url, { embeddedInPopup = false } = {}) => {
const { pathname } = new URL(url, 'https://puter.com');
return bootsDashboard({ pathname, embeddedInPopup });
};
describe('bootsDashboard', () => {
it('boots the dashboard at the root, its alias, and app landings', () => {
expect(boots('/')).toBe(true);
expect(boots('/dashboard')).toBe(true);
expect(boots('/dashboard/')).toBe(true);
expect(boots('/app/editor')).toBe(true);
});
it('matches the paths in any letter case, as the server routes them', () => {
expect(boots('/Dashboard')).toBe(true);
expect(boots('/App/editor')).toBe(true);
expect(boots('/APP/Editor/')).toBe(true);
expect(boots('/App/editor', { embeddedInPopup: true })).toBe(false);
});
it('boots the desktop on action pages', () => {
expect(boots('/action/sign-in')).toBe(false);
});
it('boots the desktop in a popup', () => {
expect(boots('/', { embeddedInPopup: true })).toBe(false);
expect(boots('/app/editor', { embeddedInPopup: true })).toBe(false);
});
it('keeps /dashboard on the dashboard even in a popup', () => {
expect(boots('/dashboard', { embeddedInPopup: true })).toBe(true);
});
it('boots the dashboard whatever the query asks for', () => {
expect(boots('/?shared=%2Fann%2Fuid%2Fnotes.txt')).toBe(true);
expect(boots('/?download=https%3A%2F%2Fexample.com%2Ffile.zip')).toBe(true);
expect(boots('/?app=explorer&path=%2Falice%2FDocuments')).toBe(true);
expect(boots('/app/editor?app=explorer')).toBe(true);
expect(boots('/app/editor?puter.fullpage=true')).toBe(true);
expect(boots('/app/editor?puter.fullpage=false')).toBe(true);
expect(boots('/?puter.fullpage=1')).toBe(true);
});
});
+8 -13
View File
@@ -20,7 +20,6 @@
import UIAlert from '../UI/UIAlert.js';
import UIWindowItemProperties from '../UI/UIWindowItemProperties.js';
import publish_as_website from './publishAsWebsite.js';
import open_item from './openItem.js';
import openWithAI from './openWithAI.js';
import launch_app from './launchApp.js';
@@ -44,7 +43,7 @@ import { is_default_app } from './defaultApp.js';
* @param {boolean} options.openWithInNewTab - Open the "Open With" apps in a new browser tab instead of an in-page window (used by Dashboard)
* @param {Function} options.onShowProperties - Optional custom properties handler (used by Dashboard); receives {name, path, uid, element}
* @param {Function} options.onShare - Opens sharing for the item; Share is left out of the menu without it. Receives {name, path, uid, element}
* @param {Function} options.onPublishWebsite - Optional custom publish-as-website handler (used by Dashboard); receives {uid, name, path}
* @param {Function} options.onPublishWebsite - Publishes the folder as a website; Publish as Website is left out of the menu without it. Receives {uid, name, path}
* @param {Function} options.onPublishWorker - Publishes the file as a worker; Publish as Worker is left out of the menu without it. Receives {uid, name, path}
* @param {Function} options.onPasteInto - Optional custom paste handler (used by Dashboard); receives the folder's path
* @param {Function} options.onRemovedFromShared - Optional, called once Remove from Shared has dropped the user's own access (used by Dashboard)
@@ -135,24 +134,19 @@ const generate_file_context_menu = async function (options) {
// -------------------------------------------
// Publish As Website
// -------------------------------------------
if ( !is_trashed && !is_trash && fsentry.is_dir ) {
if ( !is_trashed && !is_trash && fsentry.is_dir && options.onPublishWebsite ) {
menu_items.push({
html: i18n('publish_as_website'),
// Publishing serves the folder to anyone, for good, so it takes the
// same own-it-or-`manage` right as sharing it does (SubdomainDriver
// enforces that). `write` on someone else's folder is not enough.
disabled: !fsentry.is_dir || fsentry.has_website || !may_share,
onClick: async function () {
const target = {
onClick: function () {
options.onPublishWebsite({
uid: fsentry.uid,
name: $(el_item).attr('data-name'),
path: $(el_item).attr('data-path'),
};
if ( options.onPublishWebsite ) {
options.onPublishWebsite(target);
} else {
await publish_as_website(target);
}
});
},
});
}
@@ -363,10 +357,11 @@ const generate_file_context_menu = async function (options) {
html: i18n('share_remove_from_shared'),
onClick: async function () {
try {
await puter.fs.unshare(
const left = await puter.fs.unshare(
$(el_item).attr('data-path'),
window.user.username,
);
if ( left?.failed?.length ) throw left.failed[0];
// Or mode lookups keep answering for a share we just
// walked away from.
invalidate_shared_roots();
@@ -465,7 +460,7 @@ const generate_file_context_menu = async function (options) {
left = left > (window.innerWidth - window_width) ? (window.innerWidth - window_width) : left;
let top = $(el_item).position().top + $(el_item).height();
top = top > (window.innerHeight - (window_height + window.toolbar_height)) ? (window.innerHeight - (window_height + window.toolbar_height)) : top;
top = top > (window.innerHeight - window_height) ? (window.innerHeight - window_height) : top;
UIWindowItemProperties(
$(el_item).attr('data-name'),
@@ -23,7 +23,6 @@ import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
vi.mock('../UI/UIAlert.js', () => ({ default: vi.fn() }));
vi.mock('../UI/UIWindowItemProperties.js', () => ({ default: vi.fn() }));
vi.mock('./publishAsWebsite.js', () => ({ default: vi.fn() }));
vi.mock('./openItem.js', () => ({ default: vi.fn() }));
vi.mock('./openWithAI.js', () => ({ default: vi.fn() }));
vi.mock('./launchApp.js', () => ({ default: vi.fn() }));
@@ -49,6 +48,7 @@ const { default: generate_file_context_menu } =
await import('./generateFileContextMenu.js');
const { default: launch_app } = await import('./launchApp.js');
const { default: UIAlert } = await import('../UI/UIAlert.js');
const { unshareAnswering, allRefused, goneRefused } = await import('../../tests/fixtures/sdkUnshare.js');
const { can_share } = await import('./sharedAccess.js');
const { is_owned_by_me } = await import('./pathOwner.js');
@@ -114,6 +114,37 @@ describe('Share', () => {
});
});
describe('Publish as Website', () => {
const publishItem = async (options) => {
is_owned_by_me.mockReturnValueOnce(true);
can_share.mockResolvedValueOnce(true);
const row = document.createElement('div');
row.setAttribute('data-path', '/me/Site');
row.setAttribute('data-name', 'Site');
const items = await generate_file_context_menu({
element: row,
fsentry: { uid: 'dir-1', name: 'Site', path: '/me/Site', is_dir: true },
associated_app_name: 'editor',
...options,
});
return items.find((item) => item !== '-' && item.html === 'publish_as_website');
};
it('hands the folder to onPublishWebsite', async () => {
const onPublishWebsite = vi.fn();
await (await publishItem({ onPublishWebsite })).onClick();
expect(onPublishWebsite).toHaveBeenCalledWith({
uid: 'dir-1',
name: 'Site',
path: '/me/Site',
});
});
it('is left out without onPublishWebsite', async () => {
expect(await publishItem({})).toBeUndefined();
});
});
describe('Publish as Worker', () => {
const publishItem = async (options) => {
is_owned_by_me.mockReturnValueOnce(true);
@@ -165,6 +196,29 @@ describe('Remove from Shared', () => {
afterEach(() => {
document.body.innerHTML = '';
UIAlert.mockReset();
});
it.each([
['is refused', allRefused, 'Held through a team'],
['resolves with the pair refused', goneRefused, 'Subject does not exist'],
])('keeps the row and shows the error when leaving the share %s', async (_, answer, message) => {
const row = sharedRow();
document.body.append(row);
const onRemovedFromShared = vi.fn();
window.user = { username: 'alice' };
globalThis.puter = { fs: { unshare: unshareAnswering(answer) } };
const items = await generate_file_context_menu({
element: row,
fsentry: { name: 'notes.txt', path: '/ann/uid-1/notes.txt' },
associated_app_name: 'editor',
onRemovedFromShared,
});
await items.find((item) => item.html === 'share_remove_from_shared').onClick();
expect(UIAlert).toHaveBeenCalledWith({ message });
expect(row.isConnected).toBe(true);
expect(onRemovedFromShared).not.toHaveBeenCalled();
});
it('takes the row away once the user has left it', async () => {
+105
View File
@@ -0,0 +1,105 @@
/*
* 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 { jwtPayload } from './jwtPayload.js';
/**
* A token's claims as key-sorted `[key, value]` pairs in JSON, without `iat`.
* Read without checking the signature, so it only says what the token claims.
*
* @param {unknown} token
* @returns {string | null} null when the token isn't a readable JWT
*/
export const tokenClaimsKey = (token) => {
const claims = typeof token === 'string' ? jwtPayload(token) : null;
if ( ! claims || Array.isArray(claims) ) return null;
return JSON.stringify(Object.keys(claims)
.filter(key => key !== 'iat')
.sort()
.map(key => [key, claims[key]]));
};
/**
* Whether two tokens claim exactly the same things apart from when they were
* signed. Two GUI tokens that do are for the same session, user and type.
*
* @param {unknown} a
* @param {unknown} b
* @returns {boolean}
*/
export const sameTokenClaims = (a, b) => {
const key = tokenClaimsKey(a);
return key !== null && key === tokenClaimsKey(b);
};
/**
* The digest the shell sends as `guiTokenDigest`: SHA-256 of
* {@link tokenClaimsKey}, first 32 hex chars. Must match
* `TokenService.claimsDigest` on the server.
*
* @param {unknown} token
* @param {SubtleCrypto | null} [subtle] - null on an insecure origin
* @returns {Promise<string | null>} null when the token isn't readable or
* there is no SubtleCrypto
*/
export const tokenClaimsDigest = async (token, subtle = globalThis.crypto?.subtle) => {
const key = tokenClaimsKey(token);
if ( key === null || ! subtle ) return null;
const hash = new Uint8Array(await subtle.digest('SHA-256', new TextEncoder().encode(key)));
return Array.from(hash, byte => byte.toString(16).padStart(2, '0')).join('').slice(0, 32);
};
/**
* Whether the server rendered this page for this load. A history navigation or
* a restored tab can be a cached copy, rendered for a cookie that has changed.
*
* @param {Performance} [perf]
* @returns {boolean}
*/
export const pageRenderedForThisLoad = (perf = globalThis.performance) => {
const nav = perf?.getEntriesByType?.('navigation')?.[0];
if ( ! nav ) return false;
return (nav.type === 'navigate' || nav.type === 'reload') && nav.transferSize > 0;
};
/**
* What boot does about `/get-gui-token`, which hands over a token for the
* session cookie:
* - `fetch`: ask for it.
* - `same-session`: the stored token is already the one it would hand over.
* - `no-session`: there is no session cookie, so it would refuse.
*
* Anything short of a `guiTokenDigest` from this very page load is `fetch`.
*
* @param {Object} opts
* @param {Record<string, unknown> | undefined} opts.params - gui_params
* @param {string | null} opts.storedToken
* @param {boolean} opts.sameOrigin - whether the page and `/get-gui-token` share an origin
* @param {boolean} opts.renderedForThisLoad - {@link pageRenderedForThisLoad}
* @param {SubtleCrypto | null} [opts.subtle]
* @returns {Promise<'fetch' | 'same-session' | 'no-session'>}
*/
export const guiTokenBootStep = async ({ params, storedToken, sameOrigin, renderedForThisLoad, subtle }) => {
if ( ! params || ! Object.hasOwn(params, 'guiTokenDigest') ) return 'fetch';
if ( ! sameOrigin || ! renderedForThisLoad ) return 'fetch';
const hint = params.guiTokenDigest;
if ( hint === null ) return 'no-session';
if ( typeof hint !== 'string' || ! storedToken ) return 'fetch';
return await tokenClaimsDigest(storedToken, subtle) === hint ? 'same-session' : 'fetch';
};
+134
View File
@@ -0,0 +1,134 @@
/*
* 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 { createHash, webcrypto } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import {
guiTokenBootStep,
pageRenderedForThisLoad,
sameTokenClaims,
tokenClaimsDigest,
tokenClaimsKey,
} from './guiToken.js';
const jwtWith = (claims) =>
`h.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.s`;
const CLAIMS = { t: 'gui', v: '2', u: 'c2Vzc2lvbg==', su: 'c2Vzc2lvbg==', uu: 'dXNlcg==', ai: 'dXNlcg==' };
const TOKEN = jwtWith({ ...CLAIMS, iat: 1 });
const subtle = webcrypto.subtle;
describe('tokenClaimsKey', () => {
it('sorts the claims and leaves out iat', () => {
expect(tokenClaimsKey(jwtWith({ b: 1, a: 'x', iat: 5 }))).toBe('[["a","x"],["b",1]]');
});
it('is null for anything that is not a readable JWT', () => {
expect(tokenClaimsKey('not-a-token')).toBe(null);
expect(tokenClaimsKey(null)).toBe(null);
expect(tokenClaimsKey(`h.${Buffer.from('[1]').toString('base64url')}.s`)).toBe(null);
});
});
describe('sameTokenClaims', () => {
it('is true for two tokens signed at different times for the same session', () => {
expect(sameTokenClaims(TOKEN, jwtWith({ ...CLAIMS, iat: 2 }))).toBe(true);
});
it('is false when any other claim differs, is added or is missing', () => {
expect(sameTokenClaims(TOKEN, jwtWith({ ...CLAIMS, su: 'b3RoZXI=', iat: 2 }))).toBe(false);
expect(sameTokenClaims(TOKEN, jwtWith({ ...CLAIMS, uu: 'b3RoZXI=', iat: 2 }))).toBe(false);
expect(sameTokenClaims(TOKEN, jwtWith({ ...CLAIMS, t: 's', iat: 2 }))).toBe(false);
expect(sameTokenClaims(TOKEN, jwtWith({ ...CLAIMS, x: true, iat: 2 }))).toBe(false);
const { ai, ...withoutAuthId } = CLAIMS;
expect(sameTokenClaims(TOKEN, jwtWith({ ...withoutAuthId, iat: 2 }))).toBe(false);
});
it('is false when either token is unreadable', () => {
expect(sameTokenClaims('garbage', 'garbage')).toBe(false);
expect(sameTokenClaims(TOKEN, null)).toBe(false);
expect(sameTokenClaims(null, null)).toBe(false);
});
});
describe('tokenClaimsDigest', () => {
it('is the first 32 hex chars of SHA-256 over the claims key', async () => {
const expected = createHash('sha256').update(tokenClaimsKey(TOKEN)).digest('hex').slice(0, 32);
expect(await tokenClaimsDigest(TOKEN, subtle)).toBe(expected);
expect(await tokenClaimsDigest(jwtWith({ ...CLAIMS, iat: 9 }), subtle)).toBe(expected);
});
it('is null without SubtleCrypto or a readable token', async () => {
expect(await tokenClaimsDigest(TOKEN, null)).toBe(null);
expect(await tokenClaimsDigest('garbage', subtle)).toBe(null);
});
});
describe('pageRenderedForThisLoad', () => {
const perfWith = (entry) => ({ getEntriesByType: (type) => (type === 'navigation' && entry ? [entry] : []) });
it('is true for a navigation or reload the server answered', () => {
expect(pageRenderedForThisLoad(perfWith({ type: 'navigate', transferSize: 900 }))).toBe(true);
expect(pageRenderedForThisLoad(perfWith({ type: 'reload', transferSize: 300 }))).toBe(true);
});
it('is false for a history navigation, a cached copy, or no timing at all', () => {
expect(pageRenderedForThisLoad(perfWith({ type: 'back_forward', transferSize: 900 }))).toBe(false);
expect(pageRenderedForThisLoad(perfWith({ type: 'navigate', transferSize: 0 }))).toBe(false);
expect(pageRenderedForThisLoad(perfWith({ type: 'navigate' }))).toBe(false);
expect(pageRenderedForThisLoad(perfWith(null))).toBe(false);
expect(pageRenderedForThisLoad({})).toBe(false);
expect(pageRenderedForThisLoad(undefined)).toBe(false);
});
});
describe('guiTokenBootStep', () => {
const step = async (overrides) => guiTokenBootStep({
params: { guiTokenDigest: await tokenClaimsDigest(TOKEN, subtle) },
storedToken: jwtWith({ ...CLAIMS, iat: 3 }),
sameOrigin: true,
renderedForThisLoad: true,
subtle,
...overrides,
});
it('keeps the stored token when the shell names its session', async () => {
expect(await step({})).toBe('same-session');
});
it('skips the request when the shell says there is no session cookie', async () => {
expect(await step({ params: { guiTokenDigest: null } })).toBe('no-session');
expect(await step({ params: { guiTokenDigest: null }, storedToken: null })).toBe('no-session');
});
it('asks when the shell names another session or nothing is stored', async () => {
expect(await step({ storedToken: jwtWith({ ...CLAIMS, su: 'b3RoZXI=' }) })).toBe('fetch');
expect(await step({ storedToken: null })).toBe('fetch');
expect(await step({ params: { guiTokenDigest: 42 } })).toBe('fetch');
});
it('asks whenever the shell\'s word can\'t be taken', async () => {
// An older server, or one that couldn't tell.
expect(await step({ params: {} })).toBe('fetch');
expect(await step({ params: undefined })).toBe('fetch');
expect(await step({ sameOrigin: false })).toBe('fetch');
expect(await step({ renderedForThisLoad: false })).toBe('fetch');
expect(await step({ renderedForThisLoad: false, params: { guiTokenDigest: null } })).toBe('fetch');
expect(await step({ subtle: null })).toBe('fetch');
});
});
+2 -5
View File
@@ -106,9 +106,6 @@ const runLaunch = async (options) => {
const launchAttributes = {
'launch.app': options?.name ?? options?.app_obj?.name ?? 'unknown',
'launch.dashboard_mode': !! window.is_dashboard_mode,
// url_paths has the `/desktop` prefix stripped, so this counts the
// desktop-booted landing (`/desktop/app/<name>`) as the app URL
// it is.
'launch.from_app_url':
window.url_paths?.[0]?.toLocaleLowerCase() === 'app'
&& !! window.url_paths?.[1],
@@ -625,14 +622,14 @@ const runLaunch = async (options) => {
window_height = parseFloat(app_info.metadata.window_size.height);
} if ( options.maximized )
{
window_height = `calc(100% - ${window.toolbar_height + 1}px)`;
window_height = 'calc(100% - 1px)';
}
// top
let top;
if ( app_info.metadata?.window_position?.top !== undefined && app_info.metadata?.window_position?.top !== '' )
{
top = parseFloat(app_info.metadata.window_position.top) + window.toolbar_height + 1;
top = parseFloat(app_info.metadata.window_position.top) + 1;
}
if ( options.maximized )
{
+1 -1
View File
@@ -323,7 +323,7 @@ Please try recreating the link.`);
app: 'explorer',
top: options.maximized ? 0 : undefined,
left: options.maximized ? 0 : undefined,
height: options.maximized ? `calc(100% - ${window.toolbar_height + 1}px)` : undefined,
height: options.maximized ? 'calc(100% - 1px)' : undefined,
width: options.maximized ? '100%' : undefined,
});
}
+5 -3
View File
@@ -84,8 +84,9 @@ export function shared_link_recipient_uuid (params) {
* that account's saved session, ask whether to sign in to it, or nothing.
*
* Popups, embeds (`embedded`) and `action` flows act for whoever opened them,
* so a link must not change their account. A temporary session is left to the
* share link's own sign-in prompt.
* so a link must not change their account. The desktop (`desktop`) doesn't
* open share links, so it never acts on the hint. A temporary session is left
* to the share link's own sign-in prompt.
*
* @returns {{ switch_to: object } | { ask: true } | null}
*/
@@ -93,10 +94,11 @@ export function shared_link_account_step ({
params,
action,
embedded,
desktop,
current_user,
logged_in_users,
}) {
if ( action || embedded ) return null;
if ( action || embedded || desktop ) return null;
const uuid = shared_link_recipient_uuid(params);
if ( ! uuid || uuid === current_user?.uuid?.toLowerCase() ) return null;
const saved = (logged_in_users ?? []).find(user =>
@@ -127,6 +127,10 @@ describe('shared_link_account_step', () => {
expect(step({ action: 'login' })).toBeNull();
});
it('leaves the desktop alone, since it does not open share links', () => {
expect(step({ desktop: true })).toBeNull();
});
it('leaves a temporary session to the share link sign-in', () => {
const temp = { uuid: CURRENT, is_temp: true };
expect(step({ current_user: temp, logged_in_users: [temp] }))
-40
View File
@@ -1,40 +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 UIWindowPublishWebsite from '../UI/UIWindowPublishWebsite.js';
import ensure_can_publish from './ensureCanPublish.js';
/**
* Opens the "Publish as website" flow for a directory, first walking the user
* through account creation and email confirmation when the deployment requires
* a verified email to publish. Returns without publishing if the user backs out
* of either step.
*
* @param {Object} dir - The directory to publish
* @param {string} dir.uid - UID of the directory
* @param {string} dir.name - Display name of the directory
* @param {string} dir.path - Full path of the directory
* @returns {Promise<void>}
*/
const publish_as_website = async function ({ uid, name, path }) {
if ( ! await ensure_can_publish(window.require_email_verification_to_publish_website) ) return;
await UIWindowPublishWebsite(uid, name, path);
};
export default publish_as_website;
-12
View File
@@ -87,15 +87,3 @@ export const startPushWorker = async ({
console.warn('Could not update the service worker:', err);
}
};
/** Closes a browser banner that the desktop's worker showed for this uid. */
export const closeLocalBanner = async (uid, nav = globalThis.navigator) => {
try {
const registration = await nav?.serviceWorker?.getRegistration?.('/');
for ( const notification of await registration?.getNotifications?.() ?? [] ) {
if ( notification.data?.uid === uid ) notification.close();
}
} catch ( err ) {
console.warn('Could not close a browser notification:', err);
}
};
+1 -26
View File
@@ -18,7 +18,7 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { closeLocalBanner, pushWorkerEnabled } from './pushWorker.js';
import { pushWorkerEnabled } from './pushWorker.js';
afterEach(() => {
vi.resetModules();
@@ -149,28 +149,3 @@ describe('startPushWorker', () => {
expect(handler).not.toHaveBeenCalled();
});
});
describe('closeLocalBanner', () => {
it('closes only the desktop worker notification with the acknowledged uid', async () => {
const shown = [
{ data: { uid: 'one' }, close: vi.fn() },
{ data: { uid: 'two' }, close: vi.fn() },
{ data: { puter: { uid: 'one' } }, close: vi.fn() },
];
const getRegistration = vi.fn(async () => ({ getNotifications: async () => shown }));
await closeLocalBanner('one', { serviceWorker: { getRegistration } });
expect(getRegistration).toHaveBeenCalledWith('/');
expect(shown.map((n) => n.close.mock.calls.length)).toEqual([1, 0, 0]);
});
it('works without a registered worker', async () => {
await expect(closeLocalBanner('one', {})).resolves.toBeUndefined();
});
it('contains browser API failures', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {});
await expect(closeLocalBanner('one', {
serviceWorker: { getRegistration: async () => { throw new Error('unavailable'); } },
})).resolves.toBeUndefined();
});
});
@@ -246,7 +246,6 @@ const refresh_item_container = function (el_item_container, options) {
if ( item_path !== window.trash_path && item_path !== window.appdata_path ) {
// if this is trash, get original name from item metadata
fsentry.name = metadata.original_name ?? fsentry.name;
const position = window.desktop_item_positions[fsentry.uid] ?? undefined;
UIItem({
appendTo: el_item_container,
uid: fsentry.uid,
@@ -269,7 +268,6 @@ const refresh_item_container = function (el_item_container, options) {
suggested_apps: fsentry.suggested_apps,
disabled: is_disabled,
visible: visible,
position: position,
shared_with_me: fsentry.shared_with_me,
share_mode: fsentry.share_mode,
shared_by: fsentry.shared_by,
@@ -281,31 +279,6 @@ const refresh_item_container = function (el_item_container, options) {
}
}
// if this is desktop, add Trash
if ( $(el_item_container).hasClass('desktop') ) {
try {
const trash = await puter.fs.stat({ path: window.trash_path, consistency: options.consistency ?? 'eventual' });
if ( ! is_current() ) {
return;
}
UIItem({
appendTo: el_item_container,
uid: trash.id,
immutable: trash.immutable,
path: window.trash_path,
icon: { image: (trash.is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg']), type: 'icon' },
name: trash.name,
is_dir: trash.is_dir,
sort_by: trash.sort_by,
type: trash.type,
is_trash: true,
sortable: false,
});
window.sort_items(el_item_container, $(el_item_container).attr('data-sort_by'), $(el_item_container).attr('data-sort_order'));
} catch (e) {
// Ignored
}
}
// sort items
window.sort_items(
el_item_container,
@@ -47,7 +47,6 @@ Object.assign(window, {
shared_path: '/alice/Shared',
trash_path: '/alice/Trash',
user_preferences: {},
desktop_item_positions: {},
check_fsentry_against_allowed_file_types_string: () => true,
sort_items: () => {},
update_explorer_footer_item_count: () => {},
@@ -21,47 +21,6 @@ const update_mouse_position = function (x, y) {
window.mouseX = x;
window.mouseY = y;
// mouse in top-left corner of screen
if ( (window.mouseX < 150 && window.mouseY < window.toolbar_height + 20) || (window.mouseX < 20 && window.mouseY < 150) )
{
window.current_active_snap_zone = 'nw';
}
// mouse in left edge of screen
else if ( window.mouseX < 20 && window.mouseY >= 150 && window.mouseY < window.desktop_height - 150 )
{
window.current_active_snap_zone = 'w';
}
// mouse in bottom-left corner of screen
else if ( window.mouseX < 20 && window.mouseY > window.desktop_height - 150 )
{
window.current_active_snap_zone = 'sw';
}
// mouse in right edge of screen
else if ( window.mouseX > window.desktop_width - 20 && window.mouseY >= 150 && window.mouseY < window.desktop_height - 150 )
{
window.current_active_snap_zone = 'e';
}
// mouse in top-right corner of screen
else if ( (window.mouseX > window.desktop_width - 150 && window.mouseY < window.toolbar_height + 20) || (window.mouseX > window.desktop_width - 20 && window.mouseY < 150) )
{
window.current_active_snap_zone = 'ne';
}
// mouse in bottom-right corner of screen
else if ( window.mouseX > window.desktop_width - 20 && window.mouseY >= window.desktop_height - 150 )
{
window.current_active_snap_zone = 'se';
}
// mouse in top edge of screen
else if ( window.mouseY < window.toolbar_height + 20 && window.mouseX >= 150 && window.mouseX < window.desktop_width - 150 )
{
window.current_active_snap_zone = 'n';
}
// not in any snap zone
else
{
window.current_active_snap_zone = undefined;
}
// mouseover_window
var windows = document.getElementsByClassName('window');
let active_win;
+4 -17
View File
@@ -21,22 +21,9 @@
* Splits a GUI pathname into the route segments the boot code matches on
* (`window.url_paths`), dropping empty segments.
*
* A leading `desktop` segment is dropped with them: `/desktop` only picks the
* interface, and everything after it is the same route it would be at the
* root. So `/desktop/app/<name>` yields `['app', '<name>']` — the app landing
* every route check downstream already understands — and the only difference
* from `/app/<name>` is that the dashboard-mode check (see initgui.js) doesn't
* claim the path, leaving the app to open on the desktop.
*
* @param {string} pathname - the pathname to parse, e.g. `/desktop/app/editor`
* @param {string} pathname - the pathname to parse, e.g. `/app/editor`
* @returns {string[]} route segments
*/
export const parse_url_paths = (pathname) => {
const paths = String(pathname ?? '')
.split('/')
.filter((element) => element);
if ( paths[0]?.toLocaleLowerCase() === 'desktop' ) {
paths.shift();
}
return paths;
};
export const parse_url_paths = (pathname) => String(pathname ?? '')
.split('/')
.filter((element) => element);
+3 -20
View File
@@ -28,29 +28,12 @@ describe('parse_url_paths', () => {
expect(parse_url_paths('')).toEqual([]);
});
it('drops a leading desktop segment so the rest reads as a root route', () => {
it('keeps a leading desktop segment, so /desktop/app/<name> is not an app landing', () => {
expect(parse_url_paths('/desktop')).toEqual(['desktop']);
expect(parse_url_paths('/desktop/app/editor')).toEqual([
'app',
'editor',
]);
expect(parse_url_paths('/DeskTop/app/editor')).toEqual([
'app',
'editor',
]);
expect(parse_url_paths('/desktop')).toEqual([]);
expect(parse_url_paths('/desktop/')).toEqual([]);
});
it('only drops the prefix, not a later or lookalike segment', () => {
expect(parse_url_paths('/app/desktop')).toEqual(['app', 'desktop']);
expect(parse_url_paths('/desktops/app/editor')).toEqual([
'desktops',
'app',
'editor',
]);
expect(parse_url_paths('/desktop/desktop/app')).toEqual([
'desktop',
'app',
'editor',
]);
});
});
-56
View File
@@ -31,7 +31,6 @@ const ar = {
allow: 'السماح',
ascending: 'تصاعدي',
associated_websites: 'المواقع المرتبطة',
auto_arrange: 'ترتيب تلقائي',
cancel: 'إلغاء',
change_email: 'تغيير البريد الإلكتروني',
change_language: 'تغيير اللغة',
@@ -41,20 +40,13 @@ const ar = {
close_all_windows_and_log_out: 'إغلاق النوافذ وتسجيل الخروج',
change_always_open_with: 'هل تريد دائمًا فتح هذا النوع من الملفات باستخدام',
confirm: 'تأكيد',
confirm_2fa_setup: 'لقد أضفت الرمز إلى تطبيق المصادقة',
confirm_2fa_recovery: 'لقد حفظت رموز الاسترداد في مكان آمن',
confirm_account_for_free_referral_storage_c2a:
'.أنشئ حسابًا وقم بتأكيد عنوان بريدك الإلكتروني للحصول على 1 جيجابايت من مساحة التخزين المجانية. سيحصل صديقك أيضًا على 1 جيجابايت من مساحة التخزين المجانية',
confirm_code_generic_incorrect: 'رمز غير صحيح.',
confirm_code_generic_too_many_requests:
'.طلبات كثيرة جدًا. يرجى الانتظار بضع دقائق',
confirm_code_generic_submit: 'إرسال الرمز',
confirm_code_generic_try_again: 'حاول مرة أخرى',
confirm_code_generic_title: 'أدخل رمز التأكيد',
confirm_code_2fa_instruction:
'.أدخل الرمز المكون من 6 أرقام من تطبيق المصادقة الخاص بك',
confirm_code_2fa_submit_btn: 'إرسال',
confirm_code_2fa_title: 'أدخل رمز المصادقة الثنائية',
confirm_delete_multiple_items:
'هل أنت متأكد أنك تريد حذف هذه العناصر نهائيًا؟',
confirm_delete_single_item: 'هل تريد حذف هذا العنصر نهائيًا؟',
@@ -67,8 +59,6 @@ const ar = {
confirm_session_revoke: 'هل أنت متأكد أنك تريد إلغاء هذه الجلسة؟',
confirm_your_email_address: 'تأكيد عنوان بريدك الإلكتروني',
contact_us: 'اتصل بنا',
contact_us_verification_required:
'.يجب أن يكون لديك عنوان بريد إلكتروني مُؤكد لاستخدام هذه الخدمة',
continue: 'استمر',
copy: 'نسخ',
copy_link: 'نسخ الرابط',
@@ -90,17 +80,13 @@ const ar = {
deploy_as_app: 'نشر كتطبيق',
descending: 'تنازلي',
desktop: 'سطح المكتب',
desktop_background_fit: 'ملائمة',
developers: 'المطورين',
dir_published_as_website: ':%strong% تم نشره إلى',
disable_2fa: 'تعطيل المصادقة الثنائية',
disable_2fa_confirm: 'هل أنت متأكد أنك تريد تعطيل المصادقة الثنائية؟',
disable_2fa_instructions: '.أدخل كلمة المرور لتعطيل المصادقة الثنائية',
documents: 'المستندات',
dont_allow: 'عدم السماح',
download: 'تنزيل',
download_file: 'تنزيل الملف',
downloading: 'جارٍ التنزيل',
email: 'البريد الإلكتروني',
email_change_confirmation_sent:
'.تم إرسال بريد تأكيد إلى عنوان بريدك الإلكتروني الجديد. يرجى التحقق من صندوق الوارد واتباع التعليمات لإكمال العملية',
@@ -129,13 +115,10 @@ const ar = {
forgot_pass_c2a: 'هل نسيت كلمة المرور؟',
from: 'من',
general: 'عام',
get_a_copy_of_on_puter: "Puter.com! :احصل على نسخة من '%%' على",
get_copy_link: 'احصل على رابط النسخ',
home: 'الصفحة الرئيسية',
html_document: 'HTML مستند',
hue: 'درجة اللون',
incorrect_password: 'كلمة مرور غير صحيحة',
invite_link: 'رابط الدعوة',
item: 'عنصر',
items_in_trash_cannot_be_renamed:
'.لا يمكن إعادة تسمية هذا العنصر لأنه في سلة المهملات. لإعادة تسمية هذا العنصر، اسحبه أولاً خارج سلة المهملات',
@@ -147,7 +130,6 @@ const ar = {
loading: 'جارٍ التحميل',
log_in: 'تسجيل الدخول',
log_out: 'تسجيل الخروج',
looks_good: '!يبدو جيدًا',
manage_sessions: 'إدارة الجلسات',
modified: 'تم التعديل',
move: 'نقل',
@@ -172,7 +154,6 @@ const ar = {
open_with: 'فتح باستخدام',
original_name: 'الاسم الأصلي',
original_path: 'المسار الأصلي',
oss_code_and_content: 'برامج ومحتوى مفتوح المصدر',
password: 'كلمة المرور',
password_changed: '.تم تغيير كلمة المرور',
password_recovery_rate_limit:
@@ -188,29 +169,20 @@ const ar = {
paste: 'لصق',
paste_into_folder: 'لصق في المجلد',
path: 'المسار',
personalization: 'تخصيص',
pick_name_for_website: 'اختر اسمًا لموقعك الإلكتروني:',
pictures: 'الصور',
plural_suffix: 's', //this is not necessary for Arabic
powered_by_puter_js: '{{link=docs}}Puter.js{{/link}} مدعوم بواسطة ',
preparing: '...جارٍ التحضير',
preparing_for_upload: '...جارٍ التحضير للتحميل',
print: 'طباعة',
privacy: 'الخصوصية',
proceed_to_login: 'المتابعة لتسجيل الدخول',
proceed_with_account_deletion: 'المتابعة مع حذف الحساب',
properties: 'الخصائص',
public: 'عام',
publish: 'نشر',
publish_as_website: 'نشر كموقع إلكتروني',
puter_description:
'.هو سحابة شخصية تركز على الخصوصية للحفاظ على جميع ملفاتك، تطبيقاتك، وألعابك في مكان آمن واحد، متاحة من أي مكان وفي أي وقت Puter',
reading_file: '%strong% جارٍ قراءة',
recover_password: 'استعادة كلمة المرور',
refer_friends_c2a:
'!سيحصل صديقك على 1 جيجابايت أيضًا .Puter احصل على 1 جيجابايت عن كل صديق ينشئ حسابًا ويؤكده على',
refer_friends_social_media_c2a:
'Puter.com! احصل على 1 جيجابايت من التخزين المجاني على',
refresh: 'تحديث',
rename: 'إعادة تسمية',
replace: 'استبدال',
@@ -220,11 +192,9 @@ const ar = {
save: 'حفظ',
saturation: 'تشبع',
save_account: 'حفظ الحساب',
save_account_to_get_copy_link: '.يرجى إنشاء حساب للمتابعة',
save_account_to_publish: '.يرجى إنشاء حساب للمتابعة',
save_session: 'حفظ الجلسة',
save_session_c2a: '.أنشئ حسابًا لحفظ جلستك الحالية وتجنب فقدان عملك',
scan_qr_2fa: 'امسح رمز الاستجابة السريعة باستخدام تطبيق المصادقة الخاص بك',
search: 'بحث',
seconds: 'ثوانٍ',
security: 'الأمان',
@@ -242,13 +212,11 @@ const ar = {
show_hidden: 'إظهار المخفي',
sign_in_with_puter: 'Puter تسجيل الدخول باستخدام',
sign_up: 'تسجيل',
signing_in: '…جارٍ تسجيل الدخول',
size: 'الحجم',
skip: 'تخطي',
something_went_wrong: 'حدث خطأ ما.',
sort_by: 'فرز حسب',
status: 'الحالة',
storage_usage: 'استخدام التخزين',
storage_puter_used: 'Puter مستخدم بواسطة',
taking_longer_than_usual: '…يستغرق وقتًا أطول من المعتاد. يرجى الانتظار',
terms: 'الشروط',
@@ -277,25 +245,18 @@ const ar = {
videos: 'مقاطع الفيديو',
visibility: 'الرؤية',
yes: 'نعم',
you_have_been_referred_to_puter_by_a_friend:
'!بواسطة صديق Puter تم إحالتك إلى',
zip: 'ضغط',
zipping_file: '%strong% جارٍ ضغط',
// === 2FA Setup ===
setup2fa_1_step_heading: 'افتح تطبيق المصادقة الخاص بك',
setup2fa_1_instructions: '.هو خيار موثوق به لنظام Android و iOS ولكن إذا كنت غير متأكد،<a target="_blank" href="https://authy.com/download">Authy</a> :هناك العديد للاختيار من بينها .(TOTP) يمكنك استخدام أي تطبيق مصادقة يدعم بروتوكول كلمة المرور لمرة واحدة المعتمدة على الوقت ',
setup2fa_2_step_heading: ' (QR code)مسح رمز الاستجابة السريعة',
setup2fa_3_step_heading: 'أدخل الرمز المكون من 6 أرقام',
setup2fa_4_step_heading: 'انسخ رموز الاسترداد الخاصة بك',
setup2fa_4_instructions: `
.هذه رموز الاسترداد هي الطريقة الوحيدة للوصول إلى حسابك إذا فقدت هاتفك أو لم تتمكن من استخدام تطبيق المصادقة الخاص بك
.تأكد من حفظها في مكان آمن
`,
setup2fa_5_step_heading: '(2FA) تأكيد إعداد المصادقة الثنائية',
setup2fa_5_confirmation_1: 'لقد قمت بحفظ رموز الاسترداد في مكان آمن',
setup2fa_5_confirmation_2: '(2FA) أنا جاهز لتمكين المصادقة الثنائية',
setup2fa_5_button: ' (2FA) تمكين المصادقة الثنائية',
// === 2FA Login ===
login2fa_otp_title: '(2FA) أدخل رمز المصادقة الثنائية',
@@ -305,7 +266,6 @@ const ar = {
login2fa_recovery_instructions:
'.أدخل أحد رموز الاسترداد الخاصة بك للوصول إلى حسابك',
login2fa_use_recovery_code: 'استخدام رمز الاسترداد',
login2fa_recovery_back: 'الرجوع',
login2fa_recovery_placeholder: 'XXXXXXXX',
change: 'تغيير', // In English: "Change"
@@ -378,21 +338,13 @@ const ar = {
'billing.enjoy_msg':
'.بالإضافة إلى مزايا أخرى Cloud Storage استمتع بـ %% من', // In English: "Enjoy %% of Cloud Storage plus other benefits."
choose_publishing_option:
'اختر الطريقة التي تريد نشر موقع الويب الخاص بك بها', // In English: "Choose how you want to publish your website:"
create_desktop_shortcut: 'إنشاء اختصار (سطح المكتب)', // In English: "Create Shortcut (Desktop)"
create_desktop_shortcut_s: 'إنشاء اختصارات (سطح المكتب)', // In English: "Create Shortcuts (Desktop)"
create_shortcut_s: 'إنشاء اختصارات', // In English: "Create Shortcuts"
minimize: 'تصغير', // In English: "Minimize"
reload_app: 'إعادة تحميل التطبيق', // In English: "Reload App"
publish_as_serverless_worker: 'النشر كعامل', // In English: "Publish as Worker"
'toolbar.enter_fullscreen': 'وضع ملء الشاشة', // In English: "Enter Full Screen"
'toolbar.github': 'GitHub', // In English: "GitHub"
'toolbar.refer': 'إحالة', // In English: "Refer"
used_of: '{{available}}محاولات مستخدمة من {{used}}', // In English: "{{used}} used of {{available}}"
worker: 'العامل', // In English: "Worker"
'billing.offering.basic': 'أساسي', // In English: "Basic"
too_many_attempts: '.محاولات كثيرة. يُرجى المحاولة لاحقًا', // In English: "Too many attempts. Please try again later."
server_timeout:
'.استغرق الخادم وقتًا طويلاً للاستجابة. يُرجى المحاولة مرة أخرى', // In English: "The server took too long to respond. Please try again."
signup_error: '.حدث خطأ أثناء التسجيل. يُرجى المحاولة مرة أخرى', // In English: "An error occurred during signup. Please try again."
@@ -411,15 +363,10 @@ const ar = {
window_title_open: 'فتح',
window_title_change_password: 'تغيير كلمة المرور',
window_title_select_font: '…اختر الخط',
window_title_session_list: '!قائمة الجلسات',
window_title_set_new_password: 'تعيين كلمة مرور جديدة',
window_title_publish_website: 'نشر الموقع',
window_title_publish_worker: 'نشر العامل',
window_title_authenticating: '…جارٍ التحقق',
window_title_refer_friend: '!أوصِ صديقًا',
desktop_exit_full_screen: 'الخروج من وضع ملء الشاشة',
desktop_enter_full_screen: 'وضع ملء الشاشة',
item_shared_with_you: '.قام مستخدم بمشاركة هذا العنصر معك',
item_shared_by_you: '.لقد قمت بمشاركة هذا العنصر مع مستخدم آخر على الأقل',
item_shortcut: 'اختصار',
item_associated_websites: 'الموقع المرتبط',
@@ -428,9 +375,6 @@ const ar = {
window_click_to_go_back: 'انقر للرجوع.',
window_click_to_go_forward: 'انقر للتقدم.',
window_click_to_go_up: '.انقر للصعود مجلد واحد',
window_title_public: 'عام',
window_title_videos: 'فيديوهات',
window_title_pictures: 'صور',
window_title_puter: 'بيوتر',
window_folder_empty: 'هذا المجلد فارغ',
},
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more