Compare commits

..
194 Commits
Author SHA1 Message Date
Daniel Salazar 5918e3f4e2 fix: kv max number value (#3629) 2026-08-23 06:31:08 -07:00
Nariman Jelveh 2c9e818e5f Docs/remove discord reddit links (#3628)
* docs: remove Discord and Reddit links

Drops both links from the docs README (header row and Support list) and
from the footer generated on every built docs page.

* docs: remove Mastodon link
2026-08-22 22:14:56 -07:00
Nariman Jelveh 8826a9fc51 Remove Discord and Reddit links from README (#3627)
Removed links to Discord and Reddit from the README.
2026-08-22 13:07:33 -07:00
Daniel Salazar 8307e8c9f0 chore: bump up deps (#3626) 2026-08-21 21:03:54 -07:00
Daniel Salazar 732786a029 fix: clean up email validation (#3622) 2026-08-21 20:27:05 -07:00
f0cd251626 🛠️ PUT-1521: Cleanup puter js permissions api + backend routes (#3607)
* refactor(puter-js): collapse puter.perms request* to resource + access

Fifteen request methods differed only by a folder name or an access level, so
every new resource meant another method. Replace them with requestFolder,
requestApps, requestSubdomains and requestAppRootDir, each taking the access
level as an argument.

The old names stay as @deprecated aliases: puter.js ships unpinned from
js.puter.com/v2, so removing them would break live apps. They remain in the
generated declarations because stripInternal has no effect on declarations
emitted from JavaScript, and hand-omitting them would break TypeScript callers
the runtime still serves.

Also drops the user-to-user and user-to-group grant wrappers (groups.js and the
grantUser/grantGroup half of grants.js) plus the req_ shim, none of which were
documented or called. The app, origin and dev-app grants stay: the dashboard
uses puter.perms.revokeApp() to clear grants on app uninstall.

* docs(perms): document the collapsed puter.perms surface

Replace the twelve one-method-per-task pages with requestFolder, requestApps
and requestSubdomains, and rewrite the Perms overview around the seven public
methods. The deprecated aliases keep working but are no longer documented.

Boy Scout: drops the long-dead commented-out grantUser/revokeOrigin sidebar
block for pages that were never published.

* refactor(perms): drop unused user-to-user and user-to-group permission routes

Filesystem access is shared through /share, which records the grant so the
owner can see and revoke it. The older direct-grant paths were left behind with
no caller anywhere - not the GUI, not a doc, not an app: grant-user-user
(already a 501 stub), revoke-user-user, grant/revoke-user-group, and the five
/group/* CRUD routes.

Removing them orphans PermissionService.grant/revokeUserGroupPermission and its
group-members cache bump, the three PermissionStore group writers, and six
GroupStore methods, so those go too.

What stays, and why:
- grant/revokeUserUserPermission - ACLService and ShareService power fs.share
  through them.
- The group permission read path (#scanUserGroup, readUserGroupPerms) - a
  migration seeds the admin group unrestricted driver access, so it is
  load-bearing.
- GroupStore getByUid/addUsers/removeUsers - signup, save_account, OIDC and the
  self-hosted default user assign group membership.

No schema change: user_to_user_permissions, user_to_group_permissions and their
audit tables are untouched. Group rows now come only from migrations, so tests
that need one seed it with SQL the way a migration does.

* refactor(perms): reduce GroupStore to membership writes

With the /group/* routes gone, `getByUid` had no production caller left — the
routes were the only thing that read a group back. Removing it takes the row
decoder and the GroupRow type with it, since they exist only to shape its
result.

What remains is `addUsers`/`removeUsers`: signup, save_account, OIDC and the
self-hosted admin bootstrap all assign group membership. Permissions attached to
a group are read through PermissionStore, which joins the junction table itself
and never needed the store.

Tests that wanted a group id now select it, which is all `getByUid` was doing
for them.

* chore(perms): drop the three by-hand groups no code reads

freeai, experimental and dangerous exist in prod but in no migration — they
were added by hand when hardcoded permissions were keyed by group name. That
map is now a flat per-user floor (`default_user_permissions`), so a group
nothing looks up grants nothing.

Guarded rather than unconditional, because both tables the delete can reach
cascade: dropping a group that still carries permissions or members would
silently revoke them from every member. Only a group with neither goes. One that
survives has dependents and needs a deliberate decision — query
user_to_group_permissions by group_id to see what it holds.

system, admin, user and temp are untouched: config names two of them and code
names the others.

Matches on `extra.name`, not `metadata.name` — `metadata` carries the display
title and colour, and `critical: true` is set on all of these including freeai,
so it does not discriminate.

* feat(puter-js): collapse puter.perms onto request(resource, details) + check()

One method per task meant a new method, doc page and sidebar entry for every
resource. `request` now takes the resource and a payload whose accepted fields
depend on it, and `check` answers the same question without prompting.

    request('folder', { name: 'Documents', access: 'write' })  -> path
    request('apps', { access: 'read' })                        -> boolean
    request('email')                                           -> address
    check('folder', { name: 'Documents', access: 'write' })     -> boolean

Returns stay per-resource: a folder gives its path, email the address, the rest
a boolean, and anything denied is falsy so one `if` covers both.

An array asks for several at once. Everything already held is settled first, so
the prompt covers only what is missing and does not appear when the whole set is
held - the user answers once for the lot. `check` answers per entry, in order,
so a caller can tell which parts are missing rather than only that some are.

Each resource declares four things in one registry entry: how to ask for it
alone, whether it is held, the strings a batch pools into a prompt, and the
value once held. The strings themselves are defined once in
lib/permissionStrings.js, so a request and its check cannot name them
differently. `check` is built on /auth/check-permissions, already live and
already used by UI.js, and it throws rather than answering false when the check
cannot run: a caller that cannot tell "denied" from "never ran" would prompt
someone who had already granted it.

Backward compatibility: all 22 older methods stay callable and typed, marked
@deprecated with the call that replaces them. A lone string still routes to the
raw-permission path - no resource name contains a `:` and every permission
string does, so the two forms cannot collide. The grant/revoke app methods are
untouched; the consent dialog and the dashboard's uninstall path use them.

Also drops three copies of the access-level assertion onto one shared
validator, and gives `appRootDir` a non-prompting server probe, since
`app-root-dir:` only resolves while a grant is being written and a permission
check on it always answers false.

* docs(perms): document request() and check() as the perms surface

Five per-method pages became one `request()` page carrying the resource table,
the batch form and the raw-string escape hatch, plus a `check()` page. The
overview is rewritten around the two methods.

requestAppData's page is re-homed as /Perms/appData rather than deleted - its
scope table, private-entry guidance and lifetime notes are not signature
documentation and have nowhere else to live. Inbound links from KV/set.md and
Objects/app.md follow it.

Playground examples move to the new call form. They are not wired into
examples.js, but an example demonstrating a deprecated method is worse than one
nobody loads.

* fix(perms): keep /auth/revoke-user-user as a deprecated route

Dropping this route with the rest of the unused user-to-user plumbing went too
far. The grant side is retired and stays retired - puter.fs.share() is the only
way in - but access those grants left behind has to remain withdrawable, and a
caller reaching the endpoint over HTTP directly had no replacement. Revoking can
only ever narrow what someone can reach, so keeping it carries no risk.

revokeUserUserPermission never left the permission service; it is load-bearing
for puter.fs.share(). This only re-wires the handler to it, with the gates it
always had.

Nothing in this repo calls the route, which makes it exactly what a later
cleanup reads as dead, so a test pins the registration and its gate alongside
the restored 400 and grant/revoke round-trip cases.

The 501 stub at grant-user-user and the never-called /group/* routes stay
deleted, as does puter.perms.revokeUser - puter.fs.unshare() replaces it and
falls back to live grants when no share row exists.

* fix(perms): let a write grant satisfy a read check on apps and subdomains

`apps-of-user:<uuid>:write` covers managing the user's apps, which includes
reading them, but nothing said so to the permission system. Prefix implication
only widens the other way — an `apps-of-user:<uuid>` grant covers both modes —
so a scan for `:read` missed a `:write` grant, and `puter.perms.check('apps')`
reported an app holding write as holding nothing. A batched request would then
prompt again for access already granted.

Adds the read-from-write exploder for both namespaces, mirroring
`fs-access-levels`. The widening runs one way only, and does not cross into
another user's namespace; both are covered by tests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(perms): answer the app-root-dir check without provisioning it

`/auth/request-app-root-dir` conflates two questions: may the caller claim its
root directory, and where is it. The second provisions `AppData/<uid>` on first
ask, so a caller that only wanted the first — `puter.perms.check('appRootDir')`
— created a directory by asking about it.

Adds `check: true`, which runs the same actor guard and stops at the answer.
A caller that may not claim it still gets the 403, so the flag can't widen
anything. Existing callers are unaffected: without it the route behaves exactly
as before.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(perms): put request() and check() on one path

`request` dispatched to the old per-task methods while `check` asked the
permission tables, so the two answered different questions about the same
access. Concretely, before this: `request('folder', { access: 'write' })`,
`'apps'`, `'subdomains'`, `'appData'` and `'permission'` prompted every time,
whether or not the access was held — which the docs said they wouldn't;
`check('folder')` reported false for a folder the app could read through an ACL
grant that no `fs:` string names, so a batch prompted for it needlessly; a
batch entry for `'appRootDir'` skipped the post-grant retry the single call
does, resolving `undefined` after a grant that had in fact succeeded; and an
N-entry batch made N permission reads plus 2N `whoami` calls.

Both now run the same pipeline — resolve the permission strings, read what is
held once, prompt for the remainder, resolve each entry — with per-resource
hooks for the parts only that resource can answer. So a batch costs one
permission read and one `whoami`, a check reports exactly what a request would
skip the prompt for, and `'folder'` uses the same stat-or-permission reading in
both.

Also:

- A resource is looked up as an own property, so `request('constructor')` is
  the permission string it always was rather than a TypeError.
- A permission read that fails no longer decides anything: `request` falls
  through to the prompt it would have raised anyway, `check` throws. Before,
  `check('appRootDir')` folded a failed check into "not granted", which is what
  the documentation says must not happen.
- Drops `requestFolder`, `requestApps`, `requestSubdomains` and
  `requestAppRootDir`. They were added in this branch and immediately deprecated
  — never shipped, and `request()` no longer needs to route through them. The 22
  methods that did ship keep their exact behaviour, prompting without consulting
  what is held, which the suite now asserts alongside the new behaviour.
- Documents `'appRootDir'`, which was a supported resource in every overload and
  in `PermsResource` but named in none of the docs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(perms): act on review of the three preceding commits

- `src/puter-js/test/perms.test.js` still called `requestApps`,
  `requestFolder`, `requestSubdomains` and `requestAppRootDir`, which the
  previous commit removed. Four cases in the interactive browser harness threw.
  Pointed at `request(...)` instead.

- `request('appRootDir', …)` made two round trips where the shipped method
  makes one: a read-only probe, then the call that names the directory. A
  request is going to claim it either way, so the claim is now the check, and
  the entry it returns carries through to the result. `check` keeps the
  read-only mode, which is the reason that mode exists. Matters because the
  route sits on the FS_SIGN bucket, shared with signed-URL minting.

- `requestPermission` is one of the shipped methods, and the previous commit's
  message was wrong to say all 22 keep their exact behaviour: it forwards to
  `request`, so it now settles a permission the caller already holds instead of
  prompting for it. The value can differ, not just the prompt count — a user who
  would have clicked Deny on a re-prompt used to get `false`. It is the more
  honest answer (the app does hold the access, and denying a re-prompt never
  took it away), but it is a change, and the suite assertion had been switched
  to an unheld permission, which hid it. Asserted both ways instead, in the unit
  tests and the API suite.

- An entry that names no permission no longer rides a grant given for the other
  entries in the same call. Unreachable today — every resource either names one
  or reports itself held — but nothing pinned it.

- Reverted three type-union reformats in `LegacyFSController.ts` that a
  formatter had folded into the app-root-dir commit. That file was not
  prettier-clean to begin with; reformatting it is somebody else's change.

- Docs and types: `Perms.md`'s `appRootDir` row now matches `request.md`'s,
  `check.md` says that a `true` is per entry and a batch still prompts if any
  one entry is missing, and `types.js` no longer names `requestFolder` /
  `requestAppData` in prose that ships in the generated declarations.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Daniel Salazar <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-20 23:48:08 -07:00
ZHOU7821 943adae622 docs: use absolute link to router page in workers create docs (#3615) 2026-08-21 13:30:30 +07:00
Daniel Salazar 65572dcf23 fix: nicer sms card fallback (#3621) 2026-08-20 23:12:09 -07:00
ZHOU7821andZHOU7821 b3923f86da docs: fix typo in workers description (#3614)
Co-authored-by: ZHOU7821 <[email protected]>
2026-08-21 12:26:20 +07:00
Nariman Jelveh 729114bd09 Prioritize app-center in recommendations
Reordered the recommended app list so app-center appears earlier and dev-center is kept at the end. This keeps the default app suggestions aligned with the expected homepage/app-center placement without changing behavior beyond ordering.
2026-08-20 19:16:03 -07:00
Nariman Jelveh da1c85d3c5 Add Meetings to recommended app defaults
Include `meetings` in `RECOMMENDED_APP_NAMES` so it appears in the default recommended apps set alongside other core productivity tools.
2026-08-20 17:16:39 -07:00
Nariman Jelveh 66410d7f1f Revert "Let a browser send the device fingerprint header it is offered"
This reverts commit fef1337b2b.
2026-08-20 17:10:55 -07:00
Nariman Jelveh 76bd05f228 Dashboard: let the trial be a detail line, not an alarm
The Usage card gives each of its three columns a meter and two lines. The
plan column had a boxed, tinted, bordered paragraph instead — and at the
~230px a third of that card comes to, thirty words of it wrapped into a
five-line ribbon standing twice as tall as the storage and resources meters
beside it. The box is the shape we use for the dunning banner. A trial is a
date you should know about, not a fault, and it was reading as the loudest
thing on the card.

So it takes the slot its neighbours use for "n% of 100 GB": a quiet hint-
coloured line under the badge. All three columns now measure the same.

The copy stopped repeating itself while it was there. The badge said "ends
Sep 20" and the sentence beneath it said "ends on September 20, 2026" — two
elements, one fact, and neither of them answering the question someone
actually has, which is how much room is left to decide. The badge now
carries "31 days left" and the line under it carries the consequence:
"First charge Sep 20 unless you cancel." Billing keeps the full sentence and
the opt-out, and Manage is directly below.
2026-08-20 16:59:07 -07:00
Nariman Jelveh fef1337b2b Let a browser send the device fingerprint header it is offered
`fingerprint.ts` reads the device fingerprint from a request body or, for
authenticated requests with no body to carry it, from
`x-puter-device-fingerprint`. That header is documented there as "the
header the GUI may send the device fingerprint on for non-signup
requests", and the middleware has always honoured it.

A browser could never actually send it. The CORS allowlist in
`#installCors` does not include it, so the preflight comes back without
it in `Access-Control-Allow-Headers`, the browser abandons the request,
and `fetch` rejects before anything reaches the server. Nothing in tree
sends the header today, which is why this went unnoticed: the first
client to try it sees every call fail with a network error rather than a
readable status.

Adds the header to the allowlist, and a preflight test asserting the
browser is allowed to ask for it.
2026-08-20 12:40:48 -07:00
404oops 58794f4f76 feat: add MetaProvider for Muse Spark models and integrate with ChatCompletionDriver (#3616)
- Implemented MetaProvider to interface with Meta's Muse Spark models.
- Integrated MetaProvider into ChatCompletionDriver, allowing for dynamic model selection.
- Added unit and integration tests for MetaProvider to ensure functionality and reliability.
- Updated documentation to include Meta as a supported vendor for AI models.
2026-08-20 15:09:56 -04:00
Nariman Jelveh 9809e428b5 Update shared label in email template
Adjust the share-notification email copy to reference the current "Shared" files section instead of "Shared with me," in both HTML and plain-text variants. This keeps onboarding messaging aligned with the UI.
2026-08-19 20:05:56 -07:00
Nariman Jelveh eaddd1d44e redesign: share notification emails (#3612)
* redesign: share notification emails

The share digests were an unstyled fragment: a 520px div with a couple
of paragraphs, no preview line, no small-screen or dark-mode handling,
and an html-only body that left every text-only client reading a machine
down-conversion of the markup.

Both digests (`file_shared_with_you` and `file_shared_invite`) now render
through one layout: a 600px table column that goes full width under
600px, every color written inline so a client that drops `<style>` still
gets the design, with the stylesheet carrying only what inline CSS can't
express — the small-screen and dark-mode overrides. The shares are a
tinted panel of hairline-separated rows rather than loose text, the call
to action is a cell-padded button Outlook can draw, and the reason for
receiving plus the unsubscribe sit below the card where they belong. No
images at all, so nothing depends on an asset a client may refuse.

Templates may now carry a `text` part, and both digests do: it goes out
beside the HTML as multipart/alternative, which is what plain-text
clients, screen readers and spam scoring prefer.

Copy: a preview line that adds to the subject instead of repeating it, a
heading before the list, and an honest unsubscribe label — the link
silences notification mail account-wide, not just shares. The invite now
says what to do with the address and that an existing account can claim
the shares by confirming it.

Also drops `share_by_username` and `share_by_email`, unreferenced since
the digests replaced them.

* fix: widen the template map to the interface before compiling

`Object.entries` over the literal map yields a union with a distinct
type per template, and only the share digests carry a `text` part —
reading it off the union is an error the build tsconfig hides
(`noCheck: true`) and `npm run typecheck` catches.
2026-08-19 18:49:11 -07:00
Reynaldi Chernando 53b792c52c connect to worker's kv with cli (#3613) 2026-08-20 08:36:46 +07:00
Daniel Salazar 2dd7073034 fix: vscode webdav (#3610) 2026-08-19 14:04:56 -07:00
Daniel Salazar a552ce0b87 fix: better metrics for cache hit rates (#3609)
* fix: better metrics for cache hit rates

* chore: type + docs
2026-08-19 11:38:14 -07:00
Neal Shah c04827fd3f add dynamic worker create event (#3608) 2026-08-19 14:20:15 -04:00
Daniel Salazar 9debdffc5d fix: email send frequency + ai ordering (#3604) 2026-08-18 18:13:55 -07:00
Nariman JelvehandJuan Castro 57b4cbab66 feat(dashboard): rewrite Files-tab sharing as a from-scratch modal (#3598)
* feat(dashboard): rewrite Files-tab sharing as a from-scratch modal

The Files tab's Share… action opened UIWindowShare, a desktop UIWindow,
which doesn't fit the dashboard. Replace it with UIShareModal, built on
the same overlay pattern as UIItemPropertiesModal: a centered card on
desktop, a bottom sheet on mobile, styled with the dashboard's design
tokens (dark mode included).

Wiring follows the onShowProperties precedent: generate_file_context_menu
gains an optional onShare hook that TabFiles supplies; every other caller
falls back to the desktop share window unchanged.

Feature parity with UIWindowShare — grant by email/username with an
access level, list who has access (owner, direct, and inherited-from-
ancestor grants), change a grant's mode, revoke — plus:

- revoke confirmation inlined into the row instead of a stacked UIAlert
- real form semantics: Enter submits, button disabled until input,
  spinner while in flight, API errors keep the typed name for correction
- dialog a11y: focus moves in on open and back on close, Tab is trapped,
  Escape closes (first Escape cancels an open revoke confirmation),
  status messages announce via aria-live
- backdrop close keyed on where the press started, so a text-selection
  drag out of the input can't dismiss the dialog
- name-derived avatar colors and a loading state for the first fetch

Also fixes a double-encoding bug (shared by UIWindowShare) where mode
labels ran through html_encode twice, rendering "Can edit &amp; share".

* fix(dashboard): keep keyboard focus inside the share modal across re-renders

Changing a grant's mode, revoking, or Escape-canceling the inline
confirmation re-renders the access list (or disables the focused
control), which dropped focus onto <body> - outside the dialog's Tab
trap and invisible to screen readers. Focus is now restored explicitly
after each of those actions: to the same holder's control when it
survives, else to the dialog itself (tabindex=-1), and the Tab trap
steps back into the cycle when focus rests on the dialog container.
A failed grant likewise returns focus to the recipient input.

* fix(dashboard): give share modal controls 44px touch targets

On touch devices the close (32x32) and revoke (30x30) buttons and the
26px-tall per-row mode select were below the 44px minimum. On coarse
pointers the icon buttons now hit-test at 44x44 through a centered
pseudo-element (visuals unchanged, and the row spacing absorbs the
overhang without overlapping neighbors), and the row select gets
taller padding. Fine-pointer rendering is untouched.

* fix(dashboard): clear the iOS home indicator in the share bottom sheet

The app opts into viewport-fit=cover, so on notched phones the
bottom-docked sheet extends to the physical screen edge and its last
row sat under the home indicator. The sheet body's bottom padding now
adds env(safe-area-inset-bottom), matching how the codebase pads other
bottom-docked surfaces.

* fix(share): say 'Updated access' when changing a grant's mode

Changing someone's access level reported 'Shared with X', the same
message as a fresh grant, which reads as if a new share happened.
Both share dialogs now confirm mode changes with a dedicated
'Updated access for X' message. The UIWindowShare call also drops the
html_encode() around the recipient - i18n() already encodes
interpolations, so the wrapper double-encoded.

* fix(dashboard): align the share dialog's accessible name with the properties modal

The dialog's aria-label read 'name - Share' with an em dash while the
sibling properties modal uses plain 'name Properties'; screen readers
announce the dash as noise. Use the same name-then-noun pattern.

* fix(dashboard): ellipsize the share input's placeholder when it overflows

At phone widths the 'Add people by email or username' placeholder was
clipped mid-letter; text-overflow: ellipsis truncates it cleanly.

* fix(dashboard): raise the share selects' chevron contrast in light mode

The hardcoded slate-400 stroke measured ~2.6:1 against light surfaces,
below the 3:1 minimum for non-text indicators. Light mode now uses
slate-500 (~4.7:1); dark mode keeps slate-400, which already clears
5:1 there.

* fix(dashboard): stop Files-tab shortcuts from firing behind the share modal

The document-level keydown.tabfiles handler kept running while the
share (or item-properties) modal was open. With focus on any of the
modal's buttons or selects, Enter and Space were preventDefault-ed
before they could activate the control, arrows could not drive the
mode selects, and letter typeahead was hijacked into row typesearch —
while Enter opened the selected row behind the overlay, Delete moved
it to Trash, and Cmd+A/C/X/V acted on the hidden list. Yield the
keyboard to the modal for as long as one is up; its own handlers
already cover Escape and Tab.

* fix(dashboard): keep the on-screen keyboard down when the share sheet opens

Autofocusing the recipient input popped the keyboard over the bottom
sheet the moment it opened, hiding the access list before the user had
chosen what to do — the same reason the revoke flow already focuses
the dialog instead of the input. On touch-primary devices give the
dialog container initial focus (which also anchors the Tab trap);
desktop keeps the input autofocus.

* fix(dashboard): give the share sheet's confirm and submit buttons 44px touch height

The inline revoke confirmation's Cancel/Remove pair rendered ~29px
tall on touch — small targets 6px apart where one of the two is
destructive — and the submit button was fixed at 38px. Grow both to
44px under pointer: coarse, matching the standard the modal's icon
buttons already meet. The touch block moves below the confirm-button
base rules it now overrides, since a media query adds no specificity
and source order decides.

* fix(dashboard): name the person in the share rows' accessible labels

Every grant row's mode select announced as bare 'Access level' and
every revoke button as 'Remove access', so a screen reader user
tabbing the list could not tell whose grant a control changes. Carry
the holder in the aria-label ('Access level for alice' / 'Remove
access for alice'); the visible UI and the revoke tooltip stay as
they were. i18n() encodes the interpolated string as a whole, quotes
included, so the labels stay attribute-safe for any holder name.

* fix(dashboard): keep the share status region in the accessibility tree

* fix(dashboard): give the share modal's add-row controls 44px touch height

* refactor(gui): extract the share dialogs' pure logic into tested modules

* feat(dashboard): adopt the shared mode helpers and handle pending invitations

---------

Co-authored-by: Juan Castro <[email protected]>
2026-08-18 17:34:40 -07:00
Juan Fernando Castro 5e1645d40e 🔧 PUT-1524: Sanity check file sharing api (#3603)
* fix: sharing answers "who can reach this" from the grants, not the index

Two ways a share listing could name access that was no longer there.

A recipient's listing paired the flat permission read with the list of
permissions it asked for by array index. That read drops misses and
dedupes its keys, so the two are not positional: one entry's live grant
vouched for another entry that had none, and listShared() kept
publishing a withdrawn item's name, size and signed thumbnail URL to
someone who could no longer open it. Read the permission off the value
instead.

getShares() had the same gap from the owner's side, with no liveness
check at all — a grant withdrawn through /auth/revoke-user-user or an
ACL mode change left the index row behind, and the owner was told
someone could reach a file they could not. Checked against the grants
now, one batched read per distinct holder. Pending invites are not
subject to it: they have no grant yet, which is the point of them.

Also covers the access-token actor, which reaches the same reach bound
as an app through a different arm of the ACL check. No behavior change
there — it was correct and untested.

* test: pin that a revoke crosses regions

A revoke reaches a peer region as a replicated SQL delete plus three
invalidation events, one per cache the region owns: the u2u row cache,
the flat view and the scan generation. The delete alone changes nothing
there, and each cache has a different consequence if its event is lost
— 20s for the generation, 5 minutes for the row cache, and forever for
the flat view, whose grant-path entries carry no expiry.

Nothing covered the whole path end to end. The store tests prove each
event is emitted and applied; this proves the result, which is that the
recipient stops being able to read. It asserts the read still succeeds
after the SQL delete alone, so the test also records why replication is
not sufficient on its own.

* test: pin that a leaked uuid buys no access

A masked share path hides which folder an item sits in; it was never the
thing deciding who may open it. Nothing checked that at the route level,
so the guarantee rested on unit tests of the resolver alone.

Reads one shared file through its masked path, then tries the sibling
four ways: the shared uuid with the sibling's name, the sibling's own
uuid, a `..` back out of the root, and the owner's real path.

Worth knowing about this one: it's mutation-checked. Removing the head !== root.name guard in sharePathMask.ts fails it with reachable: /testuser/55dd54c0…/share-http-1df8933e.txt. I verified that specifically because two tests I wrote earlier in this chunk passed with their guards broken — both were vacuous, and I deleted them rather than commit false assurance.

* docs: say what listShared's total actually counts

`total` counts the shares recorded for you; items are filtered after the
page is read, so a withdrawn grant leaves the count higher than anything
paging will yield. The page description already explained the short-page
behaviour, but the field read as an exact count and the example printed
it as one.

The test pins the gap it describes: two shares, one withdrawn outside
the index, one item listed and a total of two.

* fix: keep an undelivered broadcast event instead of dropping it

The outbound queue was cleared before the send, so a peer that timed out
took its events with it. Most were survivable — a lost cache invalidation
heals when the entry's TTL lapses. A revoke's flat-perm invalidation is
not: grant-path entries carry no expiry, so a peer went on serving a
withdrawn grant until something else wrote that key.

Failed sends now go back on the queue, which the existing flush timer
retries. Anything queued since wins over the retry, and the queue is
bounded at 10,000 with the oldest dropped first, so a peer that stays
down cannot grow it without limit. Each retry is signed at send time, so
it is not rejected against the replay window.

* fix: stop plus-addressing from deciding who a share reaches
2026-08-18 15:51:23 -07:00
b795b219a8 ✨ PUT-1497: Share file link sharing and notifications (#3595)
* refactor(share): move share notifications into their own service

* feat(share): invite an address with no account, and email it

* feat(share): surface pending invites in the SDK and share dialog

* fix(share): unreachable revoke confirmation, and double-encoded labels

* feat(share): budget share announcements, group them, and let people block senders

Sharing had one defence against noise: a 15-minute quiet window per (sender,
recipient) pair, which dropped the second share rather than folding it in.
Twenty senders each under their own window could still bury someone, and there
was no way to make one of them stop.

Announcements are now budgeted on two axes through the existing sliding-window
limiter: 1 per 15 minutes and 20 per day from one sender, and 10 per hour /
50 per day to one recipient from anyone. Over budget the share still succeeds
and the recipient's notification is still brought up to date — only the
interruption is dropped. Invite email to an address with no account is budgeted
the same way, keyed on a hash of the canonical address.

Notifications now fold across senders: a new share rewrites the notification
the recipient hasn't dismissed, so "alice and bob shared 5 items with you"
replaces a stack of five. The record is written even when suppressed, so the
count is right whenever they next look.

Blocking is a new `user_block` table with enforcement in ShareService: a blocked
sender's share is refused with `recipient_not_accepting_shares`, spends no
quota, and writes no row, and their unclaimed invite is dropped when the address
is confirmed. Existing access is untouched — that is what revoke is for.
Managed from a Blocked people card in the dashboard's Security tab.

Also publishes the sharing limits, including the ones already on this branch
that were never documented.

* fix(share): name the item in share email, instead of 'an item'

* fix(share): make the invite lifecycle canonical, authorized, and race-safe

* refactor(email): drop EmailClient.isConfigured; callers read config.email

* feat(share): batch share email into a per-recipient digest, durably

* docs(share): document the share error codes; steady the disk migration tests

* fix(share): log why a digest wasn't sent, and recover orphaned ones

* feat(share): email recipients about shares by default, with a way to decline

Share email was off unless a deployment opted in, which meant an account
holder was told about a share in the app only. It is now on unless
`share_email_notifications` is set to false.

The reason it defaulted off was that nobody could decline. So this also
honors `user.unsubscribed` — the account-wide opt-out the /unsubscribe page
already writes and app feedback already respects, which share email ignored —
and the digest carries that link. Sharing and the in-app notification are
unaffected by it; only the mail stops.

The link is composed in the template around an interpolated uuid rather than
passed pre-built: Handlebars escapes interpolated values, so a whole URL came
out as `user_uuid&#x3D;…`, which browsers decode but link scanners and older
mail clients need not.

* fix(share): count every shared file in the digest, not just the first

* feat(share): let a recipient refuse shares from everyone

Blocking answered "not from this person" but had no answer to "not from
anyone", so the only way to stop a stream of unwanted shares was to name
each sender after they had already reached you.

Stored as a key in the user row's existing `metadata` blob rather than a
column: the share path already holds the recipient's row by the time it
asks, so reading it costs nothing, and a one-bit preference doesn't earn
a migration per dialect. `updateMetadata` merges and refreshes the cached
row, so the switch bites on the very next share.

Refusing everyone reports the same code as refusing one person — which of
the two it is is the recipient's business, not the sender's. Enforced at
both moments the per-sender block is: when the share is issued, and when
a pending invite is claimed. The per-sender list is untouched while the
blanket switch is on, so turning it off restores what it hid.

`GET /share/blocks` now carries `all`; `POST`/`DELETE` take `{ all: true }`
beside the existing `{ username }`. Managed from the same Blocked people
card in the dashboard's Security tab.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(share): keep the digest sweep off a window that still has a timer

The sweep treated an entry as orphaned the moment its window closed, which
is also the moment the node that armed it fires. Claiming an entry is only
exclusive among flushers that can see each other's deletes, so the two
could each claim a share of the same digest and both send. It now waits
out a grace period first, which costs a genuinely stranded digest that
much delay and nothing else.

Both digest listings were capped at 200 with no word when they hit it — a
truncated flush sends a digest that undercounts and reads as complete.
The cap is named and logged.

Also: `#emailHolder` still described share email as off by default, which
it stopped being; the config doc said the batch window defaults to 60s
when it is 90; and the two tests that need several calls inside one window
were racing a 50ms window across four sequential round trips, so they
failed under full-suite load rather than on the behaviour they cover.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(share): stop double-encoding the recipient in two dialog messages

`i18n()` encodes what it returns, replacements included, so encoding the
recipient first showed the entities to anyone whose address or username
contains one. Same pattern already fixed two lines above.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(notification): widen the mysql shown/acknowledged columns

Both arrived from the v1 schema as `tinyint(1)`, where they were flags.
The backend rework changed the writes to a unix second; sqlite (`INTEGER`)
and postgres (`bigint`) took it and mysql did not, so on mysql every
`markShown` and `markAcknowledged` has failed with
ER_WARN_DATA_OUT_OF_RANGE and left the column NULL. Dismissing a
notification never stuck — the unacknowledged count never moved and one
already delivered came back on every reconnect.

No backfill: every reader tests `IS NULL` / `IS NOT NULL` only, so a
legacy `1` keeps meaning "yes" once widened. Guarded on the current type,
because changing a column type copies the table and this directory
replays on every boot.

Not reachable from the test suite — it runs against sqlite and postgres,
both of which already have the right type. Verified by hand against mysql:
`/notif/mark-read` and `/notif/mark-ack` now persist, and a dismissed
share notification is no longer the one a later share folds into.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Daniel Salazar <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-18 09:36:33 -07:00
Reynaldi Chernando 401b6066b3 Use gpt 5.6 luna as default for docs (#3602) 2026-08-18 09:36:23 -07:00
Daniel Salazar ec3c33fea6 fix: misc hardening fixes (#3600) 2026-08-18 00:06:58 -07:00
Anany Singh 95d797b047 feat(workers): expose app_uid in puter.workers.get and puter.workers.list (#3596) 2026-08-18 00:05:17 -07:00
Daniel Salazar bd06e88185 feat: bring back referrals PUT-1463 (#3599) 2026-08-17 23:49:09 -07:00
Nariman Jelveh cabedc30b0 Require login on app landing pages
Prevent first-time visitors from being treated as temporary users when they open an app landing page such as `/app/<name>` or `/desktop/app/<name>`. These routes now always go through the real login/signup flow.
2026-08-17 20:11:29 -07:00
Daniel Salazar f81b76c1d1 fix: webdav connectivity fixes for macos (#3597) 2026-08-17 19:02:55 -07:00
404oops 9604cc3f23 feat(ai-chat): overhaul provider model catalogs to match current APIs (#3586) 2026-08-17 14:06:44 -04:00
2c852bf6b3 ✨ PUT-1412 File sharing backend api (#3553)
* refactor(permissions): drop hardcoded group permission map for a flat default

* test(drivers): assert credential-gate intent instead of a 403 proxy

* fix(permissions): report whether a revoke removed anything and persist the linked grant row before the flat view

* feat(permissions): replicate permission invalidations across regions

* feat(share): extend the share table into an index of active shares

* feat(share): query and maintain active shares in ShareStore

* feat(users): add a batched lookup by email

* fix(cache): apply cache updates broadcast from peer regions

* fix(permissions): scope a revoke to the issuer that granted it

* feat(share): add ShareService with a per-day share limit

A share is two writes that belong together: the permission grant, which
authorizes access, and a share row, which makes it listable and ties it to an
fsentry so it dies with the file. Nothing else grants fs:* to a user.

Authorization reuses canManagePermission — an owner satisfies it through the
is-owner implicator, a delegate through an explicit manage:fs:<uid> grant. An
owner may clear any issuer's share of their node; anyone else only the ones
they issued, or their own access. Self-revoke skips the manage gate but still
requires `see`, so it cannot be used to probe for files.

The per-day limit counts shares created rather than live rows, so revoking and
re-sharing cannot recycle a slot, and changing an existing share's mode is not
new reach and does not spend budget. Tunable via share_daily_limit.

* feat(share): expose sharing over HTTP

POST /share, POST /share/revoke, GET /share/shared-with-me, GET /share/shares.
The controller was registered but entirely commented out.

Recipients × items fan out concurrently — every pair is a distinct
(holder, entry) key, so none of them contend — bounded by
runWithConcurrencyLimitSettled, which returns results index-aligned with the
input for the per-pair outcome list. Responses carry usernames only, never
internal ids, and the 404-not-403 rule is preserved so a failed call cannot
confirm a file the caller could not otherwise see. Notifications are fired off
the response path; a share must not fail over its own notification.

Per-request caps on recipients and items bound one call's fan-out; the daily
limit bounds the total.

* feat(share): keep recipients consistent when a shared item changes

* fix(fs): stop listing issuer homes at the filesystem root

* fix(acl): serialize concurrent mode changes on one node and pin app containment on shared paths

* fix(fs): expire signed URLs over entries the signer doesn't own

signFile defaults to a ~317k-year TTL and verifySignature checks only uid,
expires and signature — never the ACL. A recipient who ever signed a shared
file therefore held a permanent, revocation-proof URL to its bytes: revoking
the share did nothing to it.

signEntry now takes the acting user and drops to NON_OWNER_SIGNATURE_TTL_SECONDS
(1 hour) when the signer is not the entry's owner. Owners keep the permanent
default, so no existing client changes behavior.

The signature-authenticated directory listing bounds its children
unconditionally: that route has no session actor, and a signature proves
possession rather than ownership, so a recipient holding a short-lived
directory signature could otherwise mint permanent URLs for every child.

A bounded window is not revocation — the durable fix is a per-entry signature
epoch folded into the HMAC and bumped on any permission change.

* refactor(permissions): drop the unused permission-issuer lookup

listUserPermissionIssuers and its store method listUserPermissionIssuerIds
existed to synthesize the filesystem root from the home directories of everyone
who had granted the caller a permission. That listing is gone — it advertised
folders readdir then refused to open — and the share index answers "who shared
with me" directly, so nothing wants them back.

One removed test only asserted that the call returned an array; the other
covered readLinkedUserUserPerms round-tripping and is kept, rewritten without
the issuer lookup.

* fix(share): return the created share, not just an acknowledgement

* feat(puter.js): add file sharing to puter.fs

share(), unshare(), listShared() and getShares() on puter.fs, following the
existing FS operation shape: positional and options-object forms through
defineOperation, JSDoc overloads as the published signature, relative paths
resolved against the app's root directory.

A bare recipient string is read as an email when it contains @ and as a
username otherwise. Sharing an item with someone who already has it replaces
their access rather than stacking a second grant, so raising read to write is
one more call.

Adds a sharing suite to the API runner, which passes unchanged on node,
browser and workerd. Documents all four methods with runnable examples, and
corrects the FS overview callout that told readers one user cannot read
another's files — true before this, not after.

* feat(gui): add a Shared folder for items others shared with you

A sidebar entry listing everything other users have shared with you, backed by
puter.fs.listShared().

The path is the sentinel `puter://shared` rather than /<user>/Shared: this is a
query, not a directory, and a path-shaped value could collide with a folder
someone actually creates. refresh_item_container and update_window_path both
branch on it to skip the stat there is no fsentry for, and the listing swaps
readdir for listShared.

Entries render at their real paths under their owners' directories — the item
container already preferred an explicit fsentry.path over joining onto the
container, so nothing else had to change. Each carries who shared it and at
what level, which the context menu reads next.

* feat(gui): share items from the context menu

A sharing dialog shaped like its neighbours — options object, HTML-string
template, jQuery wiring, delegating to UIWindow() — with a recipient field, a
read/edit/share dropdown, and the current access list with revoke buttons.

Reached from a new "Share…" context menu entry, which is hidden on items shared
*with* you: re-sharing needs manage, so the dialog would only surface an error.

Those items get "Remove from Shared" in place of Delete. Delete moves an item
to *your* trash, which for someone else's file means moving their data out of
their tree — FSService refuses it, and the user saw a bare 403. Removing your
own access is what the action was reaching for, so that is what it now does.

* fix(share): withdraw what a removed recipient re-shared

* feat(share): report access inherited from a parent folder

* fix(gui): load the puter.js bundle the server configured

* refactor(gui): extract the action icon set into a helper

* feat(gui): surface Shared in the file browser

* feat(gui): manage access from the share dialog

* test(share): cover access inherited from a parent folder

* fix(share): keep downstream access from surviving a delegate who leaves

* fix(gui): name the real owner in the share dialog

* fix(gui): page through every shared item instead of the first 50

* feat(share): return item metadata with a share

* fix(share): invalidate a holder's cache when the entry is deleted

* fix(gui): treat items inside a shared folder as someone else's

* feat(permissions): let manage inherit down the filesystem tree

Access already reached descendants through the ancestor chain while authority did not, so someone trusted to manage a shared folder could re-share the folder but nothing inside it, and could not see who had access to a file within it.

A manage-inherits-from-ancestor implicator resolves it in the permission layer, beside is-owner, so every caller agrees rather than just ShareService. It consults only the immediate parent — resolving that re-enters one level up, making a chain of depth d cost d checks rather than d².

That makes two cascade gaps reachable, both fixed here. A revoke now walks the subtree, since a grant on a descendant can rest on authority held at the folder. And it stops at a delegate whose authority survives another issuer, because what they granted was never theirs to lose.

Also pins that manage is not transitive: granting it needs manage:manage:fs:<uid>, which only the owner holds, so delegation is one level deep by construction.

* fix(gui): offer sharing inside a folder you manage

The menus encoded "manage does not inherit" and would now hide an action that works. The Shared listing records each root's mode; the menus resolve a child's by longest matching ancestor, loading on demand so a deep link or restored window works too.

* fix(share): make the daily share limit hold under concurrency

* test(share): cover concurrency, measure cost, and name cases for what they verify

* fix(gui): import the ownership helpers the item menu calls

The single-item context menu handler calls is_owned_by_me and
shared_mode_for, but the imports were only ever added to
generate_file_context_menu.js — so every right-click on an item threw a
ReferenceError before the menu could build, and the non-owner Delete
gating never ran.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): authorize before resolving the recipient

share() looked up the recipient in parallel with the entry, before the
manage check — and the two failures carried different error codes. Any
verified user with a real entry uid could probe arbitrary emails and
usernames for account existence, at no quota cost. Resolve the entry,
authorize, and only then resolve the recipient: an unauthorized caller
now sees the identical safe 404 whether or not the recipient exists.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(permissions): broadcast permission row-cache invalidations to peer regions

Every publishCacheKeys call for the u2u, u2a, and access-token row
caches omitted broadcast, so a revoke only cleared the mutating
region's Redis. A peer region applied the replicated generation bump,
re-scanned, read the deleted row from its own still-warm 5-minute row
cache, and re-warmed the flat view from it — revoked access outlived
the revoke by the row-cache TTL instead of the intended 60-second
bound. CacheReplicationService already consumes these events; the
emits were just never sent.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(fs): refuse to rename an entry owned by another user

remove and move both refuse to act on an entry the caller does not
own, even when the ACL allows the write — rename had no such guard, so
a write-mode share recipient could rename the owner's file, or the
shared folder itself, rewriting the owner's whole subtree's paths.
rename now takes the acting user and applies the same policy.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(permissions): decide a flat delete from the primary, not a lagging replica

revokeUserUserPermission deletes the SQL grant, then only drops the
flat KV entry once no issuer still grants the permission. That
remaining-check read through the row cache the delete had just
invalidated, straight to a replica — under any lag the deleted row
reappeared, the flat delete was skipped, and the stale rows were
re-cached for another five minutes. Grant-path flat entries carry no
TTL, so the holder kept working access with zero SQL rows behind it,
invisible to every listing. The check now reads the primary and
re-warms the cache with what it actually saw.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(permissions): keep a failed remote flat-invalidation from crashing the process

The outer.permission.flatInvalidated applier was fire-and-forget with
no catch, and it awaits a KV delete — one transient KV error while
applying a peer region's revoke became an unhandled rejection, which
is process-fatal under default Node. Its sibling appliers were already
guarded; this one now logs and moves on, leaving the entry to the next
invalidation or its TTL, same as a lost event.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): revoke every requested item and recipient, not just the first

revokeShare destructured only the first recipient and first item while
the parsers accept arrays up to the request caps — unshare({items:
[a, b, c]}) returned success having revoked only a, leaving access the
caller believes is gone. Revoke now fans out over every (recipient,
item) pair exactly like POST /share, reports per-pair outcomes, and
sums the revoked count; the response stays backward compatible.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): only a confirmed email designates a recipient

Recipient resolution by email accepted unconfirmed accounts, so
pre-registering someone else's address (unconfirmed) was enough to
receive shares meant for them once no confirmed account held it.
An email now only resolves to an account that has confirmed it;
username shares are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): accept tilde-rooted paths like the FS routes do

The SDK resolves relative paths to ~/..., but the share routes never
expanded the tilde — a ~-prefixed string was read as a uid and every
relative-path call 404'd. Item parsing now treats ~ as path-shaped and
expands it to the actor's home with the same helper the legacy FS
routes use, on share, revoke, and the shares listing.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): walk a directory revoke by parent linkage, not path prefix

listByFsentrySubtree matched descendants with fsentry_id = ? OR path
LIKE ?, which has two problems: fsentries.path is lazily backfilled
and NULL on old rows, so those descendants' shares silently survived a
directory revoke, and the OR'd predicates forced a scan of every
active share. A recursive CTE over parent_id — the same shape the
lineage resolver already uses — covers every descendant and runs on
idx_parentId_name.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(gui): give each item its own share dialog

single_instance keyed the dialog on the app id alone, so opening
Share… on a second file focused the first file's dialog — typing a
recipient there granted access to the wrong file, with only the title
hinting at it. The dialog is now instanced per path: same item
refocuses, different item opens fresh. Also stops pre-encoding the
title, which UIWindow encodes again.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(permissions): let manage answer a write check

A manage grant let its holder re-share a folder but not work in it: the
ACL mode family stops at write, and the fs exploder had no rule for the
narrowest mode, so `manage:fs:<uid>` never satisfied `fs:<uid>:write`.

Fold manage into the candidate list for every non-manage mode, in both
the access-token branch and the scan branch, and give `write` an (empty)
exploder rule so the manage arm is emitted for it too.

* fix(fs): authorize restructuring by write on the parent

* fix(fs): let a share recipient work inside a shared folder

rename, remove and move refused outright when the entry belonged to
someone else, so a recipient with write could neither delete nor rename
anything inside a folder shared with them. The GUI compounded it by
hiding Delete for any item it did not own.

Authorize the three by ACL write on the entry's parent. For an owner
that is the same answer; for a recipient it grants the inside of a
shared folder and withholds the folder itself, whose parent is the
owner's private tree.

Deleting sends the item to its owner's trash rather than the deleter's,
so it leaves the recipient's view without leaving the owner's account
and without changing hands. A move may not otherwise carry someone
else's entry out of their tree.

* fix(fs): give a new entry to the owner of the folder it lands in

A file a share recipient added to a shared folder was recorded as
theirs while living in the owner's tree, so a subtree could hold rows
belonging to several people — and the storage it consumed was checked
against the writer while being counted against the owner.

Take the owner from the parent row at every insert, charge the
allowance to that owner, and hand a moved entry over to the tree it
moves into. An entry now always belongs to whoever owns the directory
holding it.

* feat(fs): address shared entries as ~/share/<uid>

A recipient could read the owner's whole path off any shared entry —
where they keep the file and what sits beside it, neither of which the
share is about.

Give shares their own namespace. `~/share/<entry-uid>/rel/path` resolves
to the real path on the way in, and outgoing paths are rewritten to it
on the way out. Entries the actor owns pass through untouched, so no
existing client contract moves.

* revert(fs): mask only the directory bar, not the addressing

fe535d598 made `~/share/<uid>` the actual address for every shared
entry. That reached far past the intent: item names became uuids, the
Shared views rendered uuids instead of filenames, and navigation
addressed entries through a namespace nothing else understood.

Put real paths back everywhere — responses, the share listing, and
request handling — and do the masking where it was wanted, in the
window's directory bar. A recipient sees `Shared › Contents › sub`
while every crumb keeps the real path it navigates to.

The share listing now carries the entry's name, content type, owner and
a signed thumbnail. A share row has no fsentry behind it for a client
to stat, and the stored thumbnail is an `s3://bucket/key` URI that no
client can render and none should see.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix: path obfuscation, webdav + small ui stuff

* test(share): assert the masked share path by its exact shape

The substring check tripped on the scratch files' own names, which start
with `sharing-`; the exact-equality assertion on `/<owner>/<uid>/<name>`
already proves nothing above the share leaks.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): rename policy, shared-view guards, webdav share parent, quota/bucket invariants

- Rename: a directly-shared FILE renames with write on it; a shared
  folder root stays fixed (its name is the owner's tree structure).
  GUI can_rename mirrors the backend, guards all editor entry points.
- Up from a share root goes to the Shared view on both surfaces; the
  Shared view gets a single crumb, a disabled Up button, and refuses
  drops, New/Paste, uploads and ctrl+V everywhere (it is a query, not
  a directory).
- WebDAV: PROPFIND on /owner/uuid answers as a virtual collection
  holding the share root (ACL-gated; 404 for strangers).
- Storage allowance override no longer crosses user boundaries: a
  recipient's plan cannot raise the owner's cap.
- Overwrites stay in the bucket the entry already lives in instead of
  repointing to the handling server's bucket and stranding the old
  object.
- manage mode documented as implying write (matches enforcement);
  share dialog label now "Can edit & share". Documented that fs socket
  events are owner-only.
- Sidebar: saved orders gain the Shared entry once the user has shares.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(share): close review findings, and retire /auth/grant-user-user

Security
- Recipient writes no longer echo the owner's real path back. The pending-write
  event and the upload-progress meta both go to the *acting* user, so a write
  into a shared folder handed out the layout above the share root.
- `maskerFor` failed open: the first caller fixed the actor, and one that ran
  before the request knew who was acting pinned `undefined` — after which every
  path published unmasked. It now adopts the first real actor and rebuilds for
  a different one.
- `/auth/grant-user-user` returns 501. It wrote user-to-user grants straight to
  the permission tables with no share row, so nothing could list or cascade a
  revoke over them — and the new `manage` mode meant a delegate could reach it
  for the owner's files. Filesystem access goes through `/share`; nothing else
  is meant to pass between two users. Undocumented (its docs page was never
  written) and no callers. Revoking is untouched, so grants made before this
  can still be withdrawn.
- `#assertCanManage` asks about the permission actually being granted rather
  than a fixed `read`, so sharing at `manage` is refused at the share layer
  instead of by `grantUserUserPermission` two levels down.
- `listSharedWithMe` checks the grants, not just the index: withdrawing access
  any other way left the row publishing name, size and a signed thumbnail URL.
- Moving an item into another tree now retires its shares. Grants are keyed on
  uuid, so they followed it and left the new owner with recipients they never
  agreed to.

Correctness
- `acl.check` gets the real path again, not the masked one. ACL matches on the
  path string, and a mask hides the `AppData/<appUid>` shape it needs.
- "Leave this share" works for a grant that predates the index; the fallback
  scoped the delete to the caller as issuer, which can never match.
- `move`/`copy` reject a name with a slash or a `.`/`..` segment, as `rename`
  already did. It matters more here: a move into the owner's Trash skips the
  destination write check.
- Descendant walks scope by path, not by owner, so rows predating the
  one-owner-per-subtree invariant aren't orphaned by their parent's deletion.

Performance
- Index `user_to_user_permissions(permission)`. Retiring a node's grants is a
  prefix match, but the primary key is (issuer, holder, permission), so it was
  a full scan.
- Retirement is coalesced and chunked. `remove()` emits one event per
  descendant, so deleting a directory fired one unindexed lookup per file, all
  at once and unawaited.
- `listReaching` is a plain `fsentry_id IN (...)` on `idx_share_fsentry`. It
  runs behind every file write, and the join-plus-OR it replaced was
  unindexable.

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Daniel Salazar <[email protected]>
2026-08-17 09:08:23 -04:00
Ayush tiwari fc861da89f feat: add Gemini 3.7 Flash (#3587) 2026-08-16 23:51:37 -07:00
Parman Mohammadalizadeh facb844747 fix: derive express subdomain offset from the configured root domain (#3575)
Express derives `req.subdomains` by dropping a fixed number of labels
from the right of the hostname, defaulting to 2. A deployment whose
`domain` has more than two labels therefore reads its own root domain as
an active subdomain, so the user-site redirect sends the root origin to
the static hosting domain, which sends it back. Self-hosting docs
recommend exactly that shape (`puter.example.com`).

Set the offset from the label count of `config.domain`. Two-label
domains keep the express default, so existing deployments are unchanged.

Fixes #3561
2026-08-16 23:48:20 -07:00
Yashwarhade8010 3b791bb334 docs: update web search examples to gpt-5.6-luna (#3589) 2026-08-16 23:45:02 -07:00
Daniel Salazar a64a444a17 feat: batch delete for flush + metering fixes (#3593) 2026-08-16 15:26:33 -07:00
Daniel Salazar d3c9828207 fix: metering gui maths (#3592) 2026-08-16 14:57:29 -07:00
Daniel Salazar 87180b1081 fix: metering (#3591) 2026-08-16 14:19:05 -07:00
Daniel Salazar d22b656df8 fix: metering issues with addons (#3588) 2026-08-15 22:06:51 -07:00
Nariman Jelveh 19cd5f4476 feat: add BytePlus ModelArk providers (chat, image, video) (#3498)
* feat: add BytePlus ModelArk chat provider

Adds BytePlus ModelArk as a provider for the puter-chat-completion
driver, following the MiniMax/ZAI providers as reference per
doc/contributing-apis.md.

- OpenAI-compatible endpoint at ark.ap-southeast.bytepluses.com/api/v3
  (apiBaseUrl config selects the region)
- Static catalog of 16 chat models (Seed 2.x/1.x incl. vision, GLM,
  DeepSeek, GPT-OSS) with limits and per-token pricing from the
  official docs
- Passes Ark's thinking/response_format/stop params through custom;
  normalizes reasoning_content to reasoning
- Bare deepseek-v4-* names stay with the first-party DeepSeek
  provider; BytePlus only claims prefixed aliases
- Offline unit tests (mocked SDK against a real test server) plus an
  env-gated integration test

* feat: add BytePlus image and video providers

Extends the BytePlus ModelArk integration to the puter-image-generation
and puter-video-generation drivers, reusing the same services.byteplus
API key and regional apiBaseUrl as the chat provider.

Image (Seedream/SeedEdit via OpenAI-compatible /images/generations):
- dola-seedream-5-0-pro (pixel-tier pricing + billed input images from
  the 2nd on), seedream-5-0-lite, 4-5, 4-0, and seededit-3-0-i2i
- quality tiers 1K/1.5K/2K; aspect ratios resolve to Ark's documented
  pixel sizes; explicit WxH passes through with Ark's bounds enforced

Video (Seedance via Ark's async /contents/generations/tasks + polling):
- Seedance 2.0 / 2.0 Fast / 2.0 Mini / 1.5 Pro / 1.0 Pro / 1.0 Pro Fast
  (2.5 is priced but its API isn't live yet, so it's excluded)
- per-video-token billing from usage.completion_tokens, with per-second
  estimates feeding the credit cap; audio vs silent rates for 1.5 Pro
- first/last frame and reference-image inputs; generate_audio param
  added to IGenerateVideoParams

Pricing and capabilities hardcoded from the official docs (ModelArk
pages 1544106, 1330310, 1520757, 1521309, 1541523). Offline unit tests
mock the SDK / global fetch; integration tests are env-gated on
PUTER_TEST_AI_BYTEPLUS_API_KEY.

* fix: correct BytePlus catalogs and validation against the live API

Verified the three BytePlus providers against ModelArk with a real key;
these are the mismatches that surfaced.

- Drop seededit-3-0-i2i-250628. Ark reports it as Shutdown and every
  request 404s. Its now-unreachable image-to-image branches in the
  provider go with it.
- seedream-4-5 and the 5.0 series enforce a 3,686,400 pixel minimum, so
  they only accept the 2K tier. Mark them 2k-only and snap an
  unsupported tier up to the nearest allowed one, which also keeps the
  aspect-ratio table from mapping to a sub-minimum size.
- glm-4-7 has a 204,800 token context, not 256K.
- Guard the actor in the image provider like the video provider does.
- Round a sub-minimum video duration up to the shortest supported clip
  instead of reporting it as insufficient funds.
- Gate video resolution on the model's own dimensions; the dims table is
  shared across a family and accepts more than any one model does.

* Tighten BytePlus AI provider handling

Extract shared reasoning-content normalization for OpenAI-style chat providers, and harden BytePlus image/video behavior. This updates image tier and size validation, normalizes aspect ratios and input image refs, prevents mismatched BytePlus key/base URL fallback config, makes video resolution matching case-insensitive, and rejects excess reference images instead of silently truncating them. Tests were expanded to cover the new BytePlus request and validation paths.
2026-08-15 21:08:17 -07:00
404oops fc56075115 Merge pull request #3584 from rupesh0001-tech/rupesh
feat(ai-chat): add grok-4.6 model to xai provider
2026-08-15 21:22:01 +02:00
404oops e1998e39ab Increase max_tokens limit to 500,000 2026-08-15 21:20:45 +02:00
Daniel Salazar fb7968a1c7 fix: metering hardening; handle burst of unfinished ai requests (#3585) 2026-08-15 10:52:29 -07:00
rupesh0001-tech c88eeb3868 feat(ai-chat): add grok-4.6 model to xai provider
- Add grok-4.6 model definition with pricing and context specs
- Add aliases x-ai/grok-4.6 and grok-4.6-latest
- Add unit tests for alias resolution and metering calculation

Closes #3562
2026-08-15 20:32:22 +05:30
Reynaldi ChernandoandCopilot Autofix powered by AI 9e25ce1401 [PUT-1478] Add KV commands to CLI (#3579)
* Add KV commands to CLI

* docs

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-08-15 11:43:30 +07:00
Daniel Salazar f15d835eeb fix: restrict openai and anthropic compatible endpoints to be subscription (#3583) 2026-08-14 18:55:15 -07:00
Daniel SalazarandClaude Fable 5 27c4506e02 feat: usage rendered as credits on a 50c base, free allowance doubled (#3569)
* feat: usage rendered as credits on a 50c base, free allowance doubled

Usage is now displayed in credits: a configurable creditsPerDollar rate
(default 2,000, making the free tier's 50c allowance an even
1,000-credit base) ships with the metering usage response, and the
dashboard's usage cards and per-API table show raw credit numbers
through one shared formatter. The dashboard budget math is also fixed —
capacity is spend plus server-netted remainder, so held purchased
credit can never render as negative usage. The registered-user free
allowance doubles to 50c, tier display names move to Basic/Plus/Pro,
and dead referral-promise strings leave the English dictionary.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor: the credits display rate exists only in deployment config

No default in code and no rate on any wire the plan surfaces read: a
deployment that doesn't configure creditsPerDollar renders usage in
dollars, exactly as before credits existed. The usage endpoint sends
the rate only when configured, and nothing in code or comments states
what any deployment's rate is.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor: metering reports pre-scaled credits, never raw amounts

The usage, per-app usage, and cost-catalogue endpoints multiply every
monetary field by the config multiplier (renamed creditMultiplier)
before responding, and flag the unit; the multiplier itself never
ships. Counts, units, and byte figures pass through untouched. With no
multiplier configured the endpoints report raw amounts and clients
render dollars, as before credits existed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: absent addon fields stay absent when scaling to credits

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 16:29:01 -07:00
Neal Shah 6a7c09f54e blacklist dynamic workers (#3582) 2026-08-14 18:35:34 -04:00
Reynaldi Chernando 6254714484 deprecate gemini 2 flash and lite (#3581)
* deprecate gemini 2 flash and lite

* fix test
2026-08-14 17:27:48 -04:00
Neal Shah efa2cb4441 add more extensibility to workers driver (#3565) 2026-08-14 17:24:36 -04:00
Nariman Jelveh 4bc969b99e Update RecommendedAppsService.ts 2026-08-14 14:05:44 -07:00
Reynaldi Chernando 65f6d38432 update gpt 5.6 luna and terra pricing (#3580) 2026-08-14 16:38:13 -04:00
Daniel SalazarandClaude Fable 5 d641f6f7a1 tests: count only this test's dynamo reads in the block-window assertion (#3576)
The spy sits on the test server's shared dynamo client, so a raw call
count also picks up background work and the async tail of earlier tests
in the file — which made the block-window test flakily report a third
read. Each test runs in its own random namespace, so filtering the
spy's calls to that namespace removes the cross-talk without loosening
the assertion.

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 11:05:25 -07:00
Daniel SalazarandClaude Fable 5 00828b9998 fix: concurrency limiter heals legacy INCR keys instead of failing open (#3574)
The zset rework of the redis concurrent backend (#3529) kept the same
key names the old INCR counter used. Against a leftover string key every
zset command in the acquire MULTI fails WRONGTYPE while the trailing
EXPIRE still succeeds — so steady traffic refreshes the stale key
forever, and the failed zcard result turned into NaN, which admitted
every caller unbounded. Release then errored WRONGTYPE on each request
(the '[concurrent] release failed' log storm).

Surface per-command MULTI errors instead of coercing them to NaN, and on
WRONGTYPE delete the legacy key and re-acquire against a clean zset.

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 01:40:05 -07:00
Daniel SalazarandClaude Fable 5 126ec09556 docs: publish rate limits and quotas, and make limit changes move the docs (#3568)
Developer-facing reference for every rate limit, concurrency cap,
quota, and error shape — an advanced page, since puter.js already turns
the common failures into prompts. AGENTS.md and CONTRIBUTING.md now
carry the rule that a PR moving any of these numbers updates the page
in the same PR: an undisclosed limit is one developers discover as a
service failure.

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 00:41:01 -07:00
jelveh 25a5799088 Update RecommendedAppsService.ts 2026-08-14 00:38:05 -07:00
Daniel SalazarandClaude Fable 5 ea2f9967a6 fix: over-quota batch uploads surface the storage prompt instead of failing quietly (#3566)
* fix: over-quota batch uploads surface the storage prompt instead of failing quietly

Partial batch failures now carry each item's code/status, and when every
failed item failed the same way the shared code/status is hoisted onto
the rejection itself — so an upload that exceeds the storage quota
rejects with storage_limit_reached/413 and the SDK's upload handler
shows the free-up-space prompt. A partial failure is also no longer
misread as the signed-batch endpoint being unavailable.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: out-of-storage copies prompt to upgrade the same way uploads do

Any fs operation the server refuses with 413 storage_limit_reached now
surfaces the upgrade prompt — the check that lived inline in upload's
error handler moves to a shared helper wired into the operation
scaffold's reject path, so copy/move/mkdir/rename get it too. The
desktop's copy/paste suppresses its generic alert for that code, since
the SDK dialog already explains the refusal and carries the fix.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 00:26:07 -07:00
Daniel Salazar ba9b885a5a Revert "feat: dashboard app search continues into the App Center (#3567)" (#3572)
This reverts commit 6cc241ac31.
2026-08-13 21:00:02 -07:00
Daniel SalazarandClaude Fable 5 6cc241ac31 feat: dashboard app search continues into the App Center (#3567)
A search that matches none of the user's own apps now puts the same
query to the App Center catalogue and renders the hits under the empty
state — debounced, filtered to apps the user doesn't already have, and
launchable in place.

Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-13 20:48:03 -07:00
Nariman Jelveh 7f8e24f06d fix: keep "Add an app" in the grid while searching
Typing in the Apps tab's search dropped the tail tile — deliberately, on the
grounds that a query asks which apps you HAVE and a tile matching nothing has
no business in the answer. That reads the search too narrowly: looking for an
app you don't have is the same gesture as looking for one you do, and the
moment the search comes up short is exactly when the way to GET an app is
worth having on screen.

So the tile is pushed unconditionally now, and a query that matches nothing no
longer replaces the grid with a bare "No apps match your search" — the line
moves above a grid holding just that tile. Keeping it a real grid, rather than
parking a tile inside the empty state, is also what keeps it reachable: arrows
and Enter only walk tiles inside .myapps-page, and the tail tile carries
tabindex -1 for the pager's roving focus.

The no-apps-at-all state is untouched: with nothing installed and nothing
typed, the empty state still stands in for the whole grid.
2026-08-13 18:53:59 -07:00
Nariman Jelveh 9b6627b1ea fix: an app's background helper must stay private to it
`launchApp(name, args, { background: true })` hid the child's window and
nothing else, so the instance was hidden but not private: it kept its
taskbar item, lit the running dot on its dashboard tile, and — because
the dashboard enforces one instance per app — WAS what clicking that tile
opened. Minimize the parent, click the child's tile, and Puter handed the
user the window the parent was mid-conversation with; the app, which only
ever meant that instance for its caller, said so on screen. Showing it
also dropped the never-shown marker, so from then on the helper outlived
its launcher and owned the tile.

Hidden now means unreachable. `user_facing_windows` is the one rule: of
an app's windows, the ones that are the user's. Everything the user
drives filters through it — the tile's reopen and its running dot and
Quit item, the taskbar item's click, window list and show/hide/close-all,
the file row's switcher and open-file dot, and the dashboard's
Back/Forward — so a helper is never focused, restored, listed, or counted
as running. With none of the user's own left, the tile simply launches a
fresh instance and the helper keeps serving whoever launched it. Paths
that act on the APP rather than on a window it happens to have open —
uninstall, and a launcher's close taking its helpers down with it —
deliberately keep the unfiltered list.

The taskbar item is now what a hidden launch EARNS by becoming visible,
rather than something it advertises from the start; makeWindowVisible
adds it (and fires the dots event) before showing, since focusWindow
marks an item active and needs it to exist. Windows stamp data-in_taskbar
when they take their place in data-open-windows, so the close path only
decrements a count it actually joined — otherwise a helper closing beside
the user's own window would zero the count and strip the item off a
window still open. For the same reason a helper's close no longer pops
the dashboard URL: it never claimed an entry (the push only happens for a
window created visible), and consuming one would minimize the user's
window of the same app.

is_unseen_background_window gains the other half of its own definition:
launched hidden AND launched BY another app. An app that is always
windowless (`background` on the app record) starts hidden too, but when
the user opens it there is nobody it is serving — it is the instance
their tile has to find, or every click would start another one they
cannot see.
2026-08-13 18:38:13 -07:00
Nariman Jelveh 7576e0b03a fix: route dashboard file menus by input modality, not touch capability
A mouse right-click on a file row in the dashboard Files tab opened the
mobile context-menu sheet (centered over the row, nowhere near the
cursor) on any touch-capable laptop or desktop, because phone/tablet
detection used navigator.maxTouchPoints > 0. The same check applied the
.touch-device class, degrading mouse selection and drag on those
machines.

Route by how the menu was invoked (the row's tracked pointer type) plus
isTouchPrimaryDevice() — coarse pointer and no hover — which is false on
touch-capable laptops but true on iPads whose UA claims macOS. Also let
sidebar-folder and background menus accept taphold on such iPads, where
they were previously unreachable (taphold dismissed, and iOS never fires
native contextmenu).
2026-08-13 17:46:58 -07:00
Nariman Jelveh d980a9f590 fix: don't invert full-color icons in the dashboard context menu 2026-08-13 17:33:14 -07:00
Nariman Jelveh d18ea1adb5 fix: a background app must not outlive the app that launched it
An app launched with `background: true` gets a real window from the moment it
starts, just hidden. Nothing ever took it down: when the app that launched it
closed, the child kept running with no way to reach it and no reason to be
there. On the dashboard the only sign was a running dot on a tile the user had
never lit up, and clicking that tile did nothing at all.

Three things were wrong, and all three had to go:

A window nobody has seen now dies with its launcher. UIWindow's close path
closes hidden children the closing app launched, keyed on a marker stamped at
creation. makeWindowVisible drops that marker the first time the window becomes
visible — showing itself with `puter.ui.showWindow()`, or the user showing it —
because from then on the window is the user's, and keeps running.

The dashboard tile is a real handle again. focusExistingAppWindow only routed
MINIMIZED windows through showWindow(); a hidden one fell through to
focusWindow(), which leaves it invisible while handing it the keyboard. With no
taskbar in dashboard mode the tile is the only handle on a background app, so
that click had nowhere else to go. It now asks whether the window is on screen
at all. The Files tab's row-click had the same one-line defect.

And a background instance can't take a tile from the user's own session: an
on-screen window wins, then a window the user has seen, then a hidden one.

Removing the child then hit a crash of its own: ExecService's `remove` handler
dereferenced the launcher's iframe to say goodbye, and the launcher was already
gone. Throwing there aborts jQuery's remove() itself, so the window stayed in
the DOM — running dot and all. That one also hit anyone closing a background app
from the taskbar after its launcher had closed.

The predicates behind all of this live in one helper, window_visibility.js, with
showWindow() reading the same `hidden, not minimized` rule it spelled out inline
before.
2026-08-13 14:36:08 -07:00
Nariman Jelveh 08f075d774 Update RecommendedAppsService.ts 2026-08-13 11:45:28 -07:00
Nariman Jelveh 664de0016b fix: a hidden window must not hold the keyboard
Launching an app to serve another one took focus away from the app the user
was working in, and they had to click it to get it back. Typing a guest name
into Calendar's event editor — which launches Contacts to read the address
book — dropped the user out of the field mid-word.

Four things conspired, all of them variations on "a window nobody can see is
treated as the window in front":

`window-active` was hardcoded into every window's markup, including windows
created hidden. focusWindow() — the thing that normally grants that class,
and strips it from everyone else — is already skipped for a hidden window, so
two windows ended up claiming it. It now follows the same rule as the
window_stack push a few lines above: visible windows only.

Both "focus the window once its IPC attaches" sites read that class to decide,
so a hidden child window pulled focus a beat after launching. Neither focuses
a window with data-is_visible="0" any more.

makeWindowInvisible left `window-active` on the window it had just hidden.
Since focusWindow() disables pointer events on every other app's iframe, an
app calling puter.ui.hideWindow() on itself left whoever launched it both
unfocused AND unclickable until the next click. It now hands activation back
to the top of the window stack, the way closing a window does, and drops
itself out of the activation order until it is shown again.

showWindow only ever un-minimized: for a window hidden by hideWindow() (which
keeps its geometry and writes no data-orig-*) every branch left it hidden and
stamped NaN geometry on it from the missing attributes. It now routes such a
window to makeWindowVisible. That is what makes the taskbar item a real
handle on a background app — clicking the item calls showWindow on the group.
2026-08-13 09:59:37 -07:00
Nariman Jelveh e273431f14 feat: let an app launch another app in the background
`puter.ui.launchApp(name, args)` had no way to say "I need this app's API,
not its window". That matters because we create and show an app's window
before the app's own code runs, so an app launched purely to serve another
one cannot avoid appearing on screen: the best it can do is call
`puter.ui.hideWindow()` once it boots, which reads as a window flashing
open and shut. In dashboard mode it was worse than a flash — the child
maximized into the tab and minimized its parent behind it, so asking a
service app a question took the user's app away from them.

So `launchApp` now accepts `background: true`, and the window starts
hidden. The app is otherwise entirely normal: it keeps its taskbar item,
so a user can see that it is running, show it, or close it, and it can
show itself with `puter.ui.showWindow()` whenever it has something to say.
Only a literal `true` counts, since the flag arrives over IPC from another
app.

The decision now lives in one predicate, `starts_hidden(app_info, options)`,
which folds this together with the existing app-level `background` flag and
is used everywhere the old flag was read — including the dashboard's
minimize-the-parent branch. `show_in_taskbar` deliberately still keys on the
app-level flag alone: an app that is always windowless has nothing to put in
the taskbar, while a background *launch* should stay visible there.

Existing callers are unaffected: with `background` unset, both paths
evaluate exactly as they did.
2026-08-13 09:47:35 -07:00
Daniel Salazar 8ed8feed4b fix: don't let an aborted upload take down the process (#3557) 2026-08-13 01:02:17 -07:00
Daniel Salazar 22f5bf5429 fix: duplicate emails (#3556) 2026-08-12 22:00:48 -07:00
Nariman Jelveh 198184f986 fix: drop the feedback dialog's rate limit entirely
Reopening still failed intermittently: any call the backoff refused looks
exactly like the user closing the dialog, so an app's "Send feedback"
button just did nothing, with nothing to see anywhere.

Rate limiting this dialog is not worth that. The other modals an app can
open with no user gesture — requestPermission, alert, prompt — have no
rate limit either, so one dialog at a time is the only rule left, and a
refusal now says so in the console.
2026-08-12 17:46:05 -07:00
Nariman Jelveh 026ae46530 fix: let an app reopen the feedback dialog after the user closes it
The abuse guard counted every dismissal that sent nothing as a strike
against the app, so closing the dialog blocked the app's next
showFeedbackDialog() for 10s, then 60s, then for the rest of the page's
life. The key is the app uuid, so relaunching the app did not clear it,
and a blocked call replies sent:false — the app just sees nothing happen.

Key the guard off how fast the app comes back instead. A reopen within a
second of the app's last dialog activity is machine-paced and gets the
same escalating backoff; attempts made while backed off count as activity
too, so a loop cannot wait out a tier and start from zero strikes. Any
human-paced reopen clears the app's record, so the tiers are only reached
by an app that reopens at machine speed several times running.

One dialog at a time, and a successful send clearing the record, are
unchanged.
2026-08-12 17:35:54 -07:00
Nariman Jelveh 0615c3aa3c feat: add "Show hidden" to the dashboard's folder context menu
The dashboard's files tab filtered out dot-files unconditionally, so
there was no way to reach them the way the desktop Explorer allows.
Add the same "Show hidden" toggle next to Refresh, driven by the
shared show_hidden_files preference so the two stay in sync, and dim
revealed rows with item-revealed like the Explorer does.

The socket-driven item.added path applies the same rule, so a hidden
file created elsewhere can't appear in a view that filtered its
siblings out.
2026-08-12 17:26:04 -07:00
Nariman Jelveh 748461aabb fix: show the new folder's row in the dashboard before mkdir answers (#3555)
* fix: show the new folder's row in the dashboard before mkdir answers

Both New Folder paths in the dashboard Files tab awaited mkdir before
drawing anything, so on a slow connection the button appeared to do
nothing for seconds. The toolbar path then did a full renderDirectory on
top of that -- a second round-trip, and with the default eventual
consistency the new folder could miss the listing entirely, leaving the
rename editor unopened.

Both now go through one createFolderInstant(), which renders the row
first: a locally predicted name (mirroring the backend's " (N)" dedupe
convention), a temporary uid, and the name editor already open. mkdir is
still asked for the plain "New Folder" path with rename: true, so the
server keeps owning deduplication; the prediction is only what we draw in
the meantime, and the row corrects itself if the two disagree. On failure
the row is withdrawn and the error is shown rather than swallowed.

Renaming is the next thing the user does and it needs the real uid, so
rename() awaits the create promise parked on the row. Everything else
that acts on the item -- open, menus, drag -- sits out while the row is
pending. mkdir's item.added comes back to the originating client (the
event carries no original_client_socket_id) and cannot match a temporary
uid, so _creatingItem still suppresses it, now as a counter: as a flag,
one create finishing uncovered another still in flight.

Two things found on the way:

- directory_depth_limit_exceeded had no translation key, so that alert
  (including the pre-existing desktop create_folder path) rendered the
  raw slug.
- The empty-directory notice is now restorable without refetching, since
  a withdrawn create has to put it back. It carries its own class because
  the loading overlay shares the same container.

Verified end to end against a dev backend with mkdir slowed to 3s:
toolbar and context-menu paths, rename and Escape before the response,
two overlapping creates, and a rejected mkdir.

* fix: don't draw the instant new-folder row while a listing is rebuilding

renderDirectory() clears .files before its readdir resolves, so a row
drawn during a load survives the clear and is left behind in whatever
directory the load lands on. Clicking the new-folder button while a
folder is still opening produced a row for `<old dir>/New Folder` sitting
in the new directory's listing, with the rename editor open on it —
clicking it navigated elsewhere and renaming it renamed a folder the user
wasn't looking at.

Drop the click while a rebuild is in flight, the same way renderDirectory
already drops navigation clicks that arrive while it renders.

* fix: stop drops onto a not-yet-created folder row from mangling files

A row drawn ahead of its mkdir carries a predicted path, but it was still
registered as a live drop target. Dropping a file on it called
move_items() with a destination that does not exist yet, and move treats
a non-existent destination as a rename target — so the dragged file was
silently renamed to "New Folder" instead of moving into the folder.
Reproduced against a slow mkdir: victim.txt became a 5-byte file named
"New Folder".

Sit the row out of the jQuery UI droppable (drop and the spring-load
hover) until the real fsentry lands, matching the guards already on
opening it, its menus and dragging it. The native-file dragster drop gets
the same guard: it uploads into the same predicted path.
2026-08-12 17:16:44 -07:00
Daniel Salazar 78cfe0c0f6 metrics: add metering buffer store coutns (#3554) 2026-08-12 15:55:03 -07:00
Nariman Jelveh 81f9f00fc0 fix: stop app feedback dialog clicks from focusing the iframe beneath
Clicking inside the feedback overlay (e.g. the textarea) reached
initgui's global mousedown -> focusWindow path: mouseover_window is
computed geometrically and is blind to the overlay, so focusWindow
focused the app window's iframe underneath — stealing keyboard focus
from the textarea and forwarding the click into the app.

Suppress it the established way (same fix as the dashboard app-group
panel): set window.mouseover_window = undefined in the overlay's own
mousedown handler, which runs before the document-level one; undefined
is the only value initgui's guard skips.
2026-08-12 15:00:32 -07:00
Nariman Jelveh 556380cf16 fix: keep app feedback send button blue on hover
The generic .app-feedback-btn:hover:not(:disabled) rule out-ranked the
.app-feedback-btn-primary:hover override (the :disabled argument inside
:not() counts toward specificity), so hovering Send repainted it with
the light --afb-hover background under white text. Strengthen the
primary hover selector so the blue gradient wins.
2026-08-12 13:42:11 -07:00
Daniel Salazar 908ec23eda fix: sanitize user data (#3552) 2026-08-12 12:08:54 -07:00
Juan Fernando Castro d5ae5a0049 🔧 PUR-1072: Flatten driver permissions to hardcoded values (#3545)
* refactor(permissions): drop hardcoded group permission map for a flat default

* test(drivers): assert credential-gate intent instead of a 403 proxy
2026-08-12 12:08:38 -07:00
Daniel Salazar 419d0aaa89 doc: update bounty doc 2 (#3551) 2026-08-12 09:56:34 -07:00
Daniel Salazar c3a0c28705 docs: update bug bountu (#3550) 2026-08-12 09:55:13 -07:00
Nariman Jelveh 7ceb2090b7 feat: app user feedback system (#3546)
* feat: app user feedback system

Add puter.ui.showFeedbackDialog(), letting users send feedback to an
app's developer. In the app environment the Puter desktop renders the
dialog; on a third-party website a puter.com popup hosts it. The message
is stored in a new app_feedback table and emailed to the app owner's
confirmed email — it never passes through the app's own code.

Feedback is strictly opt-in per app via a new apps.feedback_enabled
column (a real column, not an app-metadata key, so Dev Center's
whole-blob metadata saves can't silently erase it), settable through the
existing puter.apps.update path (feedbackEnabled).

Backend follows the layered stack: AppFeedbackStore (durable count
queries) -> AppFeedbackService (opt-in check, message normalization,
abuse caps, best-effort owner email) -> AppFeedbackController
(POST /app-feedback, GET /app-feedback/target). New app-user-feedback
email template uses the escaping-safe nl2br triple-stash.

Defensive by design:
- requireUserActor blocks app tokens, so feedback can't be submitted
  programmatically; guiOriginOnly keeps cross-origin pages out.
- App identity comes only from the validated IPC sender (desktop) or the
  browser-attested opener origin (popup), never from message contents.
- The send-feedback popup action is in NON_AUTH_POPUP_ACTIONS, so it
  never delivers a token to the opener.
- Layered limits: route rate limits, plus DB-count caps that fail closed
  when the limiter backend is down, plus a per-app daily owner-email cap.
- Owner email is fully best-effort: an unconfigured transport,
  unconfirmed/unsubscribed/suspended owner, or send failure never fails
  the request or blocks storage.
- The dialog and SDK method are resolve-only and always settle, so a
  caller is never left hanging.

Migrations for sqlite/mysql/postgres, puter.js types, docs, backend
tests (sqlite + postgres), and a Playwright e2e spec are included.

* feat: add feedback control to the dashboard app-drawer

Surface the feedback dialog directly from the app window's chrome in
dashboard mode: apps that opt in (apps.feedbackEnabled) get a "Send
Feedback" button in the dashboard app-drawer, next to minimize/close.
It opens the same UIWindowAppFeedback dialog, targeting this app by uid.

The control is only rendered when the app opted in — feedback_enabled is
threaded from the launched app's metadata into the window options — and
the dialog still re-checks opt-in server-side, so a stale flag can't send
anywhere. Reuses the existing .dashboard-app-drawer-btn styling and the
app_feedback_title i18n string, so no new CSS or strings.

Adds e2e coverage: the control appears and opens the dialog for an
opted-in app, and is absent for an app that hasn't opted in.

* feat: enable app feedback by default in Dev Center

New apps created in Dev Center now have feedbackEnabled set on creation,
so users can send the developer feedback without any extra setup. A "User
Feedback" toggle in the app's settings lets developers turn it off (and
back on); it's wired into the save payload, the dirty-state tracking, and
the reset-to-original path like the neighboring toggles.

The Save update omits feedbackEnabled unless the toggle is present, and
the backend leaves an omitted field untouched, so the default survives
the create-then-save flow Dev Center runs. Add an SDK apps-suite guard
covering that round-trip (create-on -> unrelated update keeps it -> can
be turned off).

* fix: feedback modal polish + share sender email

Address four issues with the app feedback UI:

- Dashboard app-drawer: the extra "feedback" control pushed the close
  button past the drawer's derived width and clipped it. A `has-feedback`
  modifier widens the surface by one button + gap so all three controls
  fit. The control's glyph is now a message bubble with text lines, which
  reads more clearly at 14px than the previous bare speech bubble.

- The feedback dialog is no longer a UIWindow. It's a from-scratch
  overlay modal in the spirit of the dashboard modals (uninstall,
  add-app): a fixed scrim + centered card with self-contained,
  theme-aware color tokens (light default + dark override), a bottom-sheet
  layout on narrow screens, backdrop/Escape close, and an entrance
  transition. This renders consistently across the three contexts it's
  opened from (desktop app-IPC, dashboard drawer, standalone popup), so
  the callers no longer pass UIWindow-specific window_options.

- Feedback now shares the sender's email (not just their username) with
  the developer so they can respond: the owner email sets Reply-To to the
  sender and shows the address in the body — but only when the sender's
  email is verified (an unverified address could be anyone's, so it's
  never used as a reply target). EmailClient.send gains an optional
  replyTo. The dialog note now says the email will be shared.

Tests: e2e updated for the new modal (7 pass); backend feedback suite
covers the verified/unverified sender-email split (sqlite + postgres);
EmailClient + GUI unit suites pass; type-check clean.

* fix: resolve 'app-'-prefixed app names in feedback target lookup

APP_NAME_REGEX allows names beginning with "app-" (e.g. the seeded
app-center), but resolveTargetApp's startsWith('app-') heuristic sent
those to a uid-only lookup with no name fallback, so feedback for such
apps 403'd even when enabled. Use AppStore.resolveApp (uid, then name)
like the rest of the codebase.

* fix: make feedback daily caps fail closed under concurrent submissions

The per-user and per-user-per-app caps were check-then-insert and the
per-app email cap was count-then-send, so parallel requests (or multiple
nodes, or the route limiter failing open) could all read a stale
under-cap count and push past every limit — the exact scenario the
DB-backed caps exist to stop.

Now the user caps recount after the insert (own row included) and roll
the row back with 429 if a burst breached them, and the email cap claims
its slot (email_sent=1) before sending, recounts, and releases the slot
if over cap or if the send fails.

* docs: disclose the Dev Center's feedback-on-by-default in SDK docs/types

The Dev Center deliberately creates apps with feedbackEnabled (see
32c950de5), but the SDK docs, apps.d.ts, and AppFeedbackService's class
doc all described feedback as strictly opt-in / default-false with no
qualification — so a Dev Center developer reading them would wrongly
conclude feedback is off for their app. State the Dev Center behavior
alongside the API default, and correct the update-path docs: an omitted
feedbackEnabled leaves the current value unchanged rather than
defaulting to false.

* fix: don't mint a user-app token as a side effect of the feedback popup

Every embedded_in_popup boot ran the user-app token exchange, and the
exchange is a write: /auth/get-user-app-token bootstraps an app row for
the opener origin, grants flag:app-is-authenticated (what makes the
site count as connected to the account), and creates its AppData dir.
So merely opening — or immediately cancelling — a send-feedback popup
recorded a user<->site relationship the read-only feedback flow never
needs: the server resolves the feedback target from the attested origin
without any of it.

Gate the exchange behind runsUserAppTokenExchange(action) in all three
popup paths that mint (main postAuthActions exchange, temp-user signup
success, manual signup fallback). request-permission keeps the exchange
since grants are written against the app row it bootstraps.

* fix: refuse feedback when the deployment cannot deliver it

With no email transport configured (the common self-hosted default),
submissions were stored in app_feedback — a table with no read path
beyond the abuse-cap COUNTs — the owner email was silently skipped, and
the sender was still shown 'Feedback sent. Thank you!'. The developer
never learns the feedback exists while the user believes it was
delivered.

Gate acceptsFeedback on clients.email.isConfigured so the pre-flight
reports enabled:false (the dialog shows its 'not accepting feedback'
pane) and submit returns 403 instead of swallowing messages. Owner-level
store-without-email cases (unconfirmed owner email, per-app email cap
overflow) keep their existing deliberate semantics.

* fix: settle showFeedbackDialog instead of hanging on older host GUIs

In the app environment showFeedbackDialog awaited an IPC reply with no
capability check. A host GUI that predates this feature (self-hosted
Puter running the live js.puter.com SDK) has no handler for the message
and never replies, so the promise documented as 'never rejects' also
never resolved.

The GUI now advertises the IPC dialogs it can answer via a
puter.gui_features param on the app iframe URL, and the SDK resolves
false when 'feedback-dialog' isn't listed. A reply timeout could not
substitute: legitimate replies only arrive when the user closes the
dialog, so any timeout would false-negative while the user is typing.
Older SDKs ignore the extra param.

* fix: guard app-triggered feedback dialog against desktop-lockout loops

The showFeedbackDialog IPC handler had no re-entry or abuse guard, and
the dialog it opens is a full-viewport overlay above the taskbar and
every window — so 'while (true) await puter.ui.showFeedbackDialog()'
kept the desktop permanently covered (for signed-out users, the same
loop spams the full-page signup window instead). Every dismissal just
settled the promise and let the app immediately reopen it.

Allow one dialog at a time, and back off reopens per app after each
dismissal that sent nothing: 10s, then 60s, then blocked until page
reload. A successful send resets the backoff, and user-initiated paths
(dashboard drawer) are unaffected since they don't go through IPC.

* fix: carry feedback_enabled in suggested/recommended app summaries

launch_app uses options.app_obj verbatim when provided, and the
suggested-apps launch paths (open_item.js, UIWindowSearch.js,
UIDesktop.js) pass summaries from toAppSummary — which omitted
feedback_enabled. So an opted-in editor launched by opening a .txt file
showed no Send Feedback control in the dashboard drawer, while the same
app launched from the Apps tab (full puter.apps.get object) did.

* fix: gate feedback dialog Cancel/X on an in-flight submit

Escape and backdrop clicks were already ignored while the POST was
pending, but the X, Close, and Cancel buttons weren't — clicking one
mid-send settled the promise false and tore down the overlay while the
submission still landed server-side: the developer got the email, the
app was told sent=false, and a user who resubmitted 'the failed one'
sent a duplicate and burned a daily-cap slot.

Apply the same !sending gate to the buttons and disable them visually
while the send is in flight.

* fix: reject feedback origins longer than the source_origin column

readTargetParam accepted values up to 3000 chars but the raw origin is
stored verbatim into source_origin VARCHAR(2048) (MySQL/Postgres), so a
2049-3000 char origin passed every validation and then blew up the
INSERT with an HTTP 500 on Postgres/strict MySQL — or was silently
truncated on non-strict MySQL, corrupting the abuse-forensics value the
column exists for. Cap the param at the column size.

* fix: make the feedback dialog's privacy note match what is shared

The note unconditionally said 'Your email address will be shared with
the developer so they can respond', but AppFeedbackService shares the
username always and the email only when it exists and is verified — an
unverified or temp-user sender was promised a reply path that never
materializes, and nobody was told about the username.

Show 'username and email' when the signed-in user's email is verified,
and 'username' otherwise.

* fix: stop HTML-escaping email subject lines

Subjects were compiled with default Handlebars escaping, so the
app-user-feedback subject rendered a title like "Bob's App & Games" as
"Bob&#x27;s App &amp; Games" — literal entities in the recipient's mail
client. Subjects are plain-text headers, not HTML; compile them with
noEscape. Header safety is unaffected: the transport encodes newlines
and free-form values collapse whitespace upstream.

* docs: state exactly what showFeedbackDialog shares with the developer

The doc claimed the dialog 'tells the user their username will be
shared', while the dialog's note talked only about the email address and
the implementation shares the username always plus the email (as
Reply-To) only when verified. Describe the actual disclosure: username
always, email when verified.

* docs: document the COOP false-resolve limitation of showFeedbackDialog

Under COOP the popup's opener link is severed, so the SDK deliberately
resolves false while the popup stays open and the user can still submit
(a feedback submission has no server read-back the way a permission
grant does). The documented contract ('resolves to true if the user
submitted feedback') was silently wrong on cross-origin-isolated pages —
state the limitation in the doc and the SDK jsdoc: false means 'not
confirmed', not 'not sent'.

* feat: point the feedback email footer at the Dev Center

The footer told developers to turn feedback off via a puter.apps.update
one-liner, but the toggle lives in the Dev Center app settings — and
Dev Center is where apps get feedback enabled by default in the first
place. Reword it to 'manage it in the Dev Center' with a link built
from config.origin (like app_link) so it holds on self-hosted
deployments.

* test: cover the feedback service and store layers directly

The service owns every feedback business rule — target resolution,
eligibility, message normalization, the durable caps, and the owner-email
preconditions — but was only reachable through the controller's tests. Give
it and the store their own suites so a regression names the layer it broke.

Service coverage adds the branches the route tests could not reach: a
blocked origin resolving to null rather than surfacing a 403, owners who are
suspended or unsubscribed, length measured after normalization, the 24h cap
window boundary, subject-header injection via the app title, and the email
links being rooted at config.origin.

The two describes already labelled `AppFeedbackService ...` move out of the
controller test, which keeps only the caller-facing promise that a failed
send still returns success.

* refactor: prep the feedback cap error once instead of via a factory

Both throw sites are in one call and only one can ever run, so a plain
const reads the same and drops a function that existed only to defer a
constructor.

* Require verified users for app feedback API

Add `requireVerified: true` to both app feedback routes (`GET /target` and `POST /`) in `AppFeedbackController`. This tightens access control so only verified user accounts can fetch feedback targets or submit app feedback.
2026-08-12 09:49:24 -07:00
jelveh ea63c3093e feat(dashboard): add Publish as website and Properties to folder menu
The Files tab's folder-background context menu (empty listing area,
sidebar folders, breadcrumb segments) now offers Publish as website and
Properties for the folder the menu was opened on, matching the desktop's
folder menus. Both are omitted at the filesystem root and in Trash, and
Publish is omitted inside trashed folders.

The properties modal can now resolve an entry by path when the caller
has no uid, which the folder-background menu doesn't.

The publish gate (account creation + email confirmation) was duplicated
in three places, so it moves to a publish_as_website helper that all
call sites now share.
2026-08-12 08:50:03 -07:00
Daniel Salazar e8236a100c chore: bump versions (#3548) 2026-08-12 01:18:17 -07:00
Daniel Salazar 20b3b88e39 metering: big fixes to metering + jsdoc types (#3547)
Changes are:
- global egress metering
- remove file egress cost
- introduce file op cost for the per request cost s3 has
- enforce fs read/download etc to through 402 when out of usage; allow for subdomains
- enforce kv metering when out of usage through 402; allow for workers
- jsdoc as source of truth for puter.js types
- kv driver caching for get and batchget operations with decreased costs
2026-08-12 01:06:04 -07:00
Chen, Ting-An cbae39a08f fix(i18n): add Traditional Chinese app management strings (#3541)
Translate the app discovery, app request, desktop shortcut, and app folder controls that currently fall back to English in the Traditional Chinese interface. Preserve the positional placeholders used by accessibility labels.
2026-08-11 21:18:37 -07:00
Daniel Salazar afad3e37bf fix: server health tolerance for primary read (#3542) 2026-08-11 01:19:09 -07:00
Daniel Salazar a6b2161b2c fix: misc sec fixes (#3540) 2026-08-10 22:24:44 -07:00
Neal Shah 9e864e9574 PUT-1432 (#3539) 2026-08-10 23:33:20 -04:00
Daniel Salazar 79d4201f12 fix: rate limits, AI routing, and a type-check gate (#3529)
- declare rate + concurrency limits on every route and driver that lacked one
- add acquireConcurrent for websocket connections and the DAV mount
- bucket AI models by identity key only; keep resold duplicates of any vendor
- skip recently-failed provider routes; cap the fallback chain at 3 attempts
- let full-access access tokens bind a worker to an app their own user owns
- cache resolved subscriptions so tiered limits don't add a round trip
2026-08-10 19:09:47 -07:00
Daniel Salazar 0c2d7dfa34 feat: add user created timestamp on whoami (#3538) 2026-08-10 19:08:50 -07:00
Neal Shah 2a6d2fea32 allow max-tokenless models on openrouter (#3536) 2026-08-10 18:40:10 -04:00
Juan Fernando Castro 1dec5e90c4 docs: add requestAppData() to Perms sidebar (#3534) 2026-08-10 11:38:09 -07:00
Neal Shah 566298d89c make context length on togetherAI more lenient (#3533) 2026-08-10 13:14:33 -04:00
Daniel Salazar 6bb5eacf61 fix: metering kv spamc (#3532) 2026-08-10 08:36:56 -07:00
Reynaldi Chernando 390a83c860 Fix puter.js docs and types drift 10 aug (#3531) 2026-08-10 12:47:18 +07:00
Nariman Jelveh 8f23bf7b75 fix(gui): hover the add-an-app options with the accent wash, not grey
The rows already answer hover with a --select-ring border; filling them
with the grey --dashboard-hover under that accent ring read as two
systems disagreeing. The weak select tint keeps the hover in one voice
and stays under the icon chip's stronger tint in both themes.
2026-08-09 18:23:07 -07:00
Nariman Jelveh aa85dddd38 Refresh Add App AI description copy
Update the English `add_app_ai_desc` translation string in the GUI to a more direct, enthusiastic message: “Describe the app you want and AI will build it!”.
2026-08-09 18:21:31 -07:00
Nariman Jelveh 8284f35b93 fix(gui): honor godmode file_paths launches now that /apps returns booleans
The godmode gate in ExecService.launchApp checked `godmode === 1`, but
GET /apps/:name serializes the flag as a boolean, so the check always
failed and file_paths launches (e.g. Dev Center opening a worker's
source in the editor, #2218) silently dropped the file. Accept both
shapes, matching the existing guard in launch_app.js.

Also fix the two issues hiding behind that gate:
- puter.apps.get returns `uid`, not `uuid`, so the /sign call for the
  target app sent app_uid undefined — no write grant and no user-app
  token for the launched app. Use `uid` with a `uuid` fallback.
- The closeApp IPC handler had the same `godmode === 1` comparison,
  preventing godmode apps from closing other apps' windows.
2026-08-09 18:06:58 -07:00
Nariman Jelveh ccec3ce39b fix(gui): open add-an-app choices through the deep-link intro, not a + tile morph
60686643b made App Center and the AI builder morph out of the + tile the
user clicked, which answers where the window came from but not the
question these two options exist to answer: where the APP went. The grid
never showed it arriving, so the user still ended a launch with nothing
to find, no tile for minimize to fly back to, and no lesson learned.

Choosing either option now plays exactly what an /app/<name> landing
plays (beginDeepLinkLaunch): when the app already has a tile the intro
travels to it, plays the click flourish, and the window grows out of the
app's own slot; when it doesn't, the tile is INSTALLED first — the slot
opens, the progress stroke draws, the icon springs in — and only then
does the window morph out of the tile that just arrived. Same beats,
same exposure decay, same interruptibility, same duplicate-launch claim.

The app info is prefetched in parallel and handed to launch_app, the
same contract as initgui's landing path, so the intro (which may need to
draw the arriving tile from it) never costs a second round-trip.

This also reverts 60686643b's anchor plumbing (UIWindow's
dashboard_tile_el option and the dashboard_tile_in_view export): the
intro installs a real tile for the by-app-name morph to find, so no
stand-in anchor is needed.
2026-08-09 18:02:39 -07:00
Nariman Jelveh 60686643b3 fix(gui): launch from the add-an-app modal with the tile morph, not a fade
Choosing App Center or the AI builder opened the window with the plain
fade while every other launch in the Apps tab grows out of the icon that
was clicked — the one launch that most needs to say where it came from
read as the app appearing from nowhere.

The morph resolved its anchor by app name, which cannot work here: the
whole point of these two options is installing an app you do not have,
and an app with no tile has no name to find. So the launcher may name its
anchor element (dashboard_tile_el), and TabApps resolves it once before
launching so the click flourish and the window's half can never disagree
about which tile the launch came from: the app's own tile when it already
has one on screen — minimize flies the window back there, so that is
where opening should come from — and otherwise the + tile itself.

dashboard_tile_in_view's visibility test is now a named helper it shares
with the new path, so an anchor on an offscreen pager page is still
rejected and still falls through to the fade.
2026-08-09 17:49:50 -07:00
Nariman Jelveh 61bfcbdc83 feat(gui): add an add-an-app tile at the end of the Apps grid
The Apps grid showed what you have and offered no way to get more. A
dashed plus tile now rides at the tail of every page of it: after every
app, on the last page, and nowhere else. It wears the same tile skeleton
as an app so hover, focus, and arrow keys treat it identically, but
carries no app name or group id — which is what keeps it out of the
saved order, the running dots, and the deep-link tile lookups. It cannot
be picked up, is never a drop target (so no app can land past it), has
no context menu, and sits still while the apps jiggle in reorder mode.
Search results leave it out: a query asks which apps you have.

Clicking it asks how you would like to get an app: find one in the App
Center, have one built by the AI builder, or request one that does not
exist yet. The request is a form in the same card rather than the stock
Contact Us window — a titled pane one step deeper, whose Back arrow
returns to the options with the draft intact. It posts the same
/contactUs request that window did; a failure is said inside the form,
where the request is still there to retry, rather than in an alert
window the next click on the dashboard would bury.
2026-08-09 17:37:09 -07:00
Nariman Jelveh c8985b621d Add copy-link support for app tiles
Extract app tile URL generation into a shared helper and use it for a new dashboard context menu action that copies the tile's destination. This keeps copied links aligned with the existing open-in-new-tab behavior and adds regression coverage for app, external, encoded, and folder tiles.
2026-08-09 16:54:18 -07:00
Nariman Jelveh 42299a64ed Update recommended apps list
Add 'blockarena' and remove 'pretty-tiles', 'galaxy-troops', and 'blend-fruits' from the recommended apps list.
2026-08-09 11:20:40 -07:00
jelveh 344db5cb0b Remove vault from recommended apps
Drop `vault` from the recommended apps list so it no longer appears in app recommendations.
2026-08-08 11:54:56 -07:00
jelveh 66824f607d feat(gui): install an app onto the grid when its landing is what installs it
A /app/<name> landing for an app the dashboard didn't list opened with
a plain fade and left the app NOWHERE: the grid had been fetched before
the launch granted the permission that installedApps reports, so Back
found no tile to minimize into and the user landed on a dashboard
without the app they were just inside. The round trip that teaches
"windows are inflated tiles" broke on exactly the landing where a new
user is forming that model.

Now the landing SAYS what it does. The app joins the grid at the tail
(where new apps land) with a tile drawn from the landing's own app-info
prefetch -- only a confirmed-real app ever materializes, with its real
icon -- held invisible until the intro has revealed the grid and
travelled to the tile's page, and then it is INSTALLED, in the grammar
every app store taught: the slot opens (the folder well's own surface)
with the icon dim inside it, a progress stroke draws clockwise around
the slot, and on completion the icon springs to full color and size as
the label names it. Only then does the flourish play and the window
grow out of the tile. The arrival is the one beat that never decays:
per-app news delivered at most once per app, not a repeated lesson.
Minimize now has a target, and the app is simply there afterward.

The regression surface is guarded on every edge: the parked-invisible
state is re-applied by renderApps itself so mid-intro re-renders can't
strip it, and settleDeepLinkLaunch -- which the landing's finally
always reaches -- force-reveals it, so no path leaves an invisible
tile. A _pendingInstalls overlay (the mirror of _removedLocal) keeps a
refresh fetched before the grant lands from evicting the tile, and
retires itself once installedApps confirms the app or the user
uninstalls it again. The order is never saved on the splice, so the
default-position append can't freeze a custom order the user never
made. Failed or absent app info adds nothing; installed-app landings
are untouched; animations-off and reduced-motion users skip the
choreography but still get the tile, silently. The progress ring is a
transient element (the tile's ::before is the well, its ::after the
running dot) drawn as an SVG dashoffset sweep -- no Houdini dependency
-- and the app-info prefetch now asks for the 128px icons every other
tile already uses.
2026-08-08 11:25:48 -07:00
jelveh 66dedf3082 feat(gui): let the app drawer's intro flash retire once learned
The control drawer on headless dashboard apps opened itself on EVERY
window open, forever -- 2.6 seconds of tray over the app's own top
edge to teach a lesson (the controls live in this tongue) that is
learned in a few exposures. Same doctrine as the dashboard's
deep-link intro: pedagogy that knows when to step aside.

A per-account kv counter records deliveries, once per window: a flash
played while the user could see it, or the user opening the drawer
themselves (hover, tap, focus) -- the stronger proof, since the
drawer is a headless app's only chrome and must never decay out of a
user's awareness. After three, new windows keep the bare tongue and
the flash stops; hover, tap, and focus expansion never decay.

The attach is synchronous and the stored count is not: the first
drawer of a session races the read against a short cap and defaults
to teaching -- a hung read must not hold the intro hostage, and every
failure mode (unparseable value, failed read, timed-out read, failed
write) errs toward teaching once more, never toward never teaching.
The resolved count is cached and kept current in memory, so later
windows decide synchronously and a session's own not-yet-written
increments still count. kv.incr keeps two devices from losing an
increment, and the pre-read caps the key once the lesson is learned.

If the user beats a still-deciding flash to the drawer, the flash is
skipped rather than played over their hand -- its auto-collapse would
shut a drawer they are actively using. A flash in a hidden tab still
defers to first reveal (it rides requestAnimationFrame, as before)
and an unseen one is never counted.
2026-08-08 10:25:26 -07:00
Daniel Salazar 95da802b13 fix: metering hardening (#3527) 2026-08-08 06:10:01 -07:00
Daniel Salazar 0491d5fea7 fix: mcp better uploads (#3528) 2026-08-08 06:09:49 -07:00
Juan Fernando CastroandDaniel Salazar d202be10a9 feat: let apps use another app's data with user consent (#3516)
* feat(perms): add cross-app app-data permission vocabulary

* feat(perms): sweep app grants by permission prefix

* feat(perms): resolve and withdraw cross-app data grants

* feat(kv): support an authorized namespace override and per-key privacy

* feat(kv): gate cross-app KV access behind app-data grants

* feat(fs): allow cross-app AppData access and require a scope to delete

* feat(auth): accept permission lists and gate app-data grants

* feat(perms): add requestAppData to the puter.js SDK

* feat(gui): carry permission lists through the IPC and popup transports

* feat(gui): describe cross-app data requests in the consent dialog

* docs: document requestAppData and per-entry KV privacy

* perf(perms): sweep cross-app grants only for origin-bootstrapped apps

* fix(gui): stop double-encoding cross-app consent text

* fix(perms): close three gaps in cross-app grant enforcement

* fix(kv): meter and batch the per-entry privacy probe

* fix(perms): resolve app identifiers and scopes more strictly in the SDK

* test(perms): cover the cross-app consent flow end to end

* fix: small missing token resolution for app

also adds the same exclusion for the batchPut api, small change

* fix: make resolved actor optional

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-08-08 04:04:07 -07:00
jelveh 2c17476c07 fix(gui): folder pages, live drag-out, and one merge pulse in My Apps
Three fixes to the My Apps folders:

A folder big enough to need it now paginates like the grid outside
(iOS folders page too) instead of growing a scrollbar: pages of
cols x 3 tiles in a scroll-snap scroller with dots below, wheel and
swipe to flip, and a drag held at the card's edge flips folder pages
so reordering works across them. The card's height stays constant
across pages, and a deep-link landing on an app that lives on a later
folder page travels there before the launch morph.

Dragging an app out of the open folder no longer drops it blind:
after a beat held outside the card, the app leaves the folder, the
card closes behind it, and the SAME drag carries on over the grid --
placeholder shuffle, edge page flips, even a drop into another
folder -- so the app lands where the user watched themselves put it.
A quick drop during the beat still lands beside the folder, and
swinging back inside within the beat cancels cleanly.

The folder well's fill played twice on nearly every merge: the rest
countdown anchored at first contact with the target, so the hand
decelerating INTO the tile always read as movement when the dwell
elapsed, and the deliberate refill-from-empty replayed the fill. The
countdown now re-anchors on the move events themselves -- rest is
only visible at its edges -- so the fill that completes is the one
started by the last movement, played exactly once.
2026-08-08 01:28:09 -07:00
Nariman Jelveh 06d94534e8 feat(gui): iOS-style app folders in the My Apps grid (#3525)
* feat(gui): iOS-style app folders in the My Apps grid

Drag one app onto another and let it settle: a well opens under the
target and the drop makes a folder of the two. Dropping onto an existing
folder joins it. A folder opens by growing out of its own icon into a
card over a blurred grid, where its apps can be launched, rearranged,
renamed, or carried back out.

Hovering a tile mid-drag means two things — "push over, I'm passing
through" and "swallow me" — and the tile is barely bigger than its icon,
so pixels can't separate them; motion does. The shuffle is held while
the folder offer stands and fires when the icon leaves the tile, or at
the drop, so a quick drop onto a neighbour still reorders exactly as it
did. The offer itself re-arms rather than cancelling on movement: the
last events of a drag are the ones carrying the icon onto the target and
nothing is dispatched while it rests, so a cancel-on-movement dwell
could never fire at all.

Folders are stored in their own kv key; the grid's ORDER stays entirely
in the existing saved app order, with a folder occupying its first
member's slot and its members contiguous. Every saved order therefore
stays valid with no migration, and an app whose installedApps page
failed to load keeps both its folder and its position. Folders never
nest, one that drops below two apps dissolves, and a corrupt kv value
degrades to "no folders" rather than a broken tab.

Elsewhere:
- Search looks THROUGH folders — a match the user then has to hunt for
  inside one is not an answer.
- Minimize morphs into the FOLDER when an app lives in one, and a
  /app/<name> landing opens the folder so the launch grows out of the
  icon where the app actually is.
- The uninstall FLIP keyed surviving tiles by app name, which a folder
  tile doesn't have; it now keys by identity.

New pure model in appGroups.js with tests; verified end to end in the
running dashboard (create, join, open, rename, reorder, eject, ungroup,
launch-from-folder) alongside plain reorder, search, and uninstall.

* fix(gui): keep the folder name field from inheriting input[type=text] sizing

style.css styles every input[type=text] with `width: 100%` and grows it to
`padding: 7px; border: 2px` on focus. `input.myapps-group-name` matches at the
same specificity, so it only wins the properties it actually declares — width
was never one of them, and the focus rule declared neither padding nor border
width. The name field therefore spanned the entire folder card (so its hover
and focus chip read as a full-width bar rather than the name) and grew 8px
taller the moment it was clicked, shoving the folder's app grid down.

Spell the three out, in both the resting and the focus rule — the same trap
.myapps-search already documents next door.

* fix(gui): size folder icon ghosts to the icon they stand on

Border-box only reaches a folder's icon through `.dashboard * { box-sizing }`,
and every ghost cloned from one is appended to <body>, outside that rule: the
drag ghost, the click-time launch flourish, and the open/minimize morph ghosts
all fall back to content-box, where .myapps-group-icon's 5px padding is added
to the 56px slot. Each ghost rendered 66px square and 5px off, so it visibly
popped at exactly the moment it was supposed to sit flush on the real icon.

State box-sizing on the rule itself so a clone carries it wherever it lands.

* fix(gui): stop a closing folder from swallowing the next click

_closeGroup drops the open class and leaves the overlay in place for
GROUP_PANEL_CLOSE_MS so the card can recede into its tile. The scrim is
`position: fixed; inset: 0` and still hit-testable for that whole quarter
second, so a click on the grid during it landed on the outgoing overlay — whose
handler only re-runs _closeGroup, now a no-op. Shutting a folder and reaching
straight for an app did nothing.

Take the outgoing overlay out of hit-testing; it has no interactive job left.

* fix(gui): keep a folder name typed right up to the moment it closes

The name box commits on blur, and every exit that goes through a pointer blurs
it while the folder is still open — so clicking outside, or launching an app
from inside, keeps what was typed. Escape does not: _closeGroup clears
_openGroupId first and only then moves focus to the tile below (or removes the
card outright), so the blur arrives with no open folder to rename and
_renameGroup drops it. A brand-new folder opens with its name selected for
exactly this edit, so "type Games, press Escape" — the obvious way to dismiss
a dialog — was the path most likely to lose it.

Commit the pending name on the way out, before the folder id is gone.

* fix(gui): close an open folder when the Apps tab is re-entered

The dashboard hides an inactive section and calls onActivate on the way back
in; there is no deactivate hook, so a folder left open survives the round trip
and greets the user still open over a grid they walked away from. Worse,
onActivate's focusSearch then lands the caret in the search box behind the
folder's scrim, and typing filters the grid the card is covering — a modal with
the keyboard pointed outside it.

Shut the folder as the tab comes back: returning to the tab is returning to
the grid.

* fix(gui): move focus into a folder when it opens

Opening a folder called .focus({ preventScroll: true }) on a jQuery
object. jQuery's .focus() shorthand reads a lone non-function argument
as event DATA and binds a handler with it, so it never moved focus:
the folder opened modal over the grid with focus still on the tile
behind its scrim, where Tab walked away through the inert grid instead
of cycling inside the dialog — and the object it bound as a handler
threw a TypeError on that tile's every subsequent focus.

Focus the DOM node instead, as every other focus call in this file
already does.

* fix(gui): stop renaming a folder from swallowing the click that commits it

The folder's name box commits on blur, and blur fires on the PRESS —
before the click that press belongs to. Committing re-rendered, and the
re-render replaced every tile in the open folder, so by the time the
click was dispatched the tile under the pointer was detached and the
delegated handler never saw it. Typing a name and then tapping an app
in the folder — the path a brand-new folder puts the user on — renamed
the folder and did nothing else; the app only opened on a second click.

Rebuild the folder's contents only when they actually differ from what
is on screen. A rename doesn't change them, so nothing is detached, and
a background refresh no longer throws away hover/focus either. Tiles
that survive get their drag resting-rects cleared, since the card can
have moved under them since the rects were taken.

* fix(gui): keep Enter in a folder's name box from leaving the folder

Committing the name with Enter blurred the box, which left focus on
<body> — outside a dialog that is marked aria-modal and that traps Tab
on its own subtree. The next Tab therefore walked off through the inert
grid the folder is covering, exactly what the trap exists to prevent.

Step out onto the folder's first app instead; the same blur still
commits the name. The keystroke is stopped at the box because the
grid's document-level key handler reads Enter on a focused tile as
"launch it", and would otherwise have taken the focus move as its cue
to open an app the user never asked for.

* fix(gui): stop an open folder clipping its own uninstall badges

The folder's grid scrolls, so it clips anything outside its padding box
— and reorder mode's uninstall badge deliberately overhangs the top-left
corner of every tile. The top row's badges therefore rendered as flat
tabs rather than circles, on the one surface where they are a touch
user's only way to uninstall an app they have filed away.

Give the scroller 9px of top padding for the overhang to sit in and take
it straight back off as margin, so the card and everything in it stays
exactly where it was.

* fix(gui): hold page edge-flips while a folder merge is being offered

A tile in the pager's last column sits inside the 60px edge-flip zone, so
resting a dragged icon on it — the folder-making gesture — armed the edge
dwell alongside the merge dwell, and the page flipped out from under the
very folder the user was watching form (the merge target scrolls away
mid-offer, and the drop then resolves against its stale resting rect).
Worst on phones, where 72px tiles overlap the zone across the whole last
column.

A live merge offer now holds the edge flip: entering the zone arms no
dwell while an offer stands, and an offer that arrives during a running
dwell is re-checked at the flip (a resting pointer fires no event that
could clear the timer). Carrying the icon off the tile withdraws the offer
and the hold with it, so deliberate flips — resting in the bare edge
gutter — behave as before.

* fix(gui): make Escape cancel a folder rename instead of saving it

Escape pressed mid-edit fell through to the folder's close handler, and
closing commits whatever the name box holds — so the one key every inline
rename uses for "never mind" stored the abandoned half-typed name. Escape
in the box now puts the stored name back and steps out to the folder's
tiles, exactly the cancel Finder/Explorer taught; with nothing left to
cancel (name untouched) it falls through and closes the folder as before,
so a second press still exits.

* fix(gui): refill the folder well when the merge countdown restarts

The merge dwell pins its stillness anchor at first contact with the tile,
and a hand decelerating INTO a target routinely covers more than the
7px allowance between that moment and the first tick — so the countdown
quietly restarts. The well's fill, tuned to the same 460ms, had already
completed by then and just sat there half-open: a drop it seemed to
promise a folder for actually reordered. Restart the fill with the
countdown, so what the well shows is always the countdown that is
actually running.

* fix(gui): keep keyboard focus inside an open folder across its edits

The folder card is a modal dialog, but three of its flows stranded focus
on <body>, where Tab walks the inert grid behind the scrim:

- Remove from Folder rebuilds the card's grid after the context menu has
  dropped focus, so nothing inside the dialog holds it. The rebuild now
  hands focus back to the same app's tile (or the first) whenever it finds
  focus on <body> — never stealing from an uninstall modal, which holds it
  legitimately.
- The same eject dissolving the folder re-renders the grid right after
  _closeGroup's focus hand-back, replacing the very tile it chose. The
  ejected app's own tile — where the user is looking — takes focus instead.
- A click on the card's empty space focused nothing at all. The card now
  carries tabindex=-1 so such clicks land on it (no visible ring; a focus
  ring around the whole card would misread plumbing as selection), and the
  Tab trap wraps from there instead of stepping off through the scrim.

* fix(gui): size the folder name box to the name it holds

The box sat at the browser's default ~20ch regardless of content: a short
name floated in a hover pill far wider than the word, and a 40-character
one clipped while the card had room to spare. field-sizing: content hugs
the text between a 90px floor and the card's width, iOS-style; engines
without the property keep the default box exactly as before.
2026-08-08 00:28:03 -07:00
Neal Shah aea828ff12 add worker create event and new query methods (#3524) 2026-08-07 17:51:37 -04:00
Daniel Salazar c24f0fe08b fix: mcp fs copy, move, rename (#3517)
* fix: mcp fs copy, move, rename

* feat: more mcp tools for kv
2026-08-07 17:14:40 -04:00
jelveh 085ac116c7 fix(gui): keep app landings through signup, and unstack the session picker
Signing up from a direct /app/<name> landing redirected to '/' on
success, silently dropping the app the URL asked for — the deep link's
launch (and its dashboard intro) never happened. Signup now mirrors
login's pathname-preserving redirect, but only for app-landing routes
(/app/<name>, /desktop/app/<name>): every other route keeps the
historical '/', notably /action/signup, where returning to the same
path would just show the signup form again. The query string stays
dropped, matching login's credential-leak hygiene. This covers all
three signup entry points reachable from a landing: the login cover's
"Sign up", the session picker's "Create Account", and the
must_login_or_signup fallback.

The session picker (UIWindowSessionList) also left itself on top of
the cover windows its two links open, hiding their username fields:
"Create Account" tried to close the picker via the LOGIN window's
c2a selector (which matches nothing in the picker), and "Log Into
Another Account" never closed it at all. Both now close the picker —
in the reload flows only: the no-reload (popup) flows keep it open,
where it doubles as the fallback UI when the login/signup window is
abandoned mid-flow.

Picking an account was already correct (location.reload() keeps the
landing URL); with these fixes all three picker paths, plain login,
and signup all return to the app landing, where the boot replays the
launch and its intro.
2026-08-07 11:51:44 -07:00
jelveh 5538a5d24b feat(gui): let the deep-link intro step aside for users who know it
The intro exists to teach the dashboard's spatial model; once learned it
would only tax every bookmarked landing. Two mechanisms remove that tax:

- Interruptible: any real user input (pointer/key/wheel, isTrusted only)
  during the intro skips the remaining choreography and launches at
  once — it wakes the in-flight beat sleep, so the skip is immediate.
  Input never cancels the launch itself and is never swallowed;
  whatever it was doing (typing a search, clicking a tile) still
  happens.

- Exposure decay: after 3 delivered — or deliberately skipped — intros
  the beats collapse and the sequence plays in one breath, exactly like
  a warm tile click. Counted per account in kv (kv.incr, atomic across
  devices; capped at the threshold so the key stops changing) rather
  than per device: the lesson lives in the user's head and the account
  follows them, while localStorage would also bleed between accounts on
  a shared browser. Only real exposures count: a delivered flourish or
  an active skip with the grid on screen — hidden tabs, timeouts, and
  no-tile landings teach nothing and don't count. The animated page
  flip is exempt from decay: it isn't a repeated lesson, it's live
  wayfinding to where this app lives, and its settle is needed anyway
  to put the tile in view for the morph. Every failure mode (slow or
  failed kv read) errs toward teaching once more, never toward never
  teaching.

Also bounds the intro's wait on the app-list load by the same deadline
as the tile wait — fetch has no timeout of its own, so a stalled
installedApps request used to hold the deep-link launch hostage
indefinitely.
2026-08-07 11:23:47 -07:00
jelveh 14c14fb5c5 feat(gui): animate the pager flip when a deep-linked app lives on a later page
The deep-link intro used to flip to the tile's page instantly behind the
grid's load-fade, so landings on off-page apps woke up on page N with
nothing but the pager dots hinting a move happened. Now the grid always
reveals on its first page, holds the grid beat, and then visibly travels
to the tile's page before the tile's flourish — the journey shows where
the app lives, which is also where minimize will put it back.

Smooth scrollTo has no reliable completion event across engines, so the
travel uses a settle allowance (DEEP_LINK_INTRO_FLIP_SETTLE_MS, same
pattern as the drag code's DRAG_FLIP_SETTLE_MS): the scroll's ~450ms
plus a rest so the landing reads before the tile pops. First-page apps
skip the flip entirely and are unaffected; the hidden-page bail-out is
re-checked after the flip settles.
2026-08-07 11:12:03 -07:00
jelveh 41fc8d890b feat(gui): play the tile click→morph→open intro on /app/<name> landings
A direct landing on /app/<name> now plays the same sequence a real
Apps-tab tile click does — grid appears, a beat, the tile's icon ghost
pops out of its slot, a beat, and the window morphs out of the tile —
so the landing shows the user what is being opened and where minimize
puts it back.

TabApps.beginDeepLinkLaunch waits (3s cap) for the tile to be genuinely
visible (list loaded, render done, pager flipped to the tile's page,
load-fade revealed, icon painted), paces the beats, and claims the app
in _launchingApps so a click mid-intro can't spawn a duplicate. The
launch's app-info fetch is prefetched in parallel so the intro never
delays the app's own round-trip. No tile, animations off, reduced
motion, or a background tab (hidden pages throttle timers and defer
rendering) all skip straight to the immediate plain-fade launch.

Also fixes the tab title sticking as the app's name after closing a
deep-linked app: the landing's replaceState('/') committed the
dashboard's history entry while the page still carried the server's
app-name title, and Chrome shows an entry's stored title when close/
Back traverses onto it — document.title is now reset before the
replaceState so the entry is stamped with the dashboard's own title.
2026-08-07 10:34:21 -07:00
Reynaldi Chernando 45bdc46df0 Remove deprecated models 7 aug (#3522) 2026-08-07 23:20:50 +07:00
jelveh 82ca390bf4 fix(gui): create-in-folder via sidebar right-click renders in target dir
Right-clicking a sidebar/breadcrumb folder in the dashboard Files tab and
choosing New > Folder (or any file type) created the item in the right-
clicked folder correctly, but the UI inserted the new row and started the
inline rename in whatever directory was currently open — so the item
appeared to be created in the wrong place until a refresh.

Now, when the creation target isn't the directory on screen, navigate to
the target and run the select + rename flow there; same-directory
creation keeps the incremental insert.
2026-08-07 08:49:13 -07:00
Neal Shah edfd67a83c fix PUT-1444 (#3515) 2026-08-06 17:11:04 -04:00
404oops ff16ec8900 Add Neuralwatt support (#3509) 2026-08-06 17:01:33 -04:00
Daniel Salazar c7edfc0c74 perf: improve metering perf + add extra compat for monthly charges (#3513)
closes PUT-1445 and PUT-1446
2026-08-06 10:26:47 -07:00
velzie 09f30d693c Peer: allow anontoken in place of authentication (#3501) 2026-08-06 02:03:53 -04:00
Reynaldi Chernando a9ec15d121 Update NPM readme (#3510) 2026-08-05 17:07:02 -07:00
Daniel Salazar eb53c842dd fix: oidc issues with cache (#3512)
closes #3497
closes #3502
2026-08-05 17:05:31 -07:00
Daniel Salazar 1be5ce45f7 feat: support dekstop app linking again (#3511) 2026-08-05 14:16:02 -07:00
Neal Shah 294055e055 PUT-1436, PUT-1435, PUT-1371 (#3507) 2026-08-05 17:11:50 -04:00
jelveh 036008d8a7 fix: keep uninstalled recommended apps from resurrecting in the Apps tab
Uninstall only revokes permissions, but the recommended launch list is a
global hardcoded set that knows nothing about per-user revokes — so an
uninstalled recommended app's tile came back on every reload. Persist
uninstalled app names in kv (dashboard_removed_apps) and filter only the
recommended merge against them; installedApps is never filtered, so a
genuinely (re)installed app always shows.
2026-08-05 11:01:14 -07:00
Daniel Salazar 6df292f495 fix: PUT-1429 (#3508) 2026-08-05 01:17:34 -07:00
Daniel Salazar 40c8d09f05 fix: PUT-1401 (#3504) 2026-08-04 16:37:33 -07:00
meridah7 4a211b9092 docs: document the provider option and refresh the vendor list in chat() (#3505) 2026-08-04 16:22:03 -07:00
meridah7 24fc0b0e5f fix(ai-chat): infron default model is dropped by the aggregator alias rule (#3506)
* fix(ai-chat): use a resolvable default model for the infron provider

* test(ai-chat): assert the infron default model is in the served catalog
2026-08-04 16:21:55 -07:00
Nariman Jelveh f58772ec33 feat: swap browser favicon to the focused app's icon in dashboard 2026-08-04 14:16:32 -07:00
Neal Shah eb830799c0 add limit bypass (#3500)
* add limit bypass

* update test
2026-08-03 19:43:59 -04:00
jelveh 8df72ef343 fix: dashboard app drawer icon popping in late
The drawer resolved its own icon URL (a differently-sized variant under a
different URL than the dashboard tiles use), so its <img> fetched cold and
the icon popped in mid-intro. Reuse the bitmap an Apps-tab tile or Home-tab
recent already decoded — instant from the image cache; when nothing is
rendered yet (deep links), fade the icon in on load instead of popping, and
fall back to the generic app icon on a failed fetch.
2026-08-03 11:50:43 -07:00
jelveh 63b2fc34d9 feat: highlight pasted items in dashboard files tab
Pasted (copied or cut) items now land selected, the same treatment
uploads get. copy_clipboard_items resolves with the created items'
paths instead of firing and forgetting, moveClipboardItems returns
each move response's authoritative final path (with Keep Both the
landed name differs from the source's), and both dashboard paste
entry points refresh with strong consistency and hand the new paths
to selectUploadedRows. Pastes into a folder that isn't rendered match
no rows and the highlight is a no-op.
2026-08-03 06:52:40 -07:00
Nariman Jelveh 33d7324a24 feat: 'Keep Both' option in name-conflict dialogs (#3496)
Pasting or moving onto an existing name only offered Replace or
Cancel. Add a macOS-style middle ground: Keep Both retries the
operation with dedupe_name, landing the item as "name (1).ext" and
leaving the existing item untouched.

- puter-js move.js now forwards dedupeName to the wire (copy already
  did; move dropped it).
- All four conflict dialogs offer the new button: copy_clipboard_items,
  copy_items and move_items in helpers.js, and the dashboard's
  moveClipboardItems. Multi-item selections show
  Replace / Replace all / Keep Both / Skip.
- New keep_both translation key (other locales fall back to English).
2026-08-03 06:39:18 -07:00
Nariman Jelveh 62be61642d fix: phantom name conflict when pasting onto a just-renamed path (#3495)
Renaming (or moving) an entry left the OLD path's cache key serving
the pre-update entry for the full 60s TTL: updateEntry invalidated
only keys derived from the updated row, whose path is already the new
one. Pasting an item under the freed name then hit the stale cache in
the collision check and reported a conflict for a file that no longer
exists — and accepting the Replace it offered deleted the renamed file,
since the stale entry carries its uuid.

Read the pre-update entry when the patch changes the path and
invalidate its keys alongside the new ones. The move flow was shielded
by the outer.gui.item.moved cache-invalidation handler at the
controller layer; rename had no such band-aid, and fixing the store
covers every caller regardless of which events fire.
2026-08-02 23:53:59 -07:00
Nariman Jelveh 8cebbcf3be fix: thumbnails breaking after copy — duplicate the S3 object per copy (#3494)
A copied fsentry kept its source's thumbnail pointer verbatim, so both
rows shared one S3 thumbnail object. fs.remove.node deletes the
pointed-to object, so the first removal among the sharers — e.g. the
remove performed by a replace-on-copy — broke every other sharer's
thumbnail. FSService already emits fs.copy.node for exactly this
reason (its doc comment describes the duplication), but the thumbnails
extension never subscribed to it.

Add the missing handler: S3-copy the thumbnail to a freshly minted key
and repoint the copied row, under the same only-keys-we-minted trust
rule as the read/remove paths. If the shared object is already gone
(pre-fix damage), null the pointer instead of leaving the row
advertising a thumbnail it doesn't have.
2026-08-02 23:22:24 -07:00
Nariman Jelveh 5c2a423658 fix: progress window covering paste conflict dialog; ghost row after Replace (#3493)
* fix: progress window covering paste conflict dialog; ghost row after Replace

Pasting a copied file onto a name collision buried the Replace/Cancel
dialog under a stuck 'Preparing...' progress window, and answering
Replace left a stale duplicate row in every client.

- helpers.js: copy_clipboard_items armed its delayed progress window
  with a 0ms timer (its siblings use 2s), so the window opened
  instantly over the dialog. Use 2s, and in all three of
  copy_clipboard_items / copy_items / move_items pause the timer while
  a conflict dialog (or the own-location / trash-deny alerts) is
  waiting for input, re-arming it after. A window that opens
  mid-operation now shows the current file instead of a stuck
  'Preparing...', and the trash-deny bail no longer leaks a timer that
  opened an orphan window after the operation ended.
- LegacyFSController: /copy and /move dropped the legacy 'overwritten'
  response field and never emitted item.removed for the entry an
  overwrite deleted, so clients kept a ghost row until re-listing.
  Resolve the entry before the operation, return it, and emit
  item.removed on success.
- helpers.js: copy_items read resp[0].overwritten but removed
  resp.overwritten (always undefined), and the data-uid cleanup
  selectors were unquoted — invalid CSS when a UUID starts with a
  digit. Fixed all three sites.

* test: pin the v1 overwrite/collision wire contract for move and copy

The collision tests asserted only statusCode 409, which is how the
item_with_same_name_exists code regressed to 'conflict' unnoticed and
broke every replace/skip prompt in the GUI. Assert the legacy code and
entry_name explicitly, and add controller tests for the overwrite path:
the replaced entry must ride along as 'overwritten' in the /copy and
/move responses and be announced via outer.gui.item.removed so clients
drop its row.
2026-08-02 22:17:10 -07:00
Nariman Jelveh 1a9f025db6 fix: surface name collisions when pasting instead of failing silently (#3492)
Cut+paste onto a folder containing an item with the same name failed
with no feedback: the dashboard's moveClipboardItems swallowed the
error into console.error and cleared the clipboard, and the rewritten
backend broke the v1 wire contract the GUI's conflict prompts key on.

- FSService: move() and copy() collisions again return
  item_with_same_name_exists + entry_name (the contract the write path
  already preserves) instead of a generic 'conflict' code. This also
  restores the desktop's existing Replace/Skip dialogs, which were
  silently broken against the new backend.
- Dashboard: moveClipboardItems now mirrors the desktop's move_items
  conflict flow (Replace / Replace all / Skip / Cancel, retry with
  overwrite) and surfaces other move errors in an alert.
- keyboard.js: the desktop's global Ctrl+V handler threw an uncaught
  TypeError on every paste in dashboard mode (its file container has
  no data-path); guard it — which also prevents a double-paste if
  dashboard containers ever gain one.
2026-08-02 21:33:01 -07:00
jelveh a4667073f5 Update RecommendedAppsService.ts 2026-08-02 20:55:33 -07:00
jelveh 23d251e482 fix: dashboard files list blanking during same-directory refresh
Re-rendering the directory already on screen (after an upload, sort
change, undo, etc.) used to clear the list and show a spinner before
the readdir round-trip, blanking the pane for the whole fetch. Keep
the current rows visible until the fresh listing arrives, then swap
the DOM in one pass and restore the scroll position. Navigation to a
different directory still clears immediately.
2026-08-02 20:30:20 -07:00
jelveh 0c9dfb03e2 Show action bar only in mobile select mode 2026-08-02 19:49:14 -07:00
Nariman Jelveh 6dc928e0c3 fix: file picker dialogs going behind parent window when dragged by titlebar 2026-08-02 17:38:25 -07:00
Daniel Salazar 84582ee33d fix: alarm channels (#3491) 2026-08-01 15:55:06 -07:00
Daniel Salazar 116d6e6663 tests: big test push for better coverage (#3490) 2026-08-01 14:29:59 -07:00
Daniel Salazar 7d0d44aef9 feat: slack alarms (#3489) 2026-08-01 13:12:41 -07:00
Daniel Salazar 3ac6c8532e fix: open ai cost (#3488) 2026-08-01 12:34:36 -07:00
Nariman Jelveh f6a50c4fb4 Update recommended apps list order
Reorders and updates the recommended apps list: removes 'butler', 'code', and 'traffic-tap-puzzle'; adds 'contacts', 'diagram', and 'basketball-tap' (relocated from end); adjusts overall ordering of several apps.
2026-08-01 12:26:44 -07:00
Daniel Salazar c8113d7514 fix: auth message popups (#3487)
* fix: auth message popups

* remove v1 auth
2026-08-01 10:45:16 -07:00
jelveh 6159bc9ae1 Polish dashboard settings button styling
Update `.dashboard-settings-card .button` to use dashboard theme tokens for text, background, and borders, and add clearer hover/focus/active states with subtle elevation and transitions. Also override disabled styles in this context so dark mode no longer shows hard-coded light greys from the base `.button:disabled` rule.
2026-08-01 00:27:27 -07:00
Daniel Salazar 3a11d0d1f1 feat: sandboxed app workers (#3486) 2026-08-01 00:02:06 -07:00
jelveh 535cf5753e Merge branch 'main' of https://github.com/HeyPuter/puter 2026-07-31 14:14:11 -07:00
jelveh cee4a6ccce Improve app reorder mode on touch devices 2026-07-31 14:14:04 -07:00
Daniel Salazar 1f1f95c2f8 fix: auth me for local dev (#3484) 2026-07-31 14:04:59 -07:00
jelveh f600e857b0 GUI: touch reorder mode for the dashboard Apps tab
Long-press-to-drag can't be made reliable on touch: touch-action is
consulted at gesture start, so the pager's pan-x claims the finger
before a drag can begin (worst on iOS). Replace it with an explicit
edit mode - a cog button (touch-primary devices only) enters it, tiles
jiggle and drag on first movement, iOS-style x badges uninstall, and
Done exits. Drops still persist immediately, same as desktop.

Also raise the drag ghost above the window z-index bands; it was
rendering invisibly behind the fullpage dashboard window.
2026-07-31 13:46:17 -07:00
Neal ShahandDaniel Salazar 08d1708378 change cors auth path (#3464)
* change cors auth path

* undo oidc ref changes

* scary OIDC state changes

* fix: bad cors signin

* puterjs changes

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-07-31 01:55:01 -04:00
Nariman Jelveh f1bc065730 GUI: fix dev-server port-retry crash under Express 5 (#3482)
Express 5's app.listen wraps the listen callback in once() and also
invokes it on 'error', with the error as the first argument — at which
point server.address() is null, so the startup log threw a TypeError
and killed the process before the EADDRINUSE handler could try the
next port. Bail out of the callback when it receives an error and let
the 'error' listener own the retry.

Verified: with 4000 occupied the server now logs the retry and comes
up on 4001; with the port free it binds 4000 as before.
2026-07-30 18:11:12 -07:00
Nariman Jelveh b55782f066 GUI: add npm start --server=<domain> to run the GUI against a remote backend (#3481)
- npm start --server=puter.com (or -- --server=...) skips the local backend
  and serves the bundled GUI locally, pointed at the remote server's API.
  Bare domains resolve to https://api.<domain>; full origins are used
  verbatim. gui_origin points at the remote origin so /whoarewe, login,
  anti-csrf, socket.io, and builtin apps hit the real backend (CORS-open).
- --extensions=<dir>[;<dir>...] bundles out-of-tree GUI extension
  directories (sugar for PUTER_GUI_EXTENSION_PATHS). Their imports resolve
  as if the files lived in src/gui/src/extensions, with the extension's own
  files taking precedence, and bare imports fall back to the repo-root
  node_modules.
- Fix the bit-rotted dev-server: Express 5 wildcard routes, pass gui()
  params (previously called with none), inject the service_script shim,
  load bundle.min.js + bundle.min.css in prod mode, serve /sdk, and
  properly await the webpack build (it previously resolved immediately).
2026-07-30 16:29:54 -07:00
jelvehandClaude Fable 5 2c9ae3489e Suggested apps: rank registered apps above the editor fallback
For extensions with no intentional built-in mapping (doc, docx, and
every other unmapped type), suggestionsForExtension fell back to
['editor'], and #resolveForExtension always placed built-ins ahead of
apps from app_filetype_association. Since suggested[0] drives the GUI's
double-click open path and /open_item, a .docx defaulted to opening as
plain text in editor even when a word processor explicitly registered
the extension.

Tag the unknown-extension result as a fallback and order third-party
filetype-association apps ahead of it. Intentional mappings (code, txt,
md, images, pdf, media) keep built-ins in the head slot as before, and
the editor guess still appears as a last-resort option.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:51:01 -07:00
Daniel Salazar b28b41c90b otel: better telemetry numbers (#3480) 2026-07-30 13:23:16 -07:00
Nariman Jelveh f34c4dc335 Apps: normalize filetype associations to bare lowercase extensions (#3479)
* Apps: normalize filetype associations to bare lowercase extensions

Suggested-apps lookups match app_filetype_association rows against the
bare lowercase extension ('docx'), but writes stored whatever the
developer typed. Rows like '.docx' never matched, so those apps
silently dropped out of Open With suggestions.

AppStore now canonicalizes on write (trim, lowercase, strip leading
dots, dedupe, drop empties) and tolerates the dotted legacy form on
read: getAppsByFiletype normalizes the requested extension, matches
both 'docx' and '.docx', and dedupes apps associated under both forms.
Cache invalidation keys are normalized the same way. Existing dotted
rows work without a data migration.

* Update apps tests for extension canonicalization

Adjust apps API tests to match current normalization behavior for `filetypeAssociations`: extension values are stored as lowercase bare extensions (e.g. `.txt` -> `txt`), while MIME types remain unchanged. Added inline comments in both test suites to document this expected remap.
2026-07-30 13:13:14 -07:00
Daniel Salazar 5a157197b6 fix: PUT-1398 (#3478) 2026-07-30 01:42:40 -07:00
Daniel Salazar 8a711e0254 driver controller change (#3477)
* fix: launch app

* driver controller change
2026-07-30 00:41:29 -07:00
jelveh a22321daa2 Dashboard: closing a launched app goes home, not into its launcher
An app launched by another app minimizes its launcher (iOS-style
takeover). Closing the child then popped onto the launcher's history
entry, and the popstate handler restored it — so quitting an app threw
the user into a different full-screen app they had not asked for, zoom
animation and all. Closing an app should go home.

Mark the launcher when it is minimized FOR a child
(data-minimized_for_child). If it still carries that mark when the child
closes, the close's single history hop lands on the dashboard instead:
the entry is rewritten to the dashboard's route and the launcher is left
minimized, still running behind its tile's running dot. No extra history
traversal — the joint session history an app's iframe shares is exactly
what pop_dashboard_app_url's watchdog exists to survive, so the hop
count is unchanged.

Back is untouched and still returns to the launcher — that is the
navigation gesture, whereas close dismisses. Any restore (Back, tile
click, Forward) clears the mark, so quitting a child after the user has
brought the launcher back leaves the launcher alone.
2026-07-29 22:04:10 -07:00
jelveh fbf1bd18b1 Dashboard: an app launched by another app takes over the tab
In dashboard mode apps are full-tab experiences, but an app launched by
another app (puter.ui.launchApp) opened as a floating titlebar window
over its full-tab parent: the parent stayed on screen around its edges,
couldn't be raised (focusWindow never raises stay_on_top windows), and a
child with no Apps-tab tile had no switcher to come back to once
minimized.

Give child launches the same treatment as tile launches — maximized, so
they get the headless chrome and control drawer — and minimize the
parent behind them, iOS-style. State only: the parent's /app/<name>
history entry already sits beneath the child's, so Back from the child
(and the child's close, which consumes its own entry) lands on the
parent's entry and the existing popstate handler restores it. The parent
keeps running while hidden, so parent/child IPC is unaffected.

Explorer keeps its windowed form, background apps don't minimize their
parent, and an explicit `maximized` option still wins. Desktop mode is
untouched: both changes are gated on is_dashboard_mode, so an app
launching an app there still gets a floating child over a visible
parent.
2026-07-29 21:36:47 -07:00
jelveh dc371fc4eb Windows: keep dialogs and their apps in the stay-on-top z band
focusWindow re-raised a focused window's parent (and children) with the
bare z counter. For a file dialog owned by a fullpage/dashboard app that
DEMOTED the app out of the 99999999+ stay-on-top band it was created in,
burying app and dialog under every other open app window — opening a
file picker from an app stacked over another (e.g. an app launched from
Dev Center) made both vanish beneath the window below. The dialog itself
had the same flaw: raised into the plain counter band, under every app.

Raise each window within its own stacking band instead: stay-on-top
windows (and windows hanging off one through parent_uuid, walked up the
chain) get 99999999 + counter; everything else keeps the bare counter —
so desktop stacking arithmetic is unchanged. Same demotion family as the
showWindow restore fix in #3427.
2026-07-29 21:11:21 -07:00
jelveh 97e4e78df4 Dashboard files: drop the root crumb from the breadcrumb
Every path rendered as "> Puter > user > ...", but the root crumb is
noise on anything beneath it. Render it only at the root itself, where
it's all there is to show (the Up button can still reach /, and an
empty breadcrumb bar there would strand the user). Each crumb keeps
its leading caret, including the first.
2026-07-29 20:12:22 -07:00
jelveh 007649296b Keyboard: stop swallowing Enter when nothing claims it
The global Enter handler preventDefault'ed unconditionally, then
returned without acting unless a launch-menu item, context-menu item,
or selected item existed. That suppressed the browser's native Enter
activation on whatever was focused — a focused link or button (e.g. a
dashboard sidebar item, a dialog button) did nothing on Enter.

Move preventDefault/stopPropagation into the branches that actually
handle the key; otherwise fall through so native activation runs. The
handled paths are unchanged: Enter still opens the selected item,
launch-menu entry, and context-menu entry.
2026-07-29 19:40:16 -07:00
jelveh 9392aed402 Dashboard: restyle keyboard focus ring on sidebar controls
Sidebar items (and the user/collapse/close buttons) had no
:focus-visible style, so keyboard focus painted the UA's default blue
ring — hard-edged and bleeding outside the item. Use the dashboard's
own selection ring instead, tucked inside the control so it hugs the
rounded corners. :focus-visible only, so mouse clicks never paint it.
2026-07-29 19:40:06 -07:00
jelveh 32e417fe79 Dashboard files: clicking an open file returns to its window
In dashboard mode there is no taskbar, so a minimized app window's only
switcher was its Apps-tab tile — invisible from the Files tab. Opening a
file, minimizing, and clicking the file again launched a second instance
of the app, stranding the first (and any unsaved edits) somewhere
unreachable.

Make the file row itself the switcher:

- launch_app stamps the opened file's uid on the window (data-file_uid;
  the signature's uid wins so shortcuts resolve to their target)
- open_item (dashboard mode) restores/focuses an existing window that
  has the file open instead of launching a duplicate, mirroring the
  Apps-tab tile's single-instance behavior — keyed by file, not app, so
  opening a different file still gets its own instance
- re-clicks while a launch's fetches are still in flight are swallowed
  (same idea as TabApps._launchingApps, keyed by file uid, TTL'd so a
  failed launch can't swallow clicks forever)
- dashboard file opens now default to maximized, so they get the same
  headless full-tab chrome + control drawer as tile launches instead of
  a floating titlebar window
- rows show a dot while their file is open in a (possibly minimized)
  window — under the name in grid view, inline after it in list view —
  driven by the existing dashboard-app-windows-changed event

Desktop mode is untouched: the reuse branch and maximized default are
gated on is_dashboard_mode, and opening the same file twice there still
creates two windows as before.
2026-07-29 19:03:33 -07:00
Daniel Salazar 0e1f617401 fix: errors for bad keys (#3475) 2026-07-29 15:58:53 -07:00
Felix-Ayush bd6efaaa4e fix(puter-js): ignore peer offers for unknown connections (#3473)
createAnswer ran outside the connection null-check, so stale or unknown
offer ids threw on the signalling socket. Guard the whole offer path and
return the #message promise from onmessage so callers can observe errors.
2026-07-29 15:58:39 -07:00
Nariman Jelveh 2b6dc528ce Merge branch 'main' of https://github.com/HeyPuter/puter 2026-07-29 15:48:21 -07:00
Nariman Jelveh 9368ad57b6 Preserve UI state across tab visibility refresh 2026-07-29 15:47:59 -07:00
Felix-Ayush e97d338f3a fix(ai-chat): preserve max_tokens 0 for Alibaba, DeepSeek, and Claude (#3472)
These providers used `max_tokens || default`, so an explicit zero was
replaced by the fallback. Use nullish coalescing so 0 is forwarded.
2026-07-29 18:38:31 -04:00
Nariman Jelveh a87a517b82 Anchor file row menu to button edge
File row overflow menus in the dashboard now open anchored to the ⋯ button (below it with right-edge alignment) instead of pointer position, improving placement consistency. UIContextMenu now supports `position.right` for right-edge pinning, and the ⋯ trigger keeps an active visual state while its menu is open so hover styling doesn’t drop when the cursor moves onto the menu.
2026-07-29 15:25:51 -07:00
Nariman Jelveh dbb52171c8 Refine dashboard file row hover styling 2026-07-29 15:05:21 -07:00
Daniel Salazar 6c020318f9 perf: traces and perf improvements (#3471) 2026-07-29 14:35:15 -07:00
Nariman Jelveh e16994db3b Fix I-beam cursor on dashboard file rows in Safari
Safari ignores user-select: none for cursor styling, showing a text I-beam over file rows. Setting cursor: default explicitly fixes this and is inherited by child elements.
2026-07-29 14:18:50 -07:00
Daniel Salazar 8491a0b55d fix: limit api pointing to apps only (#3470) 2026-07-29 14:03:27 -07:00
Felix-Ayush 710e4da4c0 fix(puter-js): size img2txt data URIs by decoded bytes (#3457)
Match speech2txt/speech2speech and reject on decoded payload size, not
data-URI string length. Base64 expands ~4/3, so string-length checks
falsely rejected valid images under the 10MB limit.
2026-07-29 12:21:21 -07:00
Felix-Ayush fd1f4e2ac2 fix(puter-js): forward temperature 0 and max_tokens 0 in ai.chat (#3455)
Truthy checks dropped legitimate zero values, so deterministic sampling
never reached the driver. Match the stream option and use !== undefined.
2026-07-29 12:21:15 -07:00
Kobi Hikri 70bf03a6e7 ci: attach provenance and SBOM attestations to the published image (#3463) 2026-07-29 12:21:02 -07:00
Felix-Ayush 6f90d7a199 fix(ai-chat): forward temperature 0 and max_tokens 0 to providers (#3456)
Completions-family providers used truthy spreads, so temperature: 0 and
max_tokens: 0 were stripped before the SDK call. Align with Responses
providers that already use !== undefined.
2026-07-29 11:49:36 -07:00
Daniel Salazar f0b1947c54 feat: make uninstall also revoke + dashboard css changes (#3469)
* feat: make uninstall also revoke

* fix: wording for free trial
2026-07-29 10:40:43 -07:00
Daniel Salazar 92193ff11f chore: kill collector (#3466) 2026-07-28 19:02:49 -07:00
Daniel Salazar f9396b7283 fix: thumbnail res (#3465) 2026-07-28 17:31:01 -07:00
Sauhbagya PrasadandDaniel Salazar 7cf3e03433 Replaced Nginx with Caddy (#3378)
* Replace nginx with Caddy

* updated caddy location

* seprate logic for local and with domain caddy setup

* updated install

* updated install scripts

new ps1 script with caddy, and removed instances of nginx

* fix Caddy Host routing, restore TLS/SELinux/healthcheck, update docs

---------

Co-authored-by: Daniel Salazar <[email protected]>
2026-07-28 14:52:13 -07:00
Neal Shah 0a61b4e78b add fixes 1 (#3458)
* add fixes 1

* change socketio test

* clarify that success/error callbacks are legacy

* fix wisp issues
2026-07-28 17:34:12 -04:00
Reynaldi Chernando 1db4324c02 remove deprecated ai models (#3444)
* remove deprecated ai models

* test

* fix tests
2026-07-28 12:41:04 -07:00
Daniel Salazar 69529ee0db perf: try to improve app opens speed (#3462)
* perf: try to improve app opens speed

* make /rao non blocking to allow faster conn swap
2026-07-28 11:12:44 -07:00
1073 changed files with 129909 additions and 22255 deletions

No files matched your search

+2 -2
View File
@@ -2,9 +2,9 @@
# docker-compose.full.yml up -d`. None of the defaults below are safe for
# anything beyond a local laptop test.
# ── Public-facing ports (nginx) ---------------------------------------
# ── Public-facing ports (Caddy) ---------------------------------------
HTTP_PORT=80
# HTTPS_PORT=443 # uncomment after you enable TLS in nginx/nginx.conf
# HTTPS_PORT=443 # uncomment after you enable TLS in caddy/Caddyfile
# ── MariaDB ------------------------------------------------------------
MARIADB_ROOT_PASSWORD=replace-with-strong-password
+32
View File
@@ -13,6 +13,9 @@ on:
- 'tools/**'
- 'package.json'
- 'package-lock.json'
# The type-check job below reads these.
- 'tsconfig.json'
- 'tsconfig.build.json'
- '.github/workflows/backend-tests.yaml'
permissions:
@@ -20,6 +23,35 @@ permissions:
pull-requests: write
jobs:
# `tsconfig.build.json` builds with `noCheck: true`, so nothing else in CI
# runs the type checker and a missing export compiles to `undefined`,
# surfacing only when the call is finally reached at runtime. This diffs
# against tools/typecheck-baseline.json and fails only on *new* errors.
#
# The consuming repo runs an equivalent gate, but only once someone bumps the
# submodule pointer — too late to keep the error off this repo's default
# branch. Hence a gate here, on this repo's own pull requests.
#
# Its own job rather than a step in `test`: that one runs a base/PR matrix for
# coverage comparison, and the check only needs the PR ref, once.
typecheck:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '24'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Type check (new errors only)
run: npm run typecheck
test:
runs-on: ubuntu-latest
strategy:
+2
View File
@@ -87,6 +87,8 @@ jobs:
platforms: linux/amd64,linux/arm64
context: .
push: true
provenance: mode=max
sbom: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
+27
View File
@@ -23,6 +23,33 @@ permissions:
pull-requests: write
jobs:
# The JSDoc in src/puter-js/src is the source of truth for the SDK's public
# types. The declarations shipped to npm are generated from it at build time
# and never committed, so what needs guarding is the JSDoc itself: this
# generates the declarations and type-checks the published surface without
# skipLibCheck, which is how broken re-exports used to go unnoticed.
#
# Its own job rather than a step in `test`: that one builds bundles and
# installs a browser, and this needs neither.
types:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '24'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Check the puter.js JSDoc produces declarations that type-check
run: npm run check:puterjs:types
test:
runs-on: ubuntu-latest
+10 -9
View File
@@ -10,6 +10,7 @@ Use these as the source of truth before exploring further:
- [doc/architecture.md](doc/architecture.md) — backend layered stack (controllers → drivers → services → stores → clients), `PuterServer` wiring, `Context` (ALS), and extensions.
- [doc/contributing-apis.md](doc/contributing-apis.md) — adding and maintaining public APIs end to end (backend surface → puter.js → types → docs → tests). Follow it for any API work.
- [doc/pagination.md](doc/pagination.md) — the one pagination convention for list APIs (limit/cursor/offset/includeTotal, envelope shape, cursor semantics).
- [doc/alarms.md](doc/alarms.md) — raising alarms and picking a severity (what pages, what only gets recorded), plus the config that routes them.
- [doc/self-hosting.md](doc/self-hosting.md) — running Puter outside hosted infra.
- [CONTRIBUTING.md](CONTRIBUTING.md) — testing, security, AI-assisted code, PR conventions, Boy Scout Rule.
- [SECURITY.md](SECURITY.md) — how to report vulnerabilities (do not file them publicly).
@@ -51,6 +52,7 @@ When in doubt, return less. Auth-, permission-, or data-export-related changes d
- **Test new behavior.** Every new function, endpoint, driver method, or logic branch gets a test; every bug fix gets a regression test that fails before the fix. If something is genuinely hard to test, skip it but say so in the PR.
- **Boy Scout Rule, proportional to the change.** Fix the obvious typo or dead import in files you're already touching; don't ride a refactor along with a bug fix.
- **Understand what you commit.** AI assistance is fine; shipping code you couldn't defend in review is not.
- **A limit change is not done until the docs change with it.** Every rate limit, concurrency cap, quota, and allowance in the code is published in [src/docs/src/rate-limits-and-quotas.md](src/docs/src/rate-limits-and-quotas.md) — an undisclosed limit is one developers discover as a service failure. If a PR moves any of these numbers, the same PR updates that page. The numbers live in `src/backend/controllers/fs/limits.ts` (filesystem), `src/backend/drivers/util/aiLimits.ts` (all AI drivers), per-driver `rateLimit`/`concurrent` configs, and `src/backend/data/subPolicies/` (free-tier allowances).
---
@@ -97,24 +99,23 @@ Follow the same layered structure inside an extension — unless it only needs a
[src/puter-js/](src/puter-js/) is the public SDK. It ships live from `https://js.puter.com/v2/` with no version pinning — every existing app picks up changes immediately. Treat every observable behavior (signatures, response fields, error codes) as something a production app depends on.
Layout: SDK modules in [src/puter-js/src/modules/](src/puter-js/src/modules/) (one file or directory per area — `FileSystem/`, `KV.js`, `ai/`, …), shared plumbing in [src/puter-js/src/lib/](src/puter-js/src/lib/), hand-maintained type declarations in [src/puter-js/types/](src/puter-js/types/), API tests in [src/puter-js/tests/api/](src/puter-js/tests/api/), UI e2e tests in [src/puter-js/tests/e2e/](src/puter-js/tests/e2e/), developer docs in [src/docs/](src/docs/).
Layout: SDK modules in [src/puter-js/src/modules/](src/puter-js/src/modules/) (one file or directory per area — `FileSystem/`, `kv/`, `ai/`, …), shared plumbing in [src/puter-js/src/lib/](src/puter-js/src/lib/), generated (gitignored) type declarations in `src/puter-js/types/`, API tests in [src/puter-js/tests/api/](src/puter-js/tests/api/), UI e2e tests in [src/puter-js/tests/e2e/](src/puter-js/tests/e2e/), developer docs in [src/docs/](src/docs/).
Language & typing: puter.js source is plain JavaScript — never TypeScript files — typed via JSDoc. Reference the hand-maintained declarations in [src/puter-js/types/](src/puter-js/types/) with `import(...)` types rather than re-declaring shapes:
Language & typing: puter.js source is plain JavaScript — never TypeScript files — typed via JSDoc. **The JSDoc is the source of truth for the SDK's types.** `src/puter-js/types/` is `tsc --emitDeclarationOnly` output: the SDK build (`npm run build` in `src/puter-js`) generates it, the npm tarball ships it so TypeScript consumers get declarations, and git ignores it — it is never committed and never edited by hand. `npm run check:puterjs:types` generates it in CI and type-checks the result without `skipLibCheck`. The one hand-written declaration file is [src/puter-js/index.d.ts](src/puter-js/index.d.ts), which decides what is public and re-exports the generated names.
Declare a shape where it belongs, and reference it with an `import(...)` type from elsewhere. A shape more than one file needs lives in the module's `types.js`; a shape shared across modules lives in [src/puter-js/src/lib/types.js](src/puter-js/src/lib/types.js); a shape with one consumer can stay next to it:
```js
/** @typedef {import('../../types/modules/ai').ChatOptions} ChatOptions */
/** @type {ChatOptions} */
const options = { model: 'gpt-5-nano' };
/** @typedef {import('./types.js').KVOptConfig} KVOptConfig */
```
When a shape only exists locally, declare it as an inline object literal — not the `@typedef {Object}` + `@property` list form — and use `unknown` over `*`:
Use `@typedef {Object}` + `@property` for any shape whose fields need documenting — it is the only JSDoc form that carries a doc comment per field into the generated declaration. Keep the inline object-literal form for small internal shapes with nothing to say about each field, and prefer `unknown` over `*`:
```js
/** @typedef {{ key: string, value: unknown }} KVEntry */
```
Public (exposed) methods must carry JSDoc types — parameters and return value, matching the `.d.ts` declarations exactly. Unexposed/private helpers are typed at the contributor's discretion: annotate where it helps the next reader, and either way keep them clean.
Public (exposed) methods must carry JSDoc types — parameters and return value — with one `@overload` block per accepted call form, since those overloads *are* the published signature. Unexposed/private helpers are typed at the contributor's discretion: annotate where it helps the next reader, and either way keep them clean. Members tagged `@internal` are stripped from the generated declarations, so use that tag rather than `@private` to keep something off the public surface.
Typing in JS files is encouraged: annotate with JSDoc `@type`/`@param`/`@returns` using the TypeScript type system, and define shared shapes with `@typedef`. API types must not be `unknown` or untyped `...args` — spell out the real parameter and return shapes; the only exception is values passed through transparently to an upstream layer that owns their type. For example:
@@ -132,7 +133,7 @@ Every SDK change carries all five of the following — a puter.js PR missing one
1. **Backward compatibility.** Mandatory unless a maintainer explicitly signs off on a break. Existing call signatures keep working (including both positional and options-object forms where a method supports them); new parameters are optional with defaults that preserve old behavior; never rename or repurpose existing params, response fields, or error codes. New parameter names are `camelCase` (existing `snake_case` stays for compatibility). Say in the PR how existing callers are unaffected.
2. **Tests.** Add or extend a suite in [tests/api/suites/](src/puter-js/tests/api/suites/) (`<area>.suite.ts`; register new suites in `suites/index.ts` — no globbing). One suite runs unchanged on node, browser, and workerd via `npm run test:puterjs`; never write a per-platform test. The runners execute the **built** bundle — run `npm run build:workerLib` after SDK changes or the suite silently tests stale code. For `puter.ui.*` methods rendered by the desktop, use the Playwright e2e harness instead — see [src/puter-js/TESTING.md](src/puter-js/TESTING.md).
3. **Docs.** New or changed APIs update [src/docs/src/](src/docs/src/): the method page (`<Area>/<method>.md`, with frontmatter and a runnable example) and the area overview when the surface changes. Docs are the contract users code against — signatures, defaults, and return shapes must match the implementation exactly.
4. **Types.** Update [src/puter-js/types/modules/](src/puter-js/types/modules/)`<module>.d.ts` and re-export new types through `index.d.ts` / `types/puter.d.ts`. Declarations must match runtime behavior exactly — a wrong type is worse than a missing one.
4. **Types.** Type the change in JSDoc on the implementation, then run `npm run check:puterjs:types` to confirm it still produces declarations that type-check. Name any new type in [src/puter-js/index.d.ts](src/puter-js/index.d.ts) if consumers should be able to import it. Declarations must match runtime behavior exactly — a wrong type is worse than a missing one.
5. **Error handling.** Reject/throw `{ message, code }` objects with stable `snake_case` codes, matching the existing modules (see `KV.js`). Validate cheap preconditions client-side before making the network call; pass backend errors through unchanged rather than swallowing or re-wrapping them. Error codes are API surface — changing one is a breaking change.
[doc/contributing-apis.md](doc/contributing-apis.md) walks the full lifecycle of adding an API across backend + SDK.
+39 -35
View File
@@ -6,33 +6,33 @@ We at **Puter** are committed to maintaining a secure experience for our users a
The following are in scope for this program:
* **The Puter open-source project** (available at [github.com/HeyPuter/puter](https://github.com/HeyPuter/puter))
* **`puter.com`**
* **`api.puter.com`**
- **The Puter open-source project** (available at [github.com/HeyPuter/puter](https://github.com/HeyPuter/puter))
- **`puter.com`**
- **`api.puter.com`**
Out-of-scope:
* Third-party services, applications, or libraries not maintained by Puter.
* Social engineering attacks (e.g., phishing against staff).
* Denial of Service (DoS), spam, or volumetric attacks.
* Physical security issues.
- Third-party services, applications, or libraries not maintained by Puter.
- Social engineering attacks (e.g., phishing against staff).
- Denial of Service (DoS), spam, or volumetric attacks.
- Physical security issues.
## Known Non-Issues (Please Check Before Submitting)
The following have already been reviewed and determined **not to be vulnerabilities**. Reports that only re-describe one of these are **not eligible for a reward** and will be closed as non-issues — even if they include new code references. Please review this list before submitting:
* **XSS / CORS / token issues scoped to `api.puter.com`.** The primary user session cookie lives on `puter.com`, not on the API origin, so reflected/stored XSS, CORS, or token handling on `api.puter.com` is generally out of scope. Two exceptions we *do* evaluate on their merits — please report these: (a) attacker-controlled content served **inline** (e.g. an HTML `Content-Type`) from API file/response endpoints, and (b) anything that abuses the app-scoped `puter_token_v2` companion cookie set on the API host.
* **SSRF via `secureFetch`.** Production routes outbound requests through an isolated proxy that has no access to internal/SSRF-sensitive resources.
* **Attacks that depend on guessing an `appInstanceID` or app UID.** These are random 128-bit secret values and are not considered guessable.
* **Apps invoking drivers, creating workers, or using KV.** Applications are intended to do this; worker permissions are scoped to the owning app. This is by design.
* **App metadata or app user-count "leaks".** This information is currently public by design.
* **General "token in a URL" / token-lifetime designs** — signed directory URLs exposing children, a write signature implying read, or app tokens outliving a web session. These are current intended behaviors.
* **Missing PKCE, unverified `id_token` signatures, or other OIDC hardening.** Provider tokens are obtained through a server-to-server authorization-code exchange with the provider's token endpoint over TLS, so the resulting `id_token` / userinfo claims are trusted from that channel rather than from local JWKS signature verification — the callback never accepts a caller-supplied `id_token`. Adding local signature / `aud` / `iss` / `exp` checks is welcome defense-in-depth (please open a GitHub issue/PR), but their absence is not an account-takeover vector on its own.
* **JWT "algorithm confusion" / unpinned `algorithms` in `jwt.verify`.** Puter's session tokens are HMAC-signed (HS256) with a server-side secret, and there is no asymmetric public key anywhere in the verification path, so `alg`-substitution attacks do not apply. Explicitly pinning `algorithms` is a fine hardening PR, but it is not a vulnerability.
* **Static-source "SQL injection" in internal pagination.** Findings such as `LIMIT ${limit}` in list/notification queries: the limit is numerically coerced and clamped before it reaches the query, so it is not reachable with attacker-controlled string input. Hardening PRs to the internal stores are welcome, but these are not exploitable as reported.
* **Deprecated `saveTo*` GUI app messages.** The legacy `saveToDesktop` / `saveToDocuments` / etc. app-IPC handlers can create — never overwrite — new files in standard user folders. The behavior is non-destructive, path-traversal-safe, and deprecated (slated for removal); it is not treated as a sandbox escape.
* **Best-practice suggestions** such as login/registration username enumeration (kept intentionally for UX) or unauthenticated unsubscribe links (industry norm).
* **Rate-limiting suggestions for TURN credential issuance** (intentional; not billed per tunnel).
- **XSS / CORS / token issues scoped to `api.puter.com`.** The primary user session cookie lives on `puter.com`, not on the API origin, so reflected/stored XSS, CORS, or token handling on `api.puter.com` is generally out of scope. Two exceptions we _do_ evaluate on their merits — please report these: (a) attacker-controlled content served **inline** (e.g. an HTML `Content-Type`) from API file/response endpoints, and (b) anything that abuses the app-scoped `puter_token_v2` companion cookie set on the API host.
- **SSRF via `secureFetch`.** Production routes outbound requests through an isolated proxy that has no access to internal/SSRF-sensitive resources.
- **Attacks that depend on guessing an `appInstanceID` or app UID.** These are random 128-bit secret values and are not considered guessable.
- **Apps invoking drivers, creating workers, or using KV.** Applications are intended to do this; worker permissions are scoped to the owning app. This is by design.
- **App metadata or app user-count "leaks".** This information is currently public by design.
- **General "token in a URL" / token-lifetime designs** — signed directory URLs exposing children, a write signature implying read, or app tokens outliving a web session. These are current intended behaviors.
- **Missing PKCE, unverified `id_token` signatures, or other OIDC hardening.** Provider tokens are obtained through a server-to-server authorization-code exchange with the provider's token endpoint over TLS, so the resulting `id_token` / userinfo claims are trusted from that channel rather than from local JWKS signature verification — the callback never accepts a caller-supplied `id_token`. Adding local signature / `aud` / `iss` / `exp` checks is welcome defense-in-depth (please open a GitHub issue/PR), but their absence is not an account-takeover vector on its own.
- **JWT "algorithm confusion" / unpinned `algorithms` in `jwt.verify`.** Puter's session tokens are HMAC-signed (HS256) with a server-side secret, and there is no asymmetric public key anywhere in the verification path, so `alg`-substitution attacks do not apply. Explicitly pinning `algorithms` is a fine hardening PR, but it is not a vulnerability.
- **Static-source "SQL injection" in internal pagination.** Findings such as `LIMIT ${limit}` in list/notification queries: the limit is numerically coerced and clamped before it reaches the query, so it is not reachable with attacker-controlled string input. Hardening PRs to the internal stores are welcome, but these are not exploitable as reported.
- **Deprecated `saveTo*` GUI app messages.** The legacy `saveToDesktop` / `saveToDocuments` / etc. app-IPC handlers can create — never overwrite — new files in standard user folders. The behavior is non-destructive, path-traversal-safe, and deprecated (slated for removal); it is not treated as a sandbox escape.
- **Best-practice suggestions** such as login/registration username enumeration (kept intentionally for UX) or unauthenticated unsubscribe links (industry norm).
- **Rate-limiting suggestions for TURN credential issuance** (intentional; not billed per tunnel).
If you believe you have a **genuinely new** exploit chain that defeats one of these rationales (for example, demonstrating a sensitive credential that really is reachable on `api.puter.com`), say so explicitly and show why the reasoning above does not apply.
@@ -40,7 +40,7 @@ If you believe you have a **genuinely new** exploit chain that defeats one of th
To participate, you must:
1. **Report responsibly**: Provide detailed steps to reproduce the issue, including proof-of-concept code, screenshots, or a screen recording (see *Proof of Reproduction* below).
1. **Report responsibly**: Provide detailed steps to reproduce the issue, including proof-of-concept code, screenshots, or a screen recording (see _Proof of Reproduction_ below).
2. **Do no harm**: Do not exfiltrate, modify, or delete data. Only access your own account or test data.
3. **Respect availability**: Do not perform denial-of-service attacks or automated scans that degrade service.
4. **Follow disclosure policy**: Do not publicly disclose vulnerabilities until we have confirmed and patched the issue.
@@ -51,26 +51,30 @@ Reports that do not meet these guidelines may not be eligible for a reward.
## Proof of Reproduction
Reports must demonstrate a **working, reproducible exploit with real impact** — not a theoretical or static-source-review finding. Please include:
Reports **MUST** demonstrate a **working, reproducible exploit with real impact** — not a theoretical or static-source-review finding. Please include:
* Exact steps to reproduce, the relevant request/response or code path, and the commit or version you tested.
* The **observed** result versus the **expected** result.
* For client-side, UI, or authentication-flow bugs: a short screen recording (≤ 2 minutes) showing the exploit working end-to-end on a real Puter instance.
* For server-side bugs: a runnable proof-of-concept.
- Exact steps to reproduce, the relevant request/response or code path, and the commit or version you tested.
- The **observed** result versus the **expected** result.
- For client-side, UI, or authentication-flow bugs: a short screen recording (≤ 2 minutes) showing the exploit working end-to-end on a real Puter instance.
- For server-side bugs: a runnable proof-of-concept and screenshot or video showing the attack process.
Reports based solely on reading the source ("source review only, not tested") or unverified AI/LLM-generated reports are the **lowest triage priority and are generally not eligible**. If you used an AI tool to help find an issue, you must personally verify that it actually reproduces before submitting.
Reports based solely on reading the source ("source review only, not tested") or unverified AI/LLM-generated reports are the **lowest triage priority and not eligible for bounty**.
If you used an AI tool to help find an issue, you must personally verify that it actually reproduces before submitting.
Please submit **one issue per report**. Bundled "audit packs" of many speculative findings will be declined; send each confirmed issue separately.
Please submit **one issue per report**.
Bundled "audit packs" of many speculative findings will not be elligible for bounty; send each confirmed issue separately.
Additionally please **DO NOT** submit too many issues at once; these will be treated as a bundled report, and will not be elligible for bounty.
## Reporting Process
To report a vulnerability, email us at: **[[email protected]](mailto:[email protected])**.
Include:
* A description of the vulnerability
* Steps to reproduce
* Potential impact
* Suggested remediation (if available)
- A description of the vulnerability
- Steps to reproduce
- Potential impact
- Suggested remediation (if available)
- Paypal id where we can send the bounty (if eligible)
We aim to acknowledge receipt within **72 hours** and provide a resolution timeline.
@@ -78,10 +82,10 @@ We aim to acknowledge receipt within **72 hours** and provide a resolution timel
We offer monetary rewards based on the severity of the vulnerability, as determined by our internal assessment (using CVSS as a guide).
* **Critical: \$1,000 – \$2,000**
* **High: \$500 – \$1,000**
* **Medium: \$200 – \$500**
* **Low: \$50 – \$100**
- **Critical: \$1,000 – \$2,000**
- **High: \$500 – \$1,000**
- **Medium: \$200 – \$500**
- **Low: \$50 – \$100**
Non-security issues, suggestions, and best practices feedback are always welcome, but may not qualify for a reward.
If multiple researchers report the same issue, the bounty will be awarded to the first eligible report we receive.
+2
View File
@@ -32,6 +32,8 @@ Don't commit code you couldn't have written, debugged, or defended yourself. Rea
If you add or change a public API (an endpoint, driver method, or puter-js method), follow [doc/contributing-apis.md](doc/contributing-apis.md) — backward compatibility, [developer docs](src/docs/), types, and tests all move in the same PR.
The same rule applies to limits: rate limits, concurrency caps, quotas, and allowances are published in [src/docs/src/rate-limits-and-quotas.md](src/docs/src/rate-limits-and-quotas.md), and a PR that changes one of those numbers updates that page in the same PR. A limit nobody published is a limit developers only discover as a service failure.
## 6. Boy Scout Rule — leave it 1% better
![Boy Scout Rule](https://imgs.search.brave.com/DMmIWl5-NuZVtrR9kXBb06AKF8kturkgSW9UMb2-6m4/rs:fit:860:0:0:0/g:ce/aHR0cHM6Ly9sYXdz/b2Zzb2Z0d2FyZWVu/Z2luZWVyaW5nLmNv/bS9pbWFnZXMvbGF3/cy9ib3ktc2NvdXQt/cnVsZS5wbmc)
-7
View File
@@ -12,10 +12,6 @@
·
<a href="https://developer.puter.com" target="_blank">Developers</a>
·
<a href="https://discord.com/invite/PQcx7Teh8u">Discord</a>
·
<a href="https://reddit.com/r/puter">Reddit</a>
·
<a href="https://twitter.com/HeyPuter">X</a>
</p>
@@ -82,10 +78,7 @@ Puter is available as a hosted service at [**puter.com**](https://puter.com).
Connect with the maintainers and community through these channels:
- Bug report or feature request? Please [open an issue](https://github.com/HeyPuter/puter/issues/new/choose).
- Discord: [discord.com/invite/PQcx7Teh8u](https://discord.com/invite/PQcx7Teh8u)
- X (Twitter): [x.com/HeyPuter](https://x.com/HeyPuter)
- Reddit: [reddit.com/r/puter/](https://www.reddit.com/r/puter/)
- Mastodon: [mastodon.social/@puter](https://mastodon.social/@puter)
- Security issues or abuse reports? [[email protected]](mailto:[email protected])
- Email maintainers at [[email protected]](mailto:[email protected])
+73
View File
@@ -0,0 +1,73 @@
# Reverse proxy in front of Puter — mirrors what the prod ALB does:
# accepts every Host header, forwards to the Puter container, and lets
# the Puter app handle subdomain-based routing internally (api.*,
# site.*, app.*, dev.*, plus the per-user subdomains under those).
#
# To enable TLS:
# 1. Drop a wildcard fullchain.pem + privkey.pem into ./puter/tls/
# (see "Step 3 — TLS" in doc/self-hosting.md).
# 2. Uncomment the `:443` block at the bottom of this file, and swap the
# `:80` block for the redirect shown alongside it.
# 3. Uncomment the `443:443` port mapping under the `caddy` service in
# docker-compose.yml, and HTTPS_PORT in .env.
# 4. Set `"protocol": "https"` and `"pub_port": 443` in config.json.
{
# Certs are supplied by the operator, not issued by Caddy. Puter serves
# per-user sites and apps on dynamic subdomains (<name>.site.<domain>,
# <name>.app.<domain>) — only a DNS-01 wildcard cert covers those, and
# DNS-01 needs a provider plugin that isn't in the stock caddy image.
# `off` stops Caddy attempting ACME on boot (it would fail and leave the
# site unreachable) and stops it inventing its own http→https redirects.
auto_https off
}
# Shared handling, imported by the HTTP and HTTPS site blocks below so the
# two can't drift apart.
(puter_routes) {
# Rough size cap that mirrors prod ALB defaults; tune for your uploads.
# Puter chunks large uploads, so 1 GiB per request is plenty.
request_body {
max_size 1024MiB
}
# RustFS — see the `s3` service in docker-compose.yml. Browsers PUT/GET
# here for presigned-URL uploads / downloads. Matched on the `s3.`
# subdomain of whatever the install domain is, so signature verification
# works (Caddy preserves the original Host end-to-end) and HTTPS stays
# clean — no mixed content from a port-9000 host publish.
@s3 header_regexp Host ^s3\.
handle @s3 {
reverse_proxy s3:9000
}
# Everything else, on every Host, goes to Puter — which routes on that
# Host internally. Caddy forwards it unchanged and adds X-Forwarded-For
# / -Proto / -Host, which is what `trust_proxy` in config.json counts.
handle {
reverse_proxy puter:4100 {
# Stream responses through unbuffered — Puter uses SSE and
# socket.io. WebSocket upgrades need no config of their own;
# Caddy proxies them by default.
flush_interval -1
}
}
}
# ── HTTP (port 80) ─────────────────────────────────────────────────────
# A site address with no hostname is the catch-all: it answers for every
# Host, which is what Puter's subdomain routing requires.
:80 {
import puter_routes
}
# ── HTTPS (port 443) — uncomment after dropping certs in ./puter/tls/ ──
# Replace the `:80` block above with a redirect to force HTTPS everywhere:
#
# :80 {
# redir https://{host}{uri} permanent
# }
#
# :443 {
# tls /etc/caddy/tls/fullchain.pem /etc/caddy/tls/privkey.pem
# import puter_routes
# }
-2
View File
@@ -5,9 +5,7 @@
"protocol": "http",
"domain": "puter.localhost",
"cookie_name": "puter_auth_token",
"jwt_secret": "dev-jwt-secret-change-me",
"jwt_secret_v2": "dev-jwt-secret-v2-change-me",
"allow_v1_tokens": true,
"url_signature_secret": "dev-url-signature-secret-change-me",
"allow_all_host_values": true,
"allow_no_host_header": true,
+113 -6
View File
@@ -73,11 +73,7 @@
// ── Auth / session ──────────────────────────────────────────────────
// ALWAYS replace these for any public install — `openssl rand -hex 64`.
// `jwt_secret` is legacy verify-only; new tokens sign with `jwt_secret_v2`.
"jwt_secret": "change-me",
"jwt_secret_v2": "change-me",
// Set false to retire v1 tokens entirely (ROLLOUT-1).
"allow_v1_tokens": true,
"url_signature_secret": "change-me",
"cookie_name": "puter_auth_token",
"min_pass_length": 6,
@@ -255,6 +251,82 @@
}
},
// ── Sharing ─────────────────────────────────────────────────────────
// Email a recipient who already has an account about a new share. On
// unless set to false; they opt out via the unsubscribe link, or by
// blocking a sender. An invite to an address with no account always goes.
// "share_email_notifications": false,
//
// New shares one account may create per UTC day. Default 200.
// "share_daily_limit": 200,
//
// How often a share may interrupt its recipient — the notification pushed
// to their screen and the email with it. Over budget the share still
// succeeds and their notification is still brought up to date; only the
// interruption is dropped. The recipient bounds are what stop many senders
// burying one person between them. A non-positive value removes a bound.
// "share_notify_limits": {
// "pairWindowSeconds": 900,
// "pairDaily": 20,
// "recipientHourly": 10,
// "recipientDaily": 50,
// "emailBatchSeconds": 90
// },
// ── Alarms / alerting ───────────────────────────────────────────────
// Where system alarms go. Severity is the routing decision — each
// transport takes everything at or above its own `minSeverity`:
//
// critical — an unhandled server error; pages on-call.
// error — pages as well; prefer critical or warning.
// warning — look at it today; no page.
// info — a record in the chat channel only.
//
// Both transports are off unless enabled, so a self-hosted node just
// logs its alarms to the console.
"pager": {
// Severity for call sites that don't pick one. Default "critical".
"defaultSeverity": "critical",
// Retier or silence an alarm without a deploy. Keys are alarm ids,
// or a prefix ending in `*`; the exact id wins over a pattern, and
// the longest matching pattern wins among patterns. Values are a
// severity or "mute". This is applied last, so it overrides both the
// call site and any known-error rule.
"severityOverrides": {
// "cronMonitor:*": "info",
// "http_500:GET:/some/flapping/route:*": "mute"
},
"pagerduty": {
"enabled": false,
"routingKey": "",
// Lowest severity that reaches PagerDuty. Default "warning",
// which keeps `info` out of the paging system entirely.
"minSeverity": "warning"
},
// Slack incoming webhook — the low-noise destination for everything
// that shouldn't page.
"slack": {
"enabled": false,
"webhookUrl": "",
// Optional; defaults to the channel the webhook was created for.
"channel": "#alerts",
"username": "puter-alarms",
// Severity window posted to Slack. The ceiling defaults to
// "info" when PagerDuty is configured — what pages belongs in
// the pager, not in chat — and to "critical" when Slack is the
// only transport.
"minSeverity": "info",
"maxSeverity": "info",
// Don't repost the same alarm id within this window. The first
// occurrence always posts; the next post that gets through
// reports how many occurrences piled up. 0 disables throttling.
"repeatThrottleMs": 900000
}
},
// ── Rate limiting ───────────────────────────────────────────────────
// `memory` for single-node, `redis` for multi-node (default), `kv` for
// dynamo-backed counters.
@@ -274,6 +346,10 @@
"apiURL": ""
},
"gemini": { "apiKey": "" },
// Meta Model API (Muse Spark). `muse-spark-1.2-contributor`
// trades a ~12x discount for Meta training on its prompts and
// completions, so it is only served to callers that name it.
"meta": { "apiKey": "" },
"groq": { "apiKey": "" },
"deepseek": { "apiKey": "" },
"mistral": { "apiKey": "" },
@@ -291,6 +367,16 @@
"apiKey": "",
"apiBaseUrl": "https://llm.onerouter.pro/v1"
},
// BytePlus ModelArk. One key powers chat (Seed/GLM/DeepSeek), image
// generation (Seedream) and video generation (Seedance); `apiBaseUrl`
// selects the region; see
// https://docs.byteplus.com/en/docs/ModelArk/1330310 for options.
"byteplus": {
"apiKey": "",
"apiBaseUrl": "https://ark.ap-southeast.bytepluses.com/api/v3"
},
"zai": { "apiKey": "" },
"alibaba": { "apiKey": "" },
"together-ai": { "apiKey": "" },
// Local Ollama. `enabled: false` skips the auto-probe at startup
// (otherwise Puter logs ECONNREFUSED on every boot when no Ollama
@@ -387,6 +473,27 @@
],
// ── Metering ────────────────────────────────────────────────────────
// When true, all metering checks pass — no per-actor limits enforced.
"unlimitedMetering": false
// When true, every account resolves to an unlimited policy: usage is still
// recorded, but nothing is ever refused for lack of budget. This is the
// setting for a deployment with no way to buy more — without it, accounts
// are held to the free monthly allowance and start getting 402s from the AI
// surfaces, file transfers and KV once they pass it.
"unlimitedMetering": false,
// Whether an account that has spent its whole allowance is refused the
// operations that spend it — file transfers, KV calls. Recording is
// unaffected either way. `workers` extends the same refusal to
// worker-driven calls, which are exempt by default because a deployed
// worker has nowhere to surface a payment prompt. `subscriptions` covers
// the separate question of surfaces reserved for paid plans (the
// vendor-compatible AI endpoints): turn it off on a deployment with no
// paid plans, or every account is refused them.
// "meteringEnforcement": { "enabled": true, "workers": false, "subscriptions": true },
// Fleet-wide spend rate, in micro-cents per minute, past which metering
// raises the `metering:excessiveGlobalUsageRate` alarm. Omit it (the
// default) to leave the check off: the only useful value is a multiple of
// what this deployment's normal traffic costs, so it has to be measured
// rather than guessed, and a stale number here alarms on healthy growth.
// "maxGlobalUsagePerMinute": 200000000
}
+127
View File
@@ -0,0 +1,127 @@
# Alarms
`clients.alarm` is the one way code reports that something is wrong. It
de-dupes by alarm id, counts occurrences, and routes each alarm to alert
transports by **severity**.
```ts
this.clients.alarm.create(
`metering_write_failed:${userUuid}`, // de-dupe key
'Metering write failed', // what a human reads
{ userUuid, appId, error }, // context fields
'info', // severity
);
```
## Severity is the routing decision
| Severity | Meaning | Goes to |
| ---------- | ------------------------------------------------------ | ----------- |
| `critical` | An unhandled server error. Someone gets woken up. | Pager |
| `error` | Same urgency as critical; prefer one of the other two. | Pager |
| `warning` | Worth a look today. Nobody is paged. | Pager (low) |
| `info` | A record of something expected-but-notable. | Chat |
Each transport declares the severity window it accepts, so the value a call
site passes is what decides where the alarm lands. The two windows don't
overlap by default: anything that pages lives in the paging system, and chat
is the record of what didn't. The bar for `critical` is
deliberately high: an unhandled 5xx out of the HTTP error handler is the main
thing that still pages. Anything a human can look at tomorrow is `warning`,
and anything that's just worth recording is `info`.
Omitting the severity takes `pager.defaultSeverity` (itself `critical`), so
pass one explicitly unless you really mean "page someone".
### Choosing one
- Did the server fail to do its job in a way nobody expected? → `critical`
- Is a background job, rate, or dependency degraded? → `warning`
- Is this a user doing something notable (tripping an abuse heuristic,
overspending)? → `info`
- Did one of *our own* limits reject a caller — a rate limit, a concurrency
cap, a quota? → don't alarm at all. The limit doing its job is not an
event; the 429 is the whole signal, and alarming on it only produces noise
proportional to traffic. An *upstream provider* rate-limiting us is the
opposite case and still alarms (`upstream_rate_limited`, `info`) — that one
is not something we chose. The exception is a free model: nothing is billed,
nothing is actionable, and the throttling is the price of the model, so the
AI chat driver marks those `noAlarm` and only paid models still record.
`noAlarm` is the code-level mute: an `HttpError` carrying it skips the
terminal gate entirely, no matter its status or code. It is for failures the
call site *already knows* are expected and traffic-proportional — reach for it
there, not as a way to quiet an alarm you haven't diagnosed
(`severityOverrides` below is the knob for that).
An extension whose signals are all one tier can default its own local
`raiseAlarm` helper to that tier instead of repeating it at every call site —
see [extensions/cronMonitor](../../../extensions/cronMonitor/index.js).
## One incident per occurrence, unless you say otherwise
Alarms always de-dupe *in process* — repeats of an id bump its occurrence
count rather than creating a second alarm. What that means for the pager is a
separate decision, and by default every occurrence opens its own PagerDuty
incident: two failed scans an hour apart are two things that happened, and
closing one shouldn't hide the other.
Pass `{ dedup: true }` as a fifth argument when repeats of the id really are
one recurring fault, and they collapse onto a single incident carrying the
occurrence count:
```ts
this.clients.alarm.create(alarmId, message, fields, 'critical', {
dedup: true,
});
```
The HTTP error handler uses it: its id is route + error signature, so a hot
loop of the same crash is one incident with N occurrences instead of N pages.
Reach for it anywhere else only when the id is that specific — otherwise a
per-request alarm can flood the pager.
## Configuration
Everything lives under `pager` in config (see
[config.template.jsonc](../config.template.jsonc) for the annotated version).
Both transports are off unless enabled, so a self-hosted node just logs
alarms to the console.
```jsonc
"pager": {
"defaultSeverity": "critical",
"severityOverrides": { "cronMonitor:*": "info" },
"pagerduty": { "enabled": true, "routingKey": "…", "minSeverity": "warning" },
"slack": {
"enabled": true,
"webhookUrl": "…",
"channel": "#alerts",
"minSeverity": "info",
"maxSeverity": "info",
"repeatThrottleMs": 900000,
},
}
```
Slack's `maxSeverity` defaults to `info` whenever PagerDuty is configured, and
to `critical` when it isn't — a node with only a webhook still sees
everything. Raise it to have chat mirror the paging tiers as well.
### Retiering without a deploy
`severityOverrides` is the escape hatch for an alarm that turns out to be
noisier or more serious than its call site assumed. Keys are alarm ids or a
prefix ending in `*`; the exact id beats a pattern, and the longest matching
prefix wins among patterns. Values are a severity, or `mute` to drop the
alarm before any transport sees it.
It is applied *after* the call site's severity and any known-error rule, so
config always has the last word.
### Repeat throttling
The chat transport won't repost the same alarm id within
`repeatThrottleMs` (default 15 minutes). The first occurrence always posts,
and the next one that gets through reports how many piled up in between —
so a hot loop reads as one message with a count, not a wall of them.
+8 -2
View File
@@ -53,7 +53,10 @@ Both are supported ways to define an API. **Prefer a controller when you need fi
#### Middleware and gates
- **Controller routes** (and extension routes — same options) take [`RouteOptions`](../src/backend/core/http/types.ts): auth gates (`requireAuth`, `requireUserActor`, `noUserSession`, `adminOnly`, `allowedAppIds`, and the access-token controls), `subdomain` routing, per-route `rateLimit`, body parsers, and arbitrary extra `middleware`. The auth flavors are subtle and default-deny — read the JSDoc on each field before picking.
- **Driver methods** get their policies from the `@Driver` options: per-method `rateLimit` (limit/window/backend), `concurrent` in-flight caps (optionally `bySubscription`), and `noUserSession`. The `/drivers/call` surface enforces them.
- **Driver methods** get their policies from the `@Driver` options: per-method `rateLimit` (limit/window/backend), `concurrent` in-flight caps (optionally `bySubscription`), `requireSubscription`, and `noUserSession`. The `/drivers/call` surface enforces them.
- **A surface only paying accounts should reach** declares `requireSubscription` — the route option on a controller endpoint, the per-method `@Driver({ requireSubscription })` block on a driver (`/drivers/call` is one shared route, so a driver's requirement can't live in route options). `true` accepts any plan that isn't free, so a plan registered by an extension counts without core naming it; an array of policy ids (`['business', 'pro']`) accepts only those; `false` is "no requirement", the same as leaving it out. An empty array is a boot error rather than a silent no-op — it reads as subscribers-only while admitting everyone. Off unless asked for, and answered from the metering service's cached per-actor subscription, so it costs a map lookup. Distinct from `requireCredits`: this asks which plan the account is on, not whether it has budget left. Deployments with no paid plans (self-hosted installs) turn the whole thing off with `meteringEnforcement.subscriptions: false`.
- **An account must have verified a specific factor** — `requireVerified` (email, and only under `strict_email_verification_required`), `requirePhoneVerified`, `requireCardVerified`. These are opt-in and require the factor to have actually been verified, unlike the default-on gate that turns away accounts still carrying a pending verification the abuse harness asked for.
- **An endpoint that spends metered resources** on the caller's behalf — moving file content, making object-store requests, anything else the account is billed for — also declares `requireCredits: true`, which turns an account with nothing left of its budget away with a 402 before the handler runs. Endpoints that only describe or delete things deliberately don't: an account that has run out still has to be able to see what it has, clear it, and reach its billing pages. Drivers have no route options to declare this on, so they call `assertActorHasCredits` themselves ([src/backend/services/metering/enforcement.ts](../src/backend/services/metering/enforcement.ts)) — see `KVStoreDriver`, which does it once for every method.
### 3. puter.js
@@ -62,7 +65,10 @@ Both are supported ways to define an API. **Prefer a controller when you need fi
### 4. Types
- Add or extend the declaration in [src/puter-js/types/modules/](../src/puter-js/types/modules/)`<module>.d.ts` and re-export new types through `index.d.ts`. Declarations must match the runtime exactly — optionality, defaults, and return types included.
- Type the method where you wrote it, in JSDoc: `@param`/`@returns` on the implementation, one `@overload` block per accepted call form, and `@typedef {Object}` + `@property` for any new shape. The JSDoc is the source of truth — declarations are generated from it, so there is nothing to keep in sync by hand.
- Put a shape more than one file needs in the module's `types.js` (e.g. [src/puter-js/src/modules/kv/types.js](../src/puter-js/src/modules/kv/types.js)); anything shared across modules goes in [src/puter-js/src/lib/types.js](../src/puter-js/src/lib/types.js). A shape with one consumer can stay next to it.
- Run `npm run check:puterjs:types` — it generates the declarations and type-checks the published surface without `skipLibCheck`. **Never edit anything under `src/puter-js/types/`**: it is gitignored build output, produced by the SDK build and shipped in the npm tarball, and the next build overwrites it.
- Name the new type in [src/puter-js/index.d.ts](../src/puter-js/index.d.ts) if consumers should be able to import it. That file is the one hand-written declaration in the package: it decides what is public and re-exports nothing else.
### 5. Docs
+69 -20
View File
@@ -1,6 +1,6 @@
# Self-Hosting Puter
`docker-compose.yml` brings up Puter **plus every external service it needs** — MariaDB, Valkey, DynamoDB-local, RustFS S3, nginx — wired together. Closest thing to a production deployment you can self-manage on a single host.
`docker-compose.yml` brings up Puter **plus every external service it needs** — MariaDB, Valkey, DynamoDB-local, RustFS S3, Caddy — wired together. Closest thing to a production deployment you can self-manage on a single host.
## One-line installer (recommended)
@@ -8,7 +8,7 @@
curl -fsSL https://raw.githubusercontent.com/HeyPuter/puter/main/install.sh | sh
```
Generates secrets, writes `.env` + `puter/config/config.json`, downloads `docker-compose.yml` from the OSS repo, and runs `docker compose up -d`. Re-running is safe — it won't overwrite existing config (set `PUTER_FORCE=1` to rotate). Use the manual steps below if you want to inspect or tweak each step yourself.
Generates secrets, writes `.env` + `puter/config/config.json`, downloads `docker-compose.yml` + `caddy/Caddyfile` from the OSS repo, and runs `docker compose up -d`. Re-running is safe — it won't overwrite existing config (set `PUTER_FORCE=1` to rotate). Use the manual steps below if you want to inspect or tweak each step yourself.
## Requirements
@@ -20,7 +20,7 @@ Generates secrets, writes `.env` + `puter/config/config.json`, downloads `docker
| Container | Image | Role |
| --------------- | ------------------------ | ---------------------------------------------------------- |
| `puter-nginx` | `nginx:1.27-alpine` | Reverse proxy on 80 (and 443 if TLS); forwards to Puter |
| `puter-caddy` | `caddy:2.11-alpine` | Reverse proxy on 80 (and 443 if TLS); forwards to Puter |
| `puter` | `ghcr.io/heyputer/puter` | The app |
| `puter-mariadb` | `mariadb:11` | SQL database — schema applied automatically on first boot |
| `puter-valkey` | `valkey/valkey:8-alpine` | Redis-compatible cache + rate-limiter |
@@ -47,7 +47,6 @@ State lives under `./puter/data/<service>/`.
MARIADB_ROOT_PASSWORD=$(openssl rand -hex 32)
MARIADB_PASSWORD=$(openssl rand -hex 32)
S3_SECRET_KEY=$(openssl rand -hex 32)
JWT_SECRET=$(openssl rand -hex 64)
JWT_SECRET_V2=$(openssl rand -hex 64)
URL_SIGNATURE_SECRET=$(openssl rand -hex 64)
@@ -65,7 +64,7 @@ S3_SECRET_KEY=$S3_SECRET_KEY
S3_BUCKET=puter-local
EOF
mkdir -p puter/config puter/data puter/tls
mkdir -p puter/config puter/data puter/data/caddy puter/tls
cat > puter/config/config.json <<EOF
{
"domain": "puter.localhost",
@@ -78,9 +77,7 @@ cat > puter/config/config.json <<EOF
"private_app_hosting_domain": "app.puter.localhost",
"private_app_hosting_domain_alt": "dev.puter.localhost",
"jwt_secret": "$JWT_SECRET",
"jwt_secret_v2": "$JWT_SECRET_V2",
"allow_v1_tokens": true,
"url_signature_secret": "$URL_SIGNATURE_SECRET",
"database": {
@@ -125,6 +122,10 @@ cat > puter/config/config.json <<EOF
"ollama": { "enabled": false }
},
"meteringEnforcement": {
"subscriptions": false
},
"trust_proxy": 1
}
EOF
@@ -134,21 +135,22 @@ Replace `puter.localhost`, `site.puter.localhost`, `host.puter.localhost`, `dev.
Why these knobs:
- `jwt_secret` + `jwt_secret_v2` — Puter signs new auth tokens with `jwt_secret_v2` (v2 token format, `kid: 'v2'` JWT header). `jwt_secret` is verify-only and lets tokens minted before this version (cookies still in users' browsers, stored API tokens) keep working. `allow_v1_tokens: true` keeps that fallback enabled. Fresh installs can leave it as-is; future versions will flip the flag to `false` and retire `jwt_secret` entirely once legacy tokens have drained.
- `jwt_secret_v2` — the HMAC secret Puter signs and verifies auth tokens with (`kid: 'v2'` JWT header). The pre-v2 token format is retired: a token signed with the old `jwt_secret` no longer verifies, and holders are asked to sign in again. If you are upgrading from a release that had `jwt_secret`, drop it from your config — it is ignored.
- `env: "prod"` — the bundled `config.default.json` ships with `env: "dev"` (matches the source-tree `npm run start:gui` workflow, which expects webpack-dev-server emitting a CSS manifest). Self-host runs against pre-built static bundles, so `env: "prod"` makes the homepage emit the `/dist/bundle.min.css` `<link>` tag instead of waiting on a manifest that doesn't exist.
- `database.migrationPaths` — Puter applies the bundled MySQL/MariaDB schema on boot. The migration files are idempotent, so it is safe to leave this configured across restarts.
- `dynamo.bootstrapTables: true` — Puter creates its KV table on boot. **Only set against a local emulator**, never real AWS.
- `dynamo.aws` keys are dummies; DynamoDB-local doesn't validate them but the AWS SDK requires _something_. **Note:** DynamoDB uses `access_key` / `secret_key` (snake_case); S3 below uses `accessKeyId` / `secretAccessKey` (camelCase). Not interchangeable.
- `meteringEnforcement.subscriptions: false` — a few surfaces (the OpenAI/Anthropic-compatible AI endpoints) are declared paid-plan-only. A self-hosted install has no paid plans, so every account sits on the free policy and those routes would answer `402 subscription_required` for everyone. Turning the plan gates off opens them; nothing else about metering changes.
- `providers.ollama.enabled: false` — Puter auto-probes a local Ollama at `127.0.0.1:11434` by default; without one running you'd see `ECONNREFUSED` on every boot. To run a bundled Ollama, see [Optional: local LLM (Ollama)](#optional-local-llm-ollama) below.
- `s3.s3Config.forcePathStyle: true` — RustFS / MinIO / fauxqs need path-style URLs (`<endpoint>/<bucket>`). Real AWS S3 wants virtual-hosted (`<bucket>.<endpoint>`) — drop this flag (or set `false`) when you swap to real S3.
- `s3.s3Config.publicEndpoint` — `endpoint` (`http://s3:9000`) only resolves inside the docker network; presigned upload/download URLs handed to the browser need a host-reachable URL. nginx routes the `s3.<domain>` subdomain to RustFS internally and preserves the Host header end-to-end (required for S3 signature validation), so the browser hits the same port/protocol as the rest of the app — no separate published port, no mixed-content surprises when you turn on TLS. Switch to `https://s3.<your-domain>` once you enable TLS in Step 3. Real AWS S3 doesn't need this — its endpoint is already public; drop the field entirely.
- `trust_proxy: 1` — nginx terminates TLS and forwards `X-Forwarded-For`. Without this, `req.ip` is the docker-network address of the nginx container instead of the real client IP, which breaks rate limiting and IP-based audit logs. `1` = one trusted hop (nginx). Bump to `2` if you put Cloudflare in front of nginx; never set `true` (it trusts every hop and makes XFF forgeable).
- `s3.s3Config.publicEndpoint` — `endpoint` (`http://s3:9000`) only resolves inside the docker network; presigned upload/download URLs handed to the browser need a host-reachable URL. Caddy routes the `s3.<domain>` subdomain to RustFS internally and preserves the Host header end-to-end (required for S3 signature validation), so the browser hits the same port/protocol as the rest of the app — no separate published port, no mixed-content surprises when you turn on TLS. Switch to `https://s3.<your-domain>` once you enable TLS in Step 3. Real AWS S3 doesn't need this — its endpoint is already public; drop the field entirely.
- `trust_proxy: 1` — Caddy terminates TLS and forwards `X-Forwarded-For`. Without this, `req.ip` is the docker-network address of the Caddy container instead of the real client IP, which breaks rate limiting and IP-based audit logs. `1` = one trusted hop (Caddy). Bump to `2` if you put Cloudflare in front of Caddy; never set `true` (it trusts every hop and makes XFF forgeable).
> If you ever change `MARIADB_PASSWORD` after first boot, `.env` alone won't update MariaDB — its credentials are baked into `./puter/data/mariadb/` on first init. Either rotate the password inside MariaDB by hand or `docker compose down && rm -rf ./puter/data/mariadb` to start fresh.
## Step 2 — Point DNS at the server \[Optional\]
In your DNS provider, add records for the main domain plus the subdomains Puter and nginx route on (`api.*`, `site.*`, `app.*`, `s3.*`):
In your DNS provider, add records for the main domain plus the subdomains Puter and Caddy route on (`api.*`, `site.*`, `app.*`, `s3.*`):
```
A puter.localhost → <your server's public IP>
@@ -163,7 +165,7 @@ A dev.puter.localhost → <your server's public IP>
A *.dev.puter.localhost → <your server's public IP>
```
The wildcards are required — Puter routes via subdomains (`api.*`, `app.*`, etc.) and nginx routes browser S3 traffic via `s3.*` to RustFS.
The wildcards are required — Puter routes via subdomains (`api.*`, `app.*`, etc.) and Caddy routes browser S3 traffic via `s3.*` to RustFS.
## Step 3 — TLS (recommended for public installs) \[Optional\]
@@ -182,13 +184,15 @@ sudo certbot certonly --manual --preferred-challenges dns \
The cert needs to cover `*.puter.localhost` so that `s3.puter.localhost` (browser S3 endpoint), plus Puter's own `api.*` / `app.*` subdomains, all validate.
> **Why not Caddy's automatic HTTPS?** Caddy issues certs over ACME by itself, but only for hostnames it knows up front, and only over HTTP-01 with the stock image. Puter serves every user's site and app on a subdomain it invents at runtime (`<name>.site.<domain>`, `<name>.app.<domain>`), which needs a **wildcard** cert — and wildcards require DNS-01, which requires a DNS-provider plugin that isn't in `caddy:2.11-alpine`. So `caddy/Caddyfile` sets `auto_https off` and reads the cert you supply below. If you'd rather have Caddy manage certs, build an image with the plugin for your DNS provider (`xcaddy build --with github.com/caddy-dns/<provider>`) and swap the `tls` line for a `tls { dns <provider> … }` block.
Drop the resulting `fullchain.pem` and `privkey.pem` into `./puter/tls/`.
**Wire nginx to use them:**
**Wire Caddy to use them:**
1. Open [nginx/nginx.conf](../nginx/nginx.conf), uncomment **both** `# server { listen 443 ssl … }` blocks (one for `s3.*`, one for the catch-all).
2. (Optional) Replace the body of the port-80 blocks with `return 301 https://$host$request_uri;` to force HTTPS everywhere.
3. In [docker-compose.yml](../docker-compose.yml), uncomment the `443:443` port mapping under the `nginx` service.
1. Open [caddy/Caddyfile](../caddy/Caddyfile) and uncomment the `# :443 { … }` block at the bottom.
2. (Optional but recommended) Replace the plain `:80 { import puter_routes }` block with the `redir` version shown alongside it, to force HTTPS everywhere.
3. In [docker-compose.yml](../docker-compose.yml), uncomment the `443:443` port mapping under the `caddy` service.
4. In `.env`, uncomment `HTTPS_PORT=443`.
5. In `config.json`, switch:
```json
@@ -201,9 +205,9 @@ Drop the resulting `fullchain.pem` and `privkey.pem` into `./puter/tls/`.
## Running behind your own reverse proxy
The bundled `puter-nginx` mirrors production and is the supported default — it terminates TLS (Step 3) and forwards every Host to Puter. But plenty of self-hosters already run their own edge proxy (Caddy, Traefik, HAProxy, a cloud load balancer, another nginx). You can put Puter behind it instead; Puter doesn't terminate TLS itself in any setup, so "your proxy does TLS" is just a matter of pointing it at the Puter container and getting a handful of details right.
The bundled `puter-caddy` mirrors production and is the supported default — it terminates TLS (Step 3) and forwards every Host to Puter. But plenty of self-hosters already run their own edge proxy (Traefik, nginx, HAProxy, a cloud load balancer, another Caddy). You can put Puter behind it instead; Puter doesn't terminate TLS itself in any setup, so "your proxy does TLS" is just a matter of pointing it at the Puter container and getting a handful of details right.
You can keep the bundled nginx as the single hop your proxy talks to, or bypass it and forward straight to the Puter container on port `4100` (uncomment the `4100:4100` mapping under the `puter` service in [docker-compose.yml](../docker-compose.yml), or attach your proxy to the compose network). Either works — what matters is the rules below.
You can keep the bundled Caddy as the single hop your proxy talks to, or bypass it and forward straight to the Puter container on port `4100` (uncomment the `4100:4100` mapping under the `puter` service in [docker-compose.yml](../docker-compose.yml), or attach your proxy to the compose network). Either works — what matters is the rules below.
**The rules that actually matter** (getting any of these wrong is what causes the redirect loops and "Invalid Host header" failures people hit):
@@ -219,7 +223,7 @@ You can keep the bundled nginx as the single hop your proxy talks to, or bypass
- `X-Forwarded-For` — the real client IP (rate limiting + audit logs).
- `Upgrade` / `Connection` — passed through for WebSocket / socket.io upgrades, or the realtime connection silently fails.
5. **Set `trust_proxy` to the number of hops in front of Puter.** One external proxy talking directly to Puter → `"trust_proxy": 1` (installer: `PUTER_TRUST_PROXY=1`). A second proxy in front (e.g. Cloudflare → your proxy → Puter) → `2`. This is the count of proxies between the client and Puter, **including** the bundled nginx if you keep it. Too low and `req.ip` becomes a proxy address (breaks rate limiting); never set `true` (it trusts every hop and makes `X-Forwarded-For` forgeable).
5. **Set `trust_proxy` to the number of hops in front of Puter.** One external proxy talking directly to Puter → `"trust_proxy": 1` (installer: `PUTER_TRUST_PROXY=1`). A second proxy in front (e.g. Cloudflare → your proxy → Puter) → `2`. This is the count of proxies between the client and Puter, **including** the bundled Caddy if you keep it. Too low and `req.ip` becomes a proxy address (breaks rate limiting); never set `true` (it trusts every hop and makes `X-Forwarded-For` forgeable).
6. **Route the wildcard to Puter.** Your proxy must forward `*.<domain>` (covering `api.*`, `app.*`, and `s3.<domain>`) and `*.site.<domain>` (and any other hosting domains) to Puter — same wildcard DNS as Step 2. Puter does the per-subdomain routing internally; the proxy just needs to hand it the traffic with the Host intact.
@@ -227,6 +231,8 @@ With those in place the rest of the stack is unchanged — `docker compose up -d
## Step 4 — Bring it up
Both [docker-compose.yml](../docker-compose.yml) and [caddy/Caddyfile](../caddy/Caddyfile) need to sit next to your `.env` — clone the repo, or copy those two paths out of it. The Caddyfile is bind-mounted read-only; if it's missing, Docker creates a *directory* at that path and `puter-caddy` dies with "not a directory".
```bash
docker compose up -d
```
@@ -294,6 +300,18 @@ Used for password resets, email confirmation, and notifications. Without it thos
To require email confirmation before login, also set `"strict_email_verification_required": true`.
To read the mail yourself instead of sending it, point the transport at a local SMTP sink — [MailHog](https://github.com/mailhog/MailHog) catches everything and serves it at `http://localhost:8025`. Publish both ports; a container that only exposes them is unreachable from the host:
```sh
docker run -d -p 1025:1025 -p 8025:8025 mailhog/mailhog
```
```json
"email": { "from": "\"Puter\" <[email protected]>", "host": "127.0.0.1", "port": 1025, "secure": false, "ignoreTLS": true }
```
Share email is on once a transport exists: a recipient who already has an account is emailed as well as notified in-app, and they opt out with the unsubscribe link the mail carries. Set `"share_email_notifications": false` to keep those in the app only — an address with no account is still emailed, since there is nothing else to reach them with.
### Sign in with Google (or another OIDC provider)
```json
@@ -369,6 +387,37 @@ Default is 100 MB per user.
Set `is_storage_limited: false` for unlimited (bounded by host disk).
### Usage metering and budgets
Puter meters what an account costs to serve — bytes sent back, object-store
requests, KV capacity, AI tokens — against a monthly budget, and refuses the
operations that spend it once that budget is gone. The refusal is a `402` with
code `insufficient_funds`; reads that only describe things, and every kind of
deletion, stay available so an account can always see what it has and clear it.
On a self-hosted install this is almost certainly not what you want. There is
nowhere to buy more, so accounts are held to the free monthly allowance
(US$0.25 of measured cost — roughly 2 GiB of downloads) and start being refused
after that. Turn it off:
```json
"unlimitedMetering": true
```
Every account then resolves to an unlimited policy. Usage is still recorded, so
the dashboard still shows what is being consumed; nothing is ever refused for
lack of budget.
To keep the budgets but stop them blocking anything — recording only:
```json
"meteringEnforcement": { "enabled": false }
```
Calls driven by a deployed worker are exempt from enforcement by default,
because a worker has no prompt to show and nobody watching it fail. Set
`"meteringEnforcement": { "workers": true }` to include them.
### Captcha on signup / login
Built-in proof-of-work captcha — no external service needed.
@@ -469,7 +518,7 @@ Migrations re-apply idempotently across pulls. Volumes are preserved.
## Troubleshooting
**Site loads but I get "Bad Gateway" / nginx errors.**
**Site loads but I get a 502 / "Bad Gateway" from Caddy.**
The puter container failed to come up. `docker compose logs puter` will tell you which dependency rejected it (most often DB password mismatch between `.env` and `config.json`).
**Login screen says "admin password not set".**
+22 -12
View File
@@ -2,7 +2,7 @@
# Self-hosted Puter — full stack.
#
# Brings up Puter + every external service it needs:
# - nginx : reverse proxy (mirrors prod ALB; handles TLS + Host fan-out)
# - caddy : reverse proxy (mirrors prod ALB; handles TLS + Host fan-out)
# - valkey : redis-compatible cache / rate-limiter backend
# - mariadb : SQL database (Puter applies its schema on first boot)
# - dynamo : DynamoDB-local (KV store; Puter creates the table itself)
@@ -23,7 +23,8 @@
#
# Production:
# - Always replace the default passwords / S3 keys / Puter secrets.
# - Front Puter with TLS-terminating reverse proxy (Caddy / nginx).
# - Enable TLS on the bundled Caddy (see caddy/Caddyfile) or front the
# stack with your own TLS-terminating proxy.
# - Move state-bearing volumes to a backed-up location.
services:
@@ -118,7 +119,7 @@ services:
RUSTFS_SECRET_KEY: ${S3_SECRET_KEY:-puter-secret-change-me}
volumes:
- ./puter/data/s3:/data:z
# Internal-only — browsers reach RustFS via nginx (`s3.<domain>`),
# Internal-only — browsers reach RustFS via Caddy (`s3.<domain>`),
# which preserves the Host header for S3 signature validation and
# rides the same TLS termination as Puter. Uncomment to also expose
# 9000 directly on the host for `aws-cli` / debugging.
@@ -249,7 +250,7 @@ services:
condition: service_started
s3-init:
condition: service_completed_successfully
# Internal-only: nginx reaches it on the compose network. Uncomment
# Internal-only: Caddy reaches it on the compose network. Uncomment
# to also expose port 4100 directly on the host (useful for debugging).
# ports:
# - "4100:4100"
@@ -270,23 +271,32 @@ services:
retries: 3
start_period: 30s
nginx:
image: nginx:1.27-alpine
container_name: puter-nginx
caddy:
image: caddy:2.11-alpine
container_name: puter-caddy
restart: unless-stopped
depends_on:
puter:
condition: service_started
ports:
- "${HTTP_PORT:-80}:80"
# Uncomment when you enable TLS in nginx/nginx.conf:
# Uncomment when you enable TLS in caddy/Caddyfile:
# - "${HTTPS_PORT:-443}:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro,z
# TLS certs (fullchain.pem + privkey.pem). Read-only inside.
- ./puter/tls:/etc/nginx/tls:ro,z
- ./caddy/Caddyfile:/etc/caddy/Caddyfile:ro,z
# TLS certs (wildcard fullchain.pem + privkey.pem). Read-only inside.
- ./puter/tls:/etc/caddy/tls:ro,z
# Caddy's own state — the cert store it would use if you swap this
# config over to ACME. Kept under ./puter/data with everything else
# so one directory is the whole backup.
- ./puter/data/caddy:/data:z
healthcheck:
test: ["CMD-SHELL", "wget -qO- --tries=1 --timeout=2 http://localhost/ || exit 1"]
# Hits Caddy's local-only admin API rather than proxying through to
# Puter: this reports whether the proxy itself is up and configured,
# and keeps working once the `:80` block becomes an HTTPS redirect.
# 127.0.0.1, not localhost — the admin endpoint is IPv4-only and
# busybox wget tries ::1 first.
test: ["CMD-SHELL", "wget -qO- --tries=1 --timeout=2 http://127.0.0.1:2019/config/ >/dev/null || exit 1"]
interval: 10s
timeout: 3s
retries: 5
+37 -4
View File
@@ -2,6 +2,14 @@ import { Context } from '@heyputer/backend/src/core';
import type { Actor } from '@heyputer/backend/src/core/actor';
import { HttpError } from '@heyputer/backend/src/core/http';
import { PuterDriver } from '@heyputer/backend/src/drivers/types';
import type {
DriverConcurrentConfig,
DriverRateLimitConfig,
} from '@heyputer/backend/src/drivers/meta';
import {
DEFAULT_FREE_SUBSCRIPTION,
DEFAULT_TEMP_SUBSCRIPTION,
} from '@heyputer/backend/src/services/metering/consts';
import { extension } from '@heyputer/backend/src/extensions';
// App-telemetry lets an app owner enumerate the users who have
@@ -50,17 +58,42 @@ const parseIntParam = (
* Driver exposing the `app-telemetry` interface.
*
* The `/drivers/call` permission gate checks
* `service:app-telemetry:ii:app-telemetry`, which every actor already holds
* via the blanket `service` grant (hardcoded-permissions.js +
* `service:app-telemetry:ii:app-telemetry`, which every actor already holds via
* the blanket `service` grant (hardcoded-permissions.js +
* `default_implicit_user_app_permissions`). The real authorization — "is the
* caller the app owner?" — is enforced inside `get_users` below, exactly as
* v1 did.
* caller the app owner?" — is enforced inside `get_users` below, exactly as v1
* did.
*/
export class AppTelemetryDriver extends PuterDriver {
readonly driverInterface = 'app-telemetry';
readonly driverName = 'app-telemetry';
readonly isDefault = true;
// Declaring nothing here would leave both methods on the generic
// 600/minute driver default, which does not fit a paginated scan that
// can ask for MAX_LIMIT rows at MAX_OFFSET. This is a dashboard read —
// nobody calls it in a loop.
readonly rateLimit: DriverRateLimitConfig = {
default: {
limit: 60,
window: 60_000,
bySubscription: {
[DEFAULT_FREE_SUBSCRIPTION]: 30,
[DEFAULT_TEMP_SUBSCRIPTION]: 10,
},
},
};
readonly concurrent: DriverConcurrentConfig = {
default: {
limit: 5,
bySubscription: {
[DEFAULT_FREE_SUBSCRIPTION]: 2,
[DEFAULT_TEMP_SUBSCRIPTION]: 2,
},
},
};
/** Users who have authenticated into the given app (owner-only). */
async get_users({
app_uuid,
+555
View File
@@ -0,0 +1,555 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest';
import { extensionStore } from '../src/backend/extensions.ts';
import type { IConfig } from '../src/backend/types';
import './devWatcher.ts';
type Lifecycle = {
onServerStart: () => Promise<void>;
onServerShutdown: () => Promise<void>;
};
// The extension registers itself on import; that registry entry is the
// only handle on the service class.
const DevWatcherService = extensionStore.services.devWatcher as unknown as new (
config: IConfig,
clients: unknown,
stores: unknown,
services: unknown,
) => Lifecycle;
const makeService = (config: Record<string, unknown>): Lifecycle =>
new DevWatcherService(config as unknown as IConfig, {}, {}, {});
let workdir: string;
const write = (relative: string, contents: string): string => {
const abs = path.join(workdir, relative);
writeFileSync(abs, contents);
return abs;
};
/** Poll until `predicate` holds or the budget runs out. */
const waitFor = async (
predicate: () => boolean,
label: string,
timeoutMs = 15_000,
): Promise<void> => {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (predicate()) return;
await new Promise((r) => setTimeout(r, 20));
}
throw new Error(`timed out waiting for ${label}`);
};
const logLines = (spy: { mock: { calls: unknown[][] } }): string[] =>
spy.mock.calls.map((call) => call.map(String).join(' '));
describe('devWatcher extension', () => {
let log: ReturnType<typeof vi.spyOn>;
let warn: ReturnType<typeof vi.spyOn>;
let error: ReturnType<typeof vi.spyOn>;
beforeAll(() => {
workdir = mkdtempSync(path.join(tmpdir(), 'devwatch-test-'));
});
afterAll(() => {
rmSync(workdir, { recursive: true, force: true });
delete (extensionStore.services as Record<string, unknown>).devWatcher;
});
beforeEach(() => {
log = vi.spyOn(console, 'log').mockImplementation(() => {});
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
error = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
log.mockRestore();
warn.mockRestore();
error.mockRestore();
});
const started = () =>
logLines(log).some((line) =>
line.startsWith('[devwatch] starting watchers from'),
);
// -- start gating -------------------------------------------------
it('does nothing when the server is not running in dev', async () => {
await makeService({ env: 'production' }).onServerStart();
expect(started()).toBe(false);
});
it('does nothing when devwatch is explicitly disabled', async () => {
await makeService({
env: 'dev',
devwatch: { enabled: false },
}).onServerStart();
expect(started()).toBe(false);
});
it('does nothing when the server opts out with no_devwatch', async () => {
await makeService({
env: 'dev',
no_devwatch: true,
devwatch: { enabled: true },
}).onServerStart();
expect(started()).toBe(false);
});
it('starts in dev even with no explicit devwatch block', async () => {
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [],
ready_delay_ms: 0,
},
});
await service.onServerStart();
expect(started()).toBe(true);
await service.onServerShutdown();
});
it('starts outside dev when devwatch is explicitly enabled', async () => {
const service = makeService({
env: 'production',
devwatch: {
enabled: true,
root: workdir,
commands: [],
webpack: [],
ready_delay_ms: 0,
},
});
await service.onServerStart();
expect(started()).toBe(true);
await service.onServerShutdown();
});
it('ignores a devwatch config that is not an object', async () => {
// Falls back to `{}`, so the dev-env rule decides — and the
// default webpack entries would be used, so pin it off instead.
await makeService({
env: 'production',
devwatch: 'yes',
}).onServerStart();
expect(started()).toBe(false);
});
it('only starts once even if the lifecycle hook fires again', async () => {
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [],
ready_delay_ms: 0,
},
});
await service.onServerStart();
await service.onServerStart();
expect(
logLines(log).filter((line) =>
line.startsWith('[devwatch] starting watchers from'),
),
).toHaveLength(1);
await service.onServerShutdown();
});
it('waits out the configured ready delay before resolving', async () => {
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [],
ready_delay_ms: 60,
},
});
const start = Date.now();
await service.onServerStart();
expect(Date.now() - start).toBeGreaterThanOrEqual(50);
await service.onServerShutdown();
});
// -- child commands -----------------------------------------------
it('spawns a command, line-buffers its output and flushes the tail', async () => {
write(
'chatty.js',
[
"process.stdout.write('one\\ntwo\\n');",
"process.stderr.write('bad thing\\n');",
// No trailing newline: only the stream `end` flushes it.
"process.stdout.write('tail-no-newline');",
].join('\n'),
);
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [
{
name: 'chatty',
directory: '.',
command: 'node',
args: ['chatty.js'],
},
],
webpack: [],
ready_delay_ms: 0,
},
});
await service.onServerStart();
await waitFor(
() =>
logLines(log).some((l) =>
l.includes('[devwatch:chatty:1] tail-no-newline'),
),
'child stdout',
);
const lines = logLines(log);
expect(lines).toContain('[devwatch:chatty:1] one');
expect(lines).toContain('[devwatch:chatty:1] two');
expect(logLines(warn)).toContain('[devwatch:chatty:2] bad thing');
await waitFor(
() =>
logLines(log).some((l) =>
l.includes('[devwatch:chatty:exit] process exited'),
),
'child exit',
);
await service.onServerShutdown();
});
it('passes literal and computed env values to the child', async () => {
write(
'env.js',
'process.stdout.write(`STATIC=${process.env.STATIC_VALUE} ORIGIN=${process.env.FROM_CONFIG} MISSING=${process.env.BLOWS_UP}\\n`);',
);
const service = makeService({
env: 'dev',
origin: 'http://puter.localhost:4100',
devwatch: {
root: workdir,
commands: [
{
name: 'envtest',
directory: '.',
command: 'node',
args: ['env.js'],
env: {
STATIC_VALUE: 'literal',
FROM_CONFIG: ({
global_config,
}: {
global_config: Record<string, unknown> | null;
}) => String(global_config?.origin ?? ''),
// Reading through a null is the "config not
// loaded yet" shape the extension deliberately
// stays quiet about.
BLOWS_UP: () => {
const nothing = null as unknown as {
x: string;
};
return nothing.x;
},
NOISY: () => {
throw new Error('unexpected failure');
},
},
},
],
webpack: [],
ready_delay_ms: 0,
},
});
await service.onServerStart();
await waitFor(
() => logLines(log).some((l) => l.includes('STATIC=literal')),
'env output',
);
const line = logLines(log).find((l) => l.includes('STATIC=literal'))!;
expect(line).toContain('ORIGIN=http://puter.localhost:4100');
expect(line).toContain('MISSING=undefined');
// A null-property read is expected noise and stays silent; any
// other failure is reported.
const warnings = logLines(warn);
expect(
warnings.some((w) => w.includes('could not evaluate env function')),
).toBe(true);
expect(warnings.some((w) => w.includes('for BLOWS_UP'))).toBe(false);
expect(warnings.some((w) => w.includes('for NOISY'))).toBe(true);
await service.onServerShutdown();
});
it('kills a still-running child on shutdown', async () => {
write('forever.js', 'setInterval(() => {}, 1000);');
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [
{
name: 'forever',
directory: '.',
command: 'node',
args: ['forever.js'],
},
],
webpack: [],
ready_delay_ms: 0,
},
});
await service.onServerStart();
await service.onServerShutdown();
expect(logLines(log)).toContain('[devwatch:forever] stopping process');
await waitFor(
() =>
logLines(log).some((l) =>
l.includes('[devwatch:forever:exit] process exited'),
),
'child killed',
);
});
// -- webpack watchers ---------------------------------------------
const makeWebpackProject = (
name: string,
configFile: string,
contents: string,
packageJson?: string,
): string => {
const dir = path.join(workdir, name);
rmSync(dir, { recursive: true, force: true });
writeFileSync(
path.join(
(() => {
const { mkdirSync } =
require('node:fs') as typeof import('node:fs');
mkdirSync(path.join(dir, 'src'), { recursive: true });
return dir;
})(),
'src/entry.js',
),
"console.log('hello');\n",
);
writeFileSync(path.join(dir, configFile), contents);
if (packageJson) {
writeFileSync(path.join(dir, 'package.json'), packageJson);
}
return name;
};
it('compiles a CommonJS webpack config and reports later rebuilds', async () => {
const dir = makeWebpackProject(
'cjs-project',
'webpack.config.cjs',
`module.exports = {
mode: 'development',
entry: './src/entry.js',
output: { path: __dirname + '/out', filename: 'bundle.js' },
};`,
);
let onConfigSaw: Record<string, unknown> | undefined;
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [
{
name: 'cjs',
directory: dir,
onConfig: (cfg: Record<string, unknown>) => {
onConfigSaw = cfg;
},
},
],
ready_delay_ms: 0,
},
});
await service.onServerStart();
expect(onConfigSaw).toBeDefined();
// The watcher context is anchored at <root>/<directory> so relative
// entries resolve regardless of the server's cwd.
expect(onConfigSaw!.context).toBe(path.join(workdir, dir));
// First build is silent by design; force a rebuild and assert the
// update line shows up.
await new Promise((r) => setTimeout(r, 500));
writeFileSync(
path.join(workdir, dir, 'src/entry.js'),
"console.log('hello again');\n",
);
await waitFor(
() =>
logLines(log).some((l) =>
l.includes('[devwatch] updated cjs using Webpack'),
),
'webpack rebuild',
);
await service.onServerShutdown();
});
it('resolves an ESM webpack config declared through package.json type', async () => {
const dir = makeWebpackProject(
'esm-project',
'webpack.config.js',
`export default {
mode: 'development',
entry: './src/entry.js',
output: { filename: 'bundle.js' },
};`,
JSON.stringify({ name: 'esm-project', type: 'module' }),
);
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [{ directory: dir }],
ready_delay_ms: 0,
},
});
await service.onServerStart();
await service.onServerShutdown();
// Falling back to the directory as the display name is the
// documented behaviour when `name` is omitted.
expect(error).not.toHaveBeenCalled();
});
it('calls a config exported as a function and honours an explicit context', async () => {
const dir = makeWebpackProject(
'fn-project',
'webpack.config.cjs',
`module.exports = () => ({
mode: 'development',
context: 'src',
entry: './entry.js',
name: process.env.WEBPACK_MARKER,
output: { path: __dirname + '/out', filename: 'bundle.js' },
});`,
);
let seen: Record<string, unknown> | undefined;
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [
{
name: 'fn',
directory: dir,
env: { WEBPACK_MARKER: 'set-during-load' },
onConfig: (cfg: Record<string, unknown>) => {
seen = cfg;
},
},
],
ready_delay_ms: 0,
},
});
await service.onServerStart();
// Relative `context` resolves against <root>/<directory>.
expect(seen!.context).toBe(path.join(workdir, dir, 'src'));
// The entry's env map is applied while the config module runs, and
// restored afterwards.
expect(seen!.name).toBe('set-during-load');
expect(process.env.WEBPACK_MARKER).toBeUndefined();
await service.onServerShutdown();
});
it('reports a failing compilation instead of crashing the server', async () => {
const dir = makeWebpackProject(
'broken-project',
'webpack.config.cjs',
`module.exports = {
mode: 'development',
entry: './src/does-not-exist.js',
output: { path: __dirname + '/out', filename: 'bundle.js' },
};`,
);
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [{ name: 'broken', directory: dir }],
ready_delay_ms: 0,
},
});
await service.onServerStart();
await waitFor(
() =>
logLines(error).some((l) =>
l.includes('[devwatch] failed to update broken'),
),
'webpack failure',
);
expect(
logLines(error).some((l) =>
l.includes('[devwatch] error information: broken'),
),
).toBe(true);
await service.onServerShutdown();
});
it('fails loudly when a directory has no webpack config at all', async () => {
const dir = path.join('no-config');
const { mkdirSync } = await import('node:fs');
mkdirSync(path.join(workdir, dir), { recursive: true });
const service = makeService({
env: 'dev',
devwatch: {
root: workdir,
commands: [],
webpack: [{ name: 'missing', directory: dir }],
ready_delay_ms: 0,
},
});
await expect(service.onServerStart()).rejects.toThrow(
'could not find webpack config for: no-config',
);
await service.onServerShutdown();
});
});
+11 -1
View File
@@ -81,6 +81,16 @@ export const handleInstalledApps = async (
extension.get(
'/installedApps',
{ subdomain: 'api', requireUserActor: true, allowFullAccessToken: true },
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: {
scope: 'installed-apps',
limit: 120,
window: 60_000,
key: 'user',
},
},
handleInstalledApps,
);
+136 -8
View File
@@ -3,8 +3,13 @@ import { HttpError } from '@heyputer/backend/src/core/http';
import {
controllersContainers,
driversContainers,
servicesContainers,
} from '@heyputer/backend/src/exports';
import { extension } from '@heyputer/backend/src/extensions';
import {
creditMultiplierFrom,
toCredits,
} from '@heyputer/backend/src/services/metering/utils';
import type { Request, Response } from 'express';
const services = extension.import('service');
@@ -18,7 +23,7 @@ function collectAllCosts(): Record<string, unknown>[] {
const all: Record<string, unknown>[] = [];
const collect = (
source: Record<string, unknown>,
kind: 'driver' | 'controller',
kind: 'driver' | 'controller' | 'service',
) => {
for (const [name, instance] of Object.entries(source)) {
const fn = (
@@ -43,9 +48,48 @@ function collectAllCosts(): Record<string, unknown>[] {
};
collect(driversContainers as Record<string, unknown>, 'driver');
collect(controllersContainers as Record<string, unknown>, 'controller');
// Services report the costs that aren't tied to one endpoint — egress,
// which is metered for every response there is.
collect(servicesContainers as Record<string, unknown>, 'service');
return all;
}
// -- Credits scaling ---------------------------------------------------
//
// When the deployment configures a credit multiplier, every monetary amount
// is scaled to display credits BEFORE it leaves the server — raw metered
// amounts are never reported. Counts, units, and byte figures pass through
// untouched. A response that was scaled says so (`unit: 'credits'`); without
// a configured multiplier amounts pass through raw and clients render them
// as dollars.
/** The per-usage-type records of a UsageByType map, costs scaled. */
const scaleUsageByType = (
usage: Record<string, unknown>,
multiplier: number,
): Record<string, unknown> => {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(usage)) {
// `allowanceUsed` is the month's allowance-charged spend — monetary,
// scalar, scaled like the total.
if (key === 'total' || key === 'allowanceUsed') {
out[key] = toCredits(Number(value) || 0, multiplier);
} else if (
value &&
typeof value === 'object' &&
typeof (value as { cost?: unknown }).cost === 'number'
) {
out[key] = {
...(value as Record<string, unknown>),
cost: toCredits((value as { cost: number }).cost, multiplier),
};
} else {
out[key] = value;
}
}
return out;
};
export const handleMeteringUsage = async (
_req: Request,
res: Response,
@@ -57,7 +101,44 @@ export const handleMeteringUsage = async (
services.metering.getActorCurrentMonthUsageDetails(actor),
services.metering.getAllowedUsage(actor),
]);
res.json({ ...actorUsage, allowanceInfo });
const multiplier = creditMultiplierFrom(extension.config);
if (!multiplier) {
res.json({ ...actorUsage, allowanceInfo });
return;
}
res.json({
usage: scaleUsageByType(
actorUsage.usage as unknown as Record<string, unknown>,
multiplier,
),
appTotals: Object.fromEntries(
Object.entries(actorUsage.appTotals).map(([appId, totals]) => [
appId,
{ ...totals, total: toCredits(totals.total, multiplier) },
]),
),
allowanceInfo: {
...allowanceInfo,
remaining: toCredits(allowanceInfo.remaining, multiplier),
monthUsageAllowance: toCredits(
allowanceInfo.monthUsageAllowance,
multiplier,
),
// Monetary addon fields scale; absent ones stay absent rather
// than materializing as NaN/null. purchasedStorage is bytes.
addons: Object.fromEntries(
Object.entries(allowanceInfo.addons ?? {}).map(([k, v]) => [
k,
(k === 'purchasedCredits' ||
k === 'consumedPurchaseCredits') &&
typeof v === 'number'
? toCredits(v, multiplier)
: v,
]),
),
unit: 'credits',
},
});
};
export const handleMeteringUsageForApp = async (
@@ -88,7 +169,18 @@ export const handleMeteringUsageForApp = async (
actor,
appId,
);
res.json(appUsage);
const multiplier = creditMultiplierFrom(extension.config);
if (!multiplier) {
res.json(appUsage);
return;
}
res.json({
...scaleUsageByType(
appUsage as unknown as Record<string, unknown>,
multiplier,
),
unit: 'credits',
});
};
export const handleMeteringGlobalUsage = async (
@@ -105,31 +197,67 @@ export const handleMeteringAllCosts = async (
res: Response,
): Promise<void> => {
if (!cachedAllCosts) {
cachedAllCosts = collectAllCosts();
const raw = collectAllCosts();
const multiplier = creditMultiplierFrom(extension.config);
// Price the catalogue in the same unit the usage endpoints report:
// per-unit credits when a multiplier is configured, raw otherwise.
cachedAllCosts = multiplier
? raw.map(({ ucentsPerUnit, costs_currency: _cc, ...rest }) =>
typeof ucentsPerUnit === 'number'
? {
...rest,
creditsPerUnit: toCredits(
ucentsPerUnit,
multiplier,
),
}
: rest,
)
: raw;
}
res.json({ costs: cachedAllCosts });
};
/** Dashboard reads over the per-actor KV aggregates. */
const USAGE_READ_LIMIT = {
scope: 'metering-usage',
limit: 120,
window: 60_000,
key: 'user' as const,
};
extension.get(
'/metering/usage',
{ subdomain: 'api', requireAuth: true },
{ subdomain: 'api', requireAuth: true, rateLimit: USAGE_READ_LIMIT },
handleMeteringUsage,
);
extension.get(
'/metering/usage/:appIdOrName',
{ subdomain: 'api', requireAuth: true },
{ subdomain: 'api', requireAuth: true, rateLimit: USAGE_READ_LIMIT },
handleMeteringUsageForApp,
);
extension.get(
'/metering/globalUsage',
{ subdomain: 'api', adminOnly: true },
{
subdomain: 'api',
adminOnly: true,
// Sums across every shard of the global aggregate. Admin-gated, so
// this is loop protection — but one accidental poll is an
// expensive minute.
rateLimit: {
scope: 'metering-global-usage',
limit: 10,
window: 60_000,
key: 'user',
},
},
handleMeteringGlobalUsage,
);
extension.get(
'/metering/allCosts',
{ subdomain: 'api', requireAuth: true },
{ subdomain: 'api', requireAuth: true, rateLimit: USAGE_READ_LIMIT },
handleMeteringAllCosts,
);
+15 -3
View File
@@ -71,9 +71,7 @@ describe('serverInfo extension — handleServerInfo', () => {
const statfsSpy = vi
.spyOn(fs.default, 'statfs')
.mockRejectedValue(new Error('statfs unsupported'));
const errSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const { res, captured } = makeRes();
await handleServerInfo({} as Request, res);
@@ -88,4 +86,18 @@ describe('serverInfo extension — handleServerInfo', () => {
statfsSpy.mockRestore();
errSpy.mockRestore();
});
it('reports an unknown CPU model when os.cpus() comes back empty', async () => {
const os = await import('node:os');
const cpusSpy = vi.spyOn(os.default, 'cpus').mockReturnValue([]);
const { res, captured } = makeRes();
await handleServerInfo({} as Request, res);
const cpu = captured.body!.cpu as Record<string, unknown>;
expect(cpu.model).toBe('Unknown');
expect(cpu.cores).toBe(0);
cpusSpy.mockRestore();
});
});
+193 -5
View File
@@ -3,6 +3,7 @@ import {
PutObjectCommand,
type S3Client,
} from '@aws-sdk/client-s3';
import crypto from 'node:crypto';
import {
afterAll,
beforeAll,
@@ -14,6 +15,7 @@ import {
import { PuterServer } from '../src/backend/server.ts';
import { setupTestServer } from '../src/backend/testUtil.ts';
import {
handleFsCopyNodeThumbnail,
handleFsRemoveNodeThumbnail,
handleThumbnailCreated,
handleThumbnailRead,
@@ -26,6 +28,9 @@ const TINY_PNG_BASE64 =
const BUCKET = 'puter-local';
// Keys the extension will accept back: its own `thumbnails/<uuid>` namespace.
const mintedKey = () => `thumbnails/${crypto.randomUUID()}`;
const streamToBuffer = async (
body: { transformToByteArray: () => Promise<Uint8Array> } | undefined,
): Promise<Buffer> => {
@@ -195,7 +200,7 @@ describe('thumbnails extension — handleThumbnailRead', () => {
// Seed an object so the presigned URL points at something real
// (the signer itself doesn't validate existence, but this keeps
// the test honest).
const key = 'thumb-read-test';
const key = mintedKey();
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
@@ -220,6 +225,57 @@ describe('thumbnails extension — handleThumbnailRead', () => {
expect((entry.thumbnail as string).startsWith('http')).toBe(true);
});
// `fsentries.thumbnail` is writable through the FS API, so a stored
// pointer is attacker input. Signing one the extension didn't mint would
// hand out a presigned read of an arbitrary object — including another
// user's file, whose key is its fsentry uuid in this same bucket.
it.each([
// Shaped exactly like an fs object key (and like a legacy thumbnail
// row) — indistinguishable from a planted pointer, so it fails closed.
[
"another user's file object",
`s3://${BUCKET}/${crypto.randomUUID()}`,
],
[
'a key outside the thumbnails namespace',
`s3://${BUCKET}/secrets/dump`,
],
[
'a namespace-lookalike key',
`s3://${BUCKET}/thumbnails/../${crypto.randomUUID()}`,
],
['a non-uuid inside the namespace', `s3://${BUCKET}/thumbnails/etc`],
])('refuses to presign a pointer naming %s', async (_label, thumbnail) => {
const entry: Record<string, unknown> = { thumbnail };
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
db: stubDb,
});
expect(entry.thumbnail).toBeNull();
});
it('signs against its own bucket, ignoring the one in the pointer', async () => {
const key = mintedKey();
const entry: Record<string, unknown> = {
thumbnail: `s3://attacker-named-bucket/${key}`,
};
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
db: stubDb,
});
// Signed for OUR bucket; `attacker-named-bucket` never reached S3.
const signed = entry.thumbnail as string;
expect(signed.startsWith('http')).toBe(true);
expect(signed).not.toContain('attacker-named-bucket');
expect(signed).toContain(BUCKET);
});
it('leaves the thumbnail untouched when not s3/https/data', async () => {
const entry: Record<string, unknown> = { thumbnail: 'about:blank' };
await handleThumbnailRead(entry, {
@@ -285,7 +341,7 @@ describe('thumbnails extension — handleFsRemoveNodeThumbnail', () => {
});
it('deletes the S3 object referenced by an s3:// thumbnail URL', async () => {
const key = 'thumb-remove-test';
const key = mintedKey();
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
@@ -297,7 +353,7 @@ describe('thumbnails extension — handleFsRemoveNodeThumbnail', () => {
await handleFsRemoveNodeThumbnail(
{ target: { thumbnail: `s3://${BUCKET}/${key}` } },
{ s3 },
{ s3, bucketName: BUCKET },
);
// GetObject should now error because the key was deleted.
@@ -306,15 +362,147 @@ describe('thumbnails extension — handleFsRemoveNodeThumbnail', () => {
).rejects.toThrow();
});
// The destructive half of the same confused deputy: the stored pointer
// decides which object is deleted, so a key the extension didn't mint
// must never reach DeleteObject.
it('does not delete an object the pointer names but we did not mint', async () => {
const victimKey = crypto.randomUUID(); // shaped like an fs object key
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: victimKey,
Body: Buffer.from(TINY_PNG_BASE64, 'base64'),
ContentType: 'image/png',
}),
);
await handleFsRemoveNodeThumbnail(
{ target: { thumbnail: `s3://${BUCKET}/${victimKey}` } },
{ s3, bucketName: BUCKET },
);
const survivor = await s3.send(
new GetObjectCommand({ Bucket: BUCKET, Key: victimKey }),
);
expect(survivor.ContentType).toBe('image/png');
});
it('is a no-op when the target has no thumbnail', async () => {
// Should not throw or attempt a delete.
await handleFsRemoveNodeThumbnail({ target: {} }, { s3 });
await handleFsRemoveNodeThumbnail(
{ target: {} },
{ s3, bucketName: BUCKET },
);
});
it('is a no-op when the thumbnail URL is not an s3:// pointer', async () => {
await handleFsRemoveNodeThumbnail(
{ target: { thumbnail: 'https://cdn.example.com/x.png' } },
{ s3 },
{ s3, bucketName: BUCKET },
);
});
});
describe('thumbnails extension — handleFsCopyNodeThumbnail', () => {
let server: PuterServer;
let s3: S3Client;
beforeAll(async () => {
server = await setupTestServer();
s3 = server.clients.s3.get();
});
afterAll(async () => {
await server?.shutdown();
});
it('duplicates the shared thumbnail object and repoints the copied row', async () => {
const sourceKey = mintedKey();
const body = Buffer.from(TINY_PNG_BASE64, 'base64');
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: sourceKey,
Body: body,
ContentType: 'image/png',
}),
);
const copyUuid = crypto.randomUUID();
const db = { write: vi.fn().mockResolvedValue(undefined) };
await handleFsCopyNodeThumbnail(
{
copy: {
thumbnail: `s3://${BUCKET}/${sourceKey}`,
uuid: copyUuid,
},
},
{ s3, bucketName: BUCKET, db },
);
// The copied row was repointed at a fresh object...
expect(db.write).toHaveBeenCalledTimes(1);
const [, params] = db.write.mock.calls[0] as [string, [string, string]];
const [newPointer, updatedUuid] = params;
expect(updatedUuid).toBe(copyUuid);
expect(newPointer.startsWith(`s3://${BUCKET}/thumbnails/`)).toBe(true);
expect(newPointer).not.toBe(`s3://${BUCKET}/${sourceKey}`);
// ...whose content matches, while the source object survives — so
// deleting either entry can no longer break the other's thumbnail.
const newKey = newPointer.slice(`s3://${BUCKET}/`.length);
const duplicated = await s3.send(
new GetObjectCommand({ Bucket: BUCKET, Key: newKey }),
);
expect(
(await streamToBuffer(duplicated.Body as never)).equals(body),
).toBe(true);
const original = await s3.send(
new GetObjectCommand({ Bucket: BUCKET, Key: sourceKey }),
);
expect(original.ContentType).toBe('image/png');
});
it('drops the pointer when the shared object is already gone', async () => {
const copyUuid = crypto.randomUUID();
const db = { write: vi.fn().mockResolvedValue(undefined) };
await handleFsCopyNodeThumbnail(
{
copy: {
thumbnail: `s3://${BUCKET}/${mintedKey()}`, // never uploaded
uuid: copyUuid,
},
},
{ s3, bucketName: BUCKET, db },
);
expect(db.write).toHaveBeenCalledTimes(1);
const [sql, params] = db.write.mock.calls[0] as [string, [string]];
expect(sql).toContain('NULL');
expect(params).toEqual([copyUuid]);
});
it('does not duplicate an object the pointer names but we did not mint', async () => {
const foreignKey = crypto.randomUUID(); // shaped like an fs object key
const db = { write: vi.fn().mockResolvedValue(undefined) };
await handleFsCopyNodeThumbnail(
{
copy: {
thumbnail: `s3://${BUCKET}/${foreignKey}`,
uuid: crypto.randomUUID(),
},
},
{ s3, bucketName: BUCKET, db },
);
expect(db.write).not.toHaveBeenCalled();
});
it('is a no-op when the copy has no thumbnail', async () => {
const db = { write: vi.fn().mockResolvedValue(undefined) };
await handleFsCopyNodeThumbnail(
{ copy: { thumbnail: null, uuid: crypto.randomUUID() } },
{ s3, bucketName: BUCKET, db },
);
expect(db.write).not.toHaveBeenCalled();
});
});
+152 -29
View File
@@ -1,4 +1,5 @@
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
PutObjectCommand,
@@ -13,6 +14,54 @@ const clients = extension.import('client');
const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
const MAX_THUMBNAIL_PIXELS = 64e6;
// Namespace every object this extension writes. An fs object's key is its
// bare fsentry uuid and the default config points `thumbnailStore.name` at
// the same bucket as `s3_bucket`, so without a prefix of our own there is no
// way to tell a thumbnail we minted from any other object in the deployment.
const THUMBNAIL_KEY_PREFIX = 'thumbnails/';
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const mintThumbnailKey = (): string =>
`${THUMBNAIL_KEY_PREFIX}${crypto.randomUUID()}`;
/**
* Extract the object key from a stored thumbnail pointer, or null when the
* pointer isn't one this extension minted.
*
* `fsentries.thumbnail` is writable through the FS API, so neither half of the
* stored string is trusted: the bucket is discarded (callers always pass their
* own) and the key must sit under {@link THUMBNAIL_KEY_PREFIX} with a random
* uuid. Honouring an arbitrary key would lend this extension's storage
* credentials to whatever object the caller named — in the shared-bucket layout
* that is every user's file, since an fs object's key is its fsentry uuid.
* Legacy bare-uuid thumbnails fail the check and are treated as absent; they
* are indistinguishable from a planted pointer, so there is nothing safer to do
* with them than stop signing them.
*/
const resolveThumbnailKey = (pointer: string): string | null => {
let key: string;
if (pointer.startsWith('s3://')) {
const rest = pointer.slice('s3://'.length);
const slash = rest.indexOf('/');
if (slash === -1) return null;
key = rest.slice(slash + 1);
} else {
let pathname: string;
try {
pathname = new URL(pointer).pathname;
} catch {
return null;
}
const segments = pathname.replace(/^\/+/, '').split('/');
segments.shift(); // bucket
key = segments.join('/');
}
if (!key.startsWith(THUMBNAIL_KEY_PREFIX)) return null;
const id = key.slice(THUMBNAIL_KEY_PREFIX.length);
return UUID_PATTERN.test(id) ? key : null;
};
// S3 client + bucket config — lazily resolved after boot from config.
let s3Client: S3Client | null = null;
let s3PresignClient: S3Client | null = null;
@@ -112,7 +161,7 @@ export async function handleThumbnailCreated(
return;
}
const key = crypto.randomUUID();
const key = mintThumbnailKey();
event.url = `s3://${deps.bucketName}/${key}`;
await deps.s3.send(
@@ -151,7 +200,7 @@ export const handleThumbnailUploadPrepare = async (
continue;
}
const key = crypto.randomUUID();
const key = mintThumbnailKey();
const command = new PutObjectCommand({
Bucket: deps.bucketName,
Key: key,
@@ -178,27 +227,27 @@ export const handleThumbnailRead = async (
if (typeof thumb !== 'string' || !thumb) return;
const presignClient = deps.s3Presign;
if (thumb.startsWith('s3://')) {
const [bucket, key] = thumb.slice(5).split('/');
entry.thumbnail = await getSignedUrl(
presignClient,
new GetObjectCommand({ Bucket: bucket, Key: key }),
{ expiresIn: 604800 },
);
} else if (
thumb.startsWith('https') &&
thumb.includes(new URL(deps.bucketEndpoint).hostname)
) {
if (
thumb.startsWith('s3://') ||
// Legacy format — remove after full migration
const [bucket, key] = new URL(thumb).pathname.slice(1).split('/');
(thumb.startsWith('https') &&
thumb.includes(new URL(deps.bucketEndpoint).hostname))
) {
const key = resolveThumbnailKey(thumb);
if (!key) {
// Not a pointer we minted — refuse to sign it rather than hand
// out a presigned read of whatever object it names.
entry.thumbnail = null;
return;
}
entry.thumbnail = await getSignedUrl(
presignClient,
new GetObjectCommand({ Bucket: bucket, Key: key }),
new GetObjectCommand({ Bucket: deps.bucketName, Key: key }),
{ expiresIn: 604800 },
);
} else if (thumb.startsWith('data')) {
// Inline data-URL migration: upload to S3 and update the DB entry.
const key = crypto.randomUUID();
const key = mintThumbnailKey();
const { mimeType, data } = base64ParseDataUrl(thumb);
const newUrl = `s3://${deps.bucketName}/${key}`;
@@ -232,15 +281,72 @@ export const handleThumbnailRead = async (
}
};
export const handleFsRemoveNodeThumbnail = async (
payload: { target: Record<string, unknown> },
deps: { s3: S3Client },
export const handleFsCopyNodeThumbnail = async (
payload: { copy?: { thumbnail?: string | null; uuid?: string } | null },
deps: {
s3: S3Client;
bucketName: string;
db: { write: (sql: string, params: unknown[]) => Promise<unknown> };
},
): Promise<void> => {
const thumbnailUrl = payload.target.thumbnail as string | undefined;
if (!thumbnailUrl || !thumbnailUrl.startsWith('s3://')) return;
const copy = payload.copy;
const thumbnailUrl = copy?.thumbnail;
if (!copy || !copy.uuid || typeof thumbnailUrl !== 'string') return;
const [bucket, key] = thumbnailUrl.slice(5).split('/');
await deps.s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
// Same trust rule as the read and remove paths: only touch objects this
// extension minted.
const sourceKey = resolveThumbnailKey(thumbnailUrl);
if (!sourceKey) return;
// The copied row points at the SAME S3 object as its source, and
// fs.remove.node deletes the pointed-to object — so the first removal
// among the sharers (an overwrite, a trash purge) would break every
// other sharer's thumbnail. Give the copy an object of its own.
const newKey = mintThumbnailKey();
try {
await deps.s3.send(
new CopyObjectCommand({
Bucket: deps.bucketName,
CopySource: `${deps.bucketName}/${sourceKey}`,
Key: newKey,
}),
);
} catch (err) {
// The shared object is already gone (e.g. a sharer was removed
// before this fix existed) — the pointer is dead either way, so
// drop it rather than leave the row advertising a thumbnail it
// doesn't have.
await deps.db.write(
'UPDATE `fsentries` SET `thumbnail` = NULL WHERE `uuid` = ?',
[copy.uuid],
);
console.warn('[thumbnails] failed to duplicate thumbnail on copy', err);
return;
}
await deps.db.write(
'UPDATE `fsentries` SET `thumbnail` = ? WHERE `uuid` = ?',
[`s3://${deps.bucketName}/${newKey}`, copy.uuid],
);
};
export const handleFsRemoveNodeThumbnail = async (
payload: { target: { thumbnail?: string | null } },
deps: { s3: S3Client; bucketName: string },
): Promise<void> => {
const thumbnailUrl = payload.target.thumbnail;
if (!thumbnailUrl) return;
// Same trust rule as the read path, and load-bearing for the same reason:
// the pointer decides which object gets deleted, so a key we didn't mint
// would let the owner of one file destroy an object belonging to someone
// else just by naming it here.
const key = resolveThumbnailKey(thumbnailUrl);
if (!key) return;
await deps.s3.send(
new DeleteObjectCommand({ Bucket: deps.bucketName, Key: key }),
);
};
extension.on(
@@ -279,12 +385,29 @@ extension.on('thumbnail.read', async (_key, entry: Record<string, unknown>) => {
});
});
// -- fs.copy.node ----------------------------------------------------
// A copied entry initially shares its source's thumbnail object; duplicate
// it so removing either entry can't break the other's thumbnail.
extension.on('fs.copy.node', async (_key, payload) => {
await handleFsCopyNodeThumbnail(
payload as {
copy?: { thumbnail?: string | null; uuid?: string } | null;
},
{
s3: getClient(),
bucketName: thumbnailBucketName,
db: clients.db,
},
);
});
// -- fs.remove.node --------------------------------------------------
// Delete S3 thumbnail when the file is removed.
extension.on(
'fs.remove.node',
async (_key, payload: { target: Record<string, unknown> }) => {
await handleFsRemoveNodeThumbnail(payload, { s3: getClient() });
},
);
extension.on('fs.remove.node', async (_key, payload) => {
await handleFsRemoveNodeThumbnail(payload, {
s3: getClient(),
bucketName: thumbnailBucketName,
});
});
+84 -1
View File
@@ -109,6 +109,9 @@ describe('whoami extension — handleWhoami', () => {
expect(body.oidc_only).toBe(false);
// is_user_token is present (true) for user actors.
expect(body.is_user_token).toBe(true);
// Account creation time, in unix seconds.
expect(typeof body.created_ts).toBe('number');
expect(body.created_ts).toBeGreaterThan(0);
// `directories` is only sent to user actors — confirm it’s present.
expect(body.directories).toBeDefined();
// taskbar_items is only sent to user actors.
@@ -132,7 +135,7 @@ describe('whoami extension — handleWhoami', () => {
expect(flags.payment_bypass).toBeUndefined();
});
it('strips desktop_bg_* and human_readable_age fields for app actors', async () => {
it('strips desktop_bg_*, created_ts and human_readable_age fields for app actors', async () => {
const user = await seedUser();
const { res, captured } = makeRes();
@@ -154,6 +157,8 @@ describe('whoami extension — handleWhoami', () => {
expect(body.desktop_bg_color).toBeUndefined();
expect(body.desktop_bg_fit).toBeUndefined();
expect(body.human_readable_age).toBeUndefined();
// Account age, in either form, is not exposed to apps.
expect(body.created_ts).toBeUndefined();
// Directories are user-only.
expect(body.directories).toBeUndefined();
});
@@ -201,6 +206,84 @@ describe('whoami extension — handleWhoami', () => {
expect(JSON.stringify(body)).not.toContain('bootstrap-secret');
});
it('never exposes phone, card fingerprint or signup identity', async () => {
const user = await seedUser();
await server.stores.user.update(user.id as number, {
phone: '+15551234567',
card_fingerprint: 'fp_ABC123',
requires_phone_verification: false,
requires_card_verification: false,
});
// Guard against a vacuous assertion below: the columns really do hold
// the values we then expect never to see on the wire.
const stored = await server.stores.user.getById(user.id as number, {
cached: false,
force: true,
});
expect(stored?.phone).toBe('+15551234567');
expect(stored?.card_fingerprint).toBe('fp_ABC123');
for (const actor of [
{ user: { uuid: user.uuid, id: user.id as number } },
{
user: { uuid: user.uuid, id: user.id as number },
app: { uid: 'app-test-actor' },
},
]) {
const { res, captured } = makeRes();
await runWithContext({ actor }, () =>
handleWhoami(makeReq(), res),
);
const body = captured.body as Record<string, unknown>;
expect(body.phone).toBeUndefined();
expect(body.card_fingerprint).toBeUndefined();
expect(body.password).toBeUndefined();
expect(body.otp_secret).toBeUndefined();
expect(body.signup_ip).toBeUndefined();
// Not just absent as a key — the values must not appear anywhere
// in the payload (nested under metadata, taskbar items, …).
const serialized = JSON.stringify(body);
expect(serialized).not.toContain('5551234567');
expect(serialized).not.toContain('fp_ABC123');
// The verification flags, which the GUI acts on, still ship.
expect(body).toHaveProperty('requires_phone_verification');
expect(body).toHaveProperty('requires_card_verification');
}
});
it('scrubs sensitive keys added to metadata, and leaves the cached row intact', async () => {
const user = await seedUser();
await server.stores.user.updateMetadata(user.id as number, {
tmp_password: 'bootstrap-secret',
billing: { card_fingerprint: 'fp_NESTED', tier: 'pro' },
});
const { res, captured } = makeRes();
await runWithContext(
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
() => handleWhoami(makeReq(), res),
);
const body = captured.body as Record<string, unknown>;
const metadata = body.metadata as Record<string, unknown>;
expect(metadata.tmp_password).toBeUndefined();
// Nested sensitive keys are removed too; siblings survive.
expect(metadata.billing).toEqual({ tier: 'pro' });
expect(JSON.stringify(body)).not.toContain('fp_NESTED');
// The scrub works on a copy — server-side state is untouched.
const fresh = await server.stores.user.getById(user.id as number, {
cached: false,
force: true,
});
expect(fresh?.metadata?.tmp_password).toBe('bootstrap-secret');
expect(
(fresh?.metadata?.billing as Record<string, unknown>)
?.card_fingerprint,
).toBe('fp_NESTED');
});
it('marks the user as oidc_only when password is null', async () => {
const slug = Math.random().toString(36).slice(2, 8);
const oidcUser = await server.stores.user.create({
+113 -14
View File
@@ -14,6 +14,15 @@ const timeago = (() => {
return new TimeAgo('en-US');
})();
// User timestamps come off the DB as SQL datetime strings; the wire format
// for all of them is unix seconds. Unparseable values are dropped rather
// than sent as NaN.
const toUnixSeconds = (value: unknown): number | undefined => {
if (!value) return undefined;
const ms = new Date(value as string | number | Date).getTime();
return Number.isNaN(ms) ? undefined : Math.round(ms / 1000);
};
// Allowlist of `config.feature_flags` keys safe to surface via /whoami.
// Anything not listed here stays server-side, so internal flags
// (payment_bypass, staff_only_*, etc.) cannot leak by accident. Add a
@@ -24,6 +33,68 @@ const CLIENT_VISIBLE_FEATURE_FLAGS: ReadonlySet<string> = new Set([
'prompt_user_when_navigation_away_from_puter',
]);
// Keys that must never leave the server, whoever put them on the response.
// `details` is an explicit pick, but the `whoami.details` event hands
// listeners the full UserRow next to the object they may write to, and
// `metadata` is a free-form blob — so any of these can arrive on the
// response without an edit to the pick above. The scrub runs last, over the
// whole payload, and is the one place that decides what "sensitive" means.
//
// Credentials and single-use tokens, the payment/phone identifiers used for
// verification (`card_fingerprint` is the Stripe fingerprint, stable per
// card number), the network identity recorded at signup, and internal
// anti-abuse bookkeeping. `requires_phone_verification` /
// `requires_card_verification` stay: they are the flags the GUI acts on, and
// they carry no identifier.
const SENSITIVE_KEYS: ReadonlySet<string> = new Set([
'password',
'tmp_password',
'pass_recovery_token',
'email_confirm_code',
'email_confirm_token',
'change_email_confirm_token',
'otp_secret',
'otp_recovery_codes',
'card_fingerprint',
'phone',
'clean_email',
'signup_ip',
'signup_ip_forwarded',
'signup_user_agent',
'signup_origin',
'signup_server',
'audit_metadata',
]);
// Depth-limited, cycle-safe walk deleting every SENSITIVE_KEYS entry it finds
// at any level (`metadata` and `taskbar_items` are both nested structures).
const scrubSensitive = (
value: unknown,
seen: Set<object> = new Set(),
depth = 0,
): void => {
if (depth > 8 || value === null || typeof value !== 'object') return;
if (seen.has(value as object)) return;
seen.add(value as object);
if (Array.isArray(value)) {
for (const entry of value) scrubSensitive(entry, seen, depth + 1);
return;
}
for (const key of Object.keys(value as Record<string, unknown>)) {
if (SENSITIVE_KEYS.has(key)) {
delete (value as Record<string, unknown>)[key];
continue;
}
scrubSensitive(
(value as Record<string, unknown>)[key],
seen,
depth + 1,
);
}
};
export const handleWhoami = async (
req: Request,
res: Response,
@@ -65,8 +136,12 @@ export const handleWhoami = async (
}
}
const metadata = user.metadata ? { ...user.metadata } : user.metadata;
if (metadata) delete metadata.tmp_password;
// Deep-copied (it is decoded JSON) so the scrub below edits the response
// and not the cached UserRow. Sensitive keys inside it — tmp_password and
// anything else on the denylist — are removed by scrubSensitive.
const metadata = user.metadata
? structuredClone(user.metadata)
: user.metadata;
const details: Record<string, unknown> = {
username: user.username,
@@ -75,7 +150,9 @@ export const handleWhoami = async (
unconfirmed_email: user.email,
email_confirmed: user.email_confirmed || user.username === 'admin',
requires_email_confirmation: user.requires_email_confirmation,
phone: user.phone,
// The phone number itself is deliberately absent: nothing on the
// client reads it, and it is PII that would otherwise be handed to
// every app actor. Only the verification flag ships.
requires_phone_verification: user.requires_phone_verification,
requires_card_verification: user.requires_card_verification,
desktop_bg_url: user.desktop_bg_url,
@@ -83,6 +160,10 @@ export const handleWhoami = async (
desktop_bg_fit: user.desktop_bg_fit,
is_temp: user.password === null && user.email === null,
is_user_token: true,
// Present only once the account has actually asked for a code (see the
// referral extension) — null until then, and never minted from here:
// this endpoint is polled, and a mint is a write.
referral_code: user.referral_code,
oidc_only: oidcOnly,
taskbar_items: isUser
? await getTaskbarItems(
@@ -98,6 +179,7 @@ export const handleWhoami = async (
: undefined,
otp: !!user.otp_enabled,
feature_flags,
created_ts: toUnixSeconds(user.timestamp),
human_readable_age: user.timestamp
? timeago.format(new Date(user.timestamp as string))
: null,
@@ -141,14 +223,9 @@ export const handleWhoami = async (
}
// Last activity
if (user.last_activity_ts) {
try {
details.last_activity_ts = Math.round(
new Date(user.last_activity_ts as string).getTime() / 1000,
);
} catch {
/* ignore parse error */
}
const lastActivityTs = toUnixSeconds(user.last_activity_ts);
if (lastActivityTs !== undefined) {
details.last_activity_ts = lastActivityTs;
}
// Strip sensitive fields for app actors
@@ -164,8 +241,11 @@ export const handleWhoami = async (
delete details.desktop_bg_color;
delete details.desktop_bg_fit;
delete details.human_readable_age;
delete details.created_ts;
delete details.is_user_token;
delete details.metadata;
// An app has no business reading the code its user earns credit with.
delete details.referral_code;
}
if (actor.app) {
@@ -183,19 +263,38 @@ export const handleWhoami = async (
}
const subscription = details.subscription as
| { offering?: Record<string, unknown> }
| undefined;
{ offering?: Record<string, unknown> } | undefined;
if (subscription?.offering) {
delete subscription.offering.group;
delete subscription.offering.benefits;
delete subscription.offering.price_id;
}
// Last word on what ships, after every listener has had its say.
scrubSensitive(details);
res.json(details);
};
extension.get(
'/whoami',
{ subdomain: 'api', requireAuth: true, allowUnconfirmed: true },
{
subdomain: 'api',
requireAuth: true,
allowUnconfirmed: true,
// The GUI polls this, and each call fans out to every `whoami`
// event listener — so it costs more than the response suggests.
//
// It is also the call everything else leans on to find out who it is
// talking to, so it rides along with unrelated work rather than
// arriving at its own pace: the ceiling has to clear whatever the
// busiest session is doing, not what a person clicks.
rateLimit: {
scope: 'whoami',
limit: 1_800,
window: 60_000,
key: 'user',
},
},
handleWhoami,
);
+15 -12
View File
@@ -11,7 +11,7 @@
# What this does, in order:
# 1. Checks that docker (with the compose plugin) exists.
# 2. Creates ./puter-selfhosted/ (override with $env:PUTER_DIR).
# 3. Downloads docker-compose.yml + nginx.conf from the OSS repo.
# 3. Downloads docker-compose.yml + caddy/Caddyfile from the OSS repo.
# 4. Generates fresh secrets and writes .env + puter/config/config.json.
# 5. Runs `docker compose up -d` and prints how to find the admin password.
#
@@ -23,7 +23,7 @@
# PUTER_DIR install directory (default: ./puter-selfhosted)
# PUTER_URL base URL to fetch docker-compose.yml (default: GitHub raw, main branch)
# PUTER_DOMAIN domain Puter will serve on (default: puter.localhost)
# PUTER_PORT HTTP port for nginx (default: 80)
# PUTER_PORT HTTP port for Caddy (default: 80)
# PUTER_FORCE set to 1 to overwrite existing .env / config.json
[CmdletBinding()]
@@ -77,10 +77,10 @@ if ($LASTEXITCODE -ne 0) {
# ── Step 2: install dir ─────────────────────────────────────────────
$null = New-Item -ItemType Directory -Force -Path $PuterDir
Set-Location $PuterDir
$null = New-Item -ItemType Directory -Force -Path 'puter/config', 'puter/data', 'puter/tls'
$null = New-Item -ItemType Directory -Force -Path 'puter/config', 'puter/data', 'puter/data/caddy', 'puter/tls'
Write-Log "install dir: $((Get-Location).Path)"
# ── Step 3: docker-compose.yml + nginx config ──────────────────────
# ── Step 3: docker-compose.yml + Caddy config ──────────────────────
Write-Log "downloading docker-compose.yml from $PuterUrl"
try {
Invoke-WebRequest -Uri "$PuterUrl/docker-compose.yml" -OutFile 'docker-compose.yml' -UseBasicParsing
@@ -88,17 +88,19 @@ try {
Die "could not fetch $PuterUrl/docker-compose.yml — $_"
}
Write-Log "downloading nginx/nginx.conf from $PuterUrl"
$null = New-Item -ItemType Directory -Force -Path 'nginx'
# The Caddyfile is domain-agnostic — it answers on every Host and leaves
# the subdomain routing to Puter — so there's nothing to template in.
Write-Log "downloading caddy/Caddyfile from $PuterUrl"
$null = New-Item -ItemType Directory -Force -Path 'caddy'
# If the path was previously auto-created as a directory by a failed
# `compose up`, remove it so we can write the file there.
if (Test-Path 'nginx/nginx.conf' -PathType Container) {
Remove-Item 'nginx/nginx.conf' -Recurse -Force
if (Test-Path 'caddy/Caddyfile' -PathType Container) {
Remove-Item 'caddy/Caddyfile' -Recurse -Force
}
try {
Invoke-WebRequest -Uri "$PuterUrl/nginx/nginx.conf" -OutFile 'nginx/nginx.conf' -UseBasicParsing
Invoke-WebRequest -Uri "$PuterUrl/caddy/Caddyfile" -OutFile 'caddy/Caddyfile' -UseBasicParsing
} catch {
Die "could not fetch $PuterUrl/nginx/nginx.conf — $_"
Die "could not fetch $PuterUrl/caddy/Caddyfile — $_"
}
# ── Step 4: secrets, .env, config.json ──────────────────────────────
@@ -121,7 +123,8 @@ if ($writeConfig) {
$envContent = @"
HTTP_PORT=$PuterPort
# HTTPS_PORT=443 # uncomment after enabling TLS (see doc/selfhosting/full-stack.md)
# HTTPS_PORT=443 # uncomment after enabling TLS in caddy/Caddyfile
# # (see "Step 3 — TLS" in doc/self-hosting.md)
MARIADB_ROOT_PASSWORD=$mariadbRootPw
MARIADB_DATABASE=puter
@@ -205,4 +208,4 @@ Write-Log " cd $PuterDir; docker compose logs -f puter"
Write-Log ''
Write-Log "open http://${PuterDomain}:${PuterPort} once the puter container is healthy."
Write-Log 'first-boot admin password is logged once — grab it with:'
Write-Log " cd $PuterDir; docker compose logs puter | Select-String password"
Write-Log " cd $PuterDir; docker compose logs puter | Select-String password"
+45 -18
View File
@@ -7,7 +7,8 @@
# What this does, in order:
# 1. Checks that docker (with the compose plugin), curl, and openssl exist.
# 2. Creates ./puter-selfhosted/ (override with PUTER_DIR=...).
# 3. Downloads docker-compose.yml from the OSS repo (raw.githubusercontent.com).
# 3. Downloads docker-compose.yml + caddy/Caddyfile from the OSS repo
# (raw.githubusercontent.com).
# 4. Generates fresh secrets and writes .env + puter/config/config.json.
# 5. Runs `docker compose up -d` and prints the first-boot admin password.
#
@@ -19,15 +20,17 @@
# PUTER_DIR install directory (default: ./puter-selfhosted)
# PUTER_URL base URL to fetch docker-compose.yml (default: GitHub raw, main branch)
# PUTER_DOMAIN domain Puter will serve on (default: puter.localhost)
# PUTER_PORT HTTP port for nginx (default: 80)
# PUTER_PORT HTTP port for Caddy (default: 80)
# PUTER_PROTOCOL public scheme: http | https (default: http)
# Set https when a TLS-terminating reverse proxy (Caddy,
# Traefik, nginx, a cloud LB) sits in front — Puter then
# builds https:// origins, S3 URLs, and redirects. See
# "Running behind your own reverse proxy" in doc/self-hosting.md.
# Set https once TLS is terminating in front of Puter —
# either the bundled Caddy with your certs (see "Step 3 —
# TLS" in doc/self-hosting.md) or your own proxy (Traefik,
# a cloud LB). Puter then builds https:// origins, S3
# URLs, and redirects. Leave it http and the installer
# serves plain HTTP on PUTER_PORT.
# PUTER_TRUST_PROXY number of reverse-proxy hops in front (default: 1)
# 1 = the bundled nginx (or a single external proxy);
# 2 = two hops (e.g. Cloudflare → your proxy → Puter).
# 1 = the bundled Caddy (or a single external proxy);
# 2 = two hops (e.g. Cloudflare → Caddy → Puter).
# PUTER_ENV prod | dev (default: prod)
# PUTER_FORCE set to 1 to overwrite existing .env / config.json
@@ -72,25 +75,27 @@ mkdir -p puter/config puter/data puter/tls
# bind-mount roots sidesteps the mismatch without guessing each image's
# internal UID. (Docker Desktop on macOS/Windows papers over this with
# its VM layer; native Linux docker on Debian/Alpine doesn't.)
mkdir -p puter/data/valkey puter/data/mariadb puter/data/dynamo puter/data/s3 puter/data/puter
chmod 0777 puter/data/valkey puter/data/mariadb puter/data/dynamo puter/data/s3 puter/data/puter
mkdir -p puter/data/valkey puter/data/mariadb puter/data/dynamo puter/data/s3 puter/data/puter puter/data/caddy
chmod 0777 puter/data/valkey puter/data/mariadb puter/data/dynamo puter/data/s3 puter/data/puter puter/data/caddy
log "install dir: $(pwd)"
# ── Step 3: docker-compose.yml + nginx config ──────────────────────
# ── Step 3: docker-compose.yml + Caddy config ──────────────────────
log "downloading docker-compose.yml from $PUTER_URL"
curl -fsSL "$PUTER_URL/docker-compose.yml" -o docker-compose.yml \
|| die "could not fetch $PUTER_URL/docker-compose.yml"
# nginx is mounted as `./nginx/nginx.conf:/etc/nginx/nginx.conf:ro` — if
# Caddy is mounted as `./caddy/Caddyfile:/etc/caddy/Caddyfile:ro,z` — if
# the host file is missing, docker silently creates a directory at that
# path and the mount fails with "not a directory" at container start.
log "downloading nginx/nginx.conf from $PUTER_URL"
mkdir -p nginx
# The Caddyfile is domain-agnostic — it answers on every Host and leaves
# the subdomain routing to Puter — so there's nothing to template in.
log "downloading caddy/Caddyfile from $PUTER_URL"
mkdir -p caddy
# If the path was previously auto-created as a dir by a failed `compose up`,
# remove it so curl can write the file.
[ -d nginx/nginx.conf ] && rmdir nginx/nginx.conf 2>/dev/null || true
curl -fsSL "$PUTER_URL/nginx/nginx.conf" -o nginx/nginx.conf \
|| die "could not fetch $PUTER_URL/nginx/nginx.conf"
[ -d caddy/Caddyfile ] && rmdir caddy/Caddyfile 2>/dev/null || true
curl -fsSL "$PUTER_URL/caddy/Caddyfile" -o caddy/Caddyfile \
|| die "could not fetch $PUTER_URL/caddy/Caddyfile"
# ── Step 4: secrets, .env, config.json ──────────────────────────────
write_config=1
@@ -113,7 +118,8 @@ if [ "$write_config" = "1" ]; then
cat > .env <<EOF
HTTP_PORT=$PUTER_PORT
# HTTPS_PORT=443 # uncomment after enabling TLS (see doc/selfhosting/full-stack.md)
# HTTPS_PORT=443 # uncomment after enabling TLS in caddy/Caddyfile
# # (see "Step 3 — TLS" in doc/self-hosting.md)
MARIADB_ROOT_PASSWORD=$MARIADB_ROOT_PASSWORD
MARIADB_DATABASE=puter
@@ -125,6 +131,11 @@ S3_SECRET_KEY=$S3_SECRET_KEY
S3_BUCKET=puter-local
EOF
# `meteringEnforcement.subscriptions` is off here because a self-hosted
# install has no paid plans to be on: every account resolves to the free
# policy, so leaving the plan gates armed would 402 the surfaces that
# declare one (the OpenAI/Anthropic-compatible AI endpoints) for everybody.
# The code default is on — this is a property of the install, not of Puter.
log "writing puter/config/config.json"
cat > puter/config/config.json <<EOF
{
@@ -185,11 +196,27 @@ EOF
"ollama": { "enabled": false }
},
"meteringEnforcement": {
"subscriptions": false
},
"trust_proxy": $PUTER_TRUST_PROXY
}
EOF
fi
# `https` only works if something in front is actually terminating it. The
# bundled Caddy does that from ./puter/tls once you enable its `:443` block
# (see "Step 3 — TLS" in doc/self-hosting.md); your own edge proxy is fine
# too. Neither in place means Puter hands out https:// URLs for an endpoint
# that only speaks HTTP — broken logins and mixed content.
if [ "$PUTER_PROTOCOL" = "https" ] && [ ! -f puter/tls/fullchain.pem ]; then
warn "PUTER_PROTOCOL=https but ./puter/tls/fullchain.pem is missing."
warn "The bundled Caddy is still serving plain HTTP on port $PUTER_PORT."
warn "Either drop a wildcard cert into ./puter/tls and uncomment the :443"
warn "block in caddy/Caddyfile, or terminate TLS in your own proxy."
fi
# ── Step 5: bring it up ─────────────────────────────────────────────
log "docker compose up -d"
docker compose up -d
-135
View File
@@ -1,135 +0,0 @@
# Reverse proxy in front of Puter — mirrors what the prod ALB does:
# accepts every Host header, forwards to the Puter container, and lets
# the Puter app handle subdomain-based routing internally (api.*,
# site.*, app.*, etc).
#
# To enable TLS:
# 1. Drop your fullchain.pem + privkey.pem into ./puter/tls/.
# 2. Uncomment the 443 server{} block below.
# 3. Update server_name to your domain (and wildcard subdomains).
worker_processes auto;
events {
worker_connections 4096;
}
http {
# Required for Puter's WebSocket / socket.io upgrades.
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
# Rough size cap that mirrors prod ALB defaults; tune for your
# uploads. Puter chunks large uploads, so 1 GiB per request is plenty.
client_max_body_size 1024m;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_buffering off;
server_tokens off;
upstream puter_backend {
server puter:4100;
keepalive 32;
}
upstream s3_backend {
# RustFS — see `s3` service in docker-compose.full.yml. Browsers
# PUT/GET here for presigned-URL uploads / downloads. Routed via
# the `s3.<domain>` subdomain so signature verification works
# (Host header preserved end-to-end) and so HTTPS stays clean
# (no mixed-content from a port-9000 host publish).
server s3:9000;
keepalive 32;
}
# ── HTTP (port 80) ─────────────────────────────────────────────
server {
listen 80;
listen [::]:80;
server_name ~^s3\.;
location / {
proxy_pass http://s3_backend;
proxy_http_version 1.1;
# Critical: preserve the original Host so RustFS validates
# the request against the same host the URL was signed for.
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
# Note: when you enable TLS, replace this block with a redirect:
# return 301 https://$host$request_uri;
location / {
proxy_pass http://puter_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
# ── HTTPS (port 443) — uncomment after dropping certs in ./puter/tls/ ─
# server {
# listen 443 ssl;
# listen [::]:443 ssl;
# http2 on;
# server_name ~^s3\.;
#
# ssl_certificate /etc/nginx/tls/fullchain.pem;
# ssl_certificate_key /etc/nginx/tls/privkey.pem;
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_session_cache shared:SSL:10m;
# ssl_session_timeout 10m;
#
# location / {
# proxy_pass http://s3_backend;
# proxy_http_version 1.1;
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# }
# }
#
# server {
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
# http2 on;
# server_name _;
#
# ssl_certificate /etc/nginx/tls/fullchain.pem;
# ssl_certificate_key /etc/nginx/tls/privkey.pem;
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_session_cache shared:SSL:10m;
# ssl_session_timeout 10m;
#
# location / {
# proxy_pass http://puter_backend;
# proxy_http_version 1.1;
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# proxy_set_header X-Forwarded-Host $host;
# proxy_set_header X-Forwarded-Port $server_port;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection $connection_upgrade;
# }
# }
}
+2106 -3713
View File
File diff suppressed because it is too large. Load diff
+20 -29
View File
@@ -13,14 +13,9 @@
"@babel/core": "^7.29.7",
"@eslint/js": "^9.35.0",
"@playwright/test": "^1.56.1",
"@stylistic/eslint-plugin": "^5.3.1",
"@types/better-sqlite3": "^7.6.13",
"@types/express": "^5.0.0",
"@types/mime-types": "^3.0.1",
"@typescript-eslint/eslint-plugin": "^8.46.1",
"@typescript-eslint/parser": "^8.46.1",
"@vitest/coverage-v8": "^4.0.14",
"@vitest/ui": "^4.0.14",
"babel-loader": "^10.1.1",
"babel-plugin-istanbul": "^8.0.0",
"chalk": "^4.1.0",
@@ -30,29 +25,23 @@
"eslint": "^9.35.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"eslint-rule-composer": "^0.3.0",
"globals": "^15.15.0",
"html-webpack-plugin": "^5.6.0",
"husky": "^9.1.7",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"license-check-and-add": "^4.0.5",
"nodemon": "^3.1.0",
"prettier": "^3.8.3",
"prettier-plugin-jsdoc": "^1.8.1",
"simple-git": "^3.32.3",
"typescript": "^5.4.5",
"uglify-js": "^3.17.4",
"vite-plugin-static-copy": "^3.3.0",
"vitest": "^4.1.5",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.1",
"yaml": "^2.8.1"
"webpack-cli": "^5.1.1"
},
"scripts": {
"test:backend": "npm run setupExtensions && vitest run --config src/backend/vitest.config.ts ",
"test:backend:postgres": "npm run setupExtensions && PUTER_TEST_DB_ENGINE=postgres vitest run --config src/backend/vitest.config.ts ",
"test:backend": "npm run setupExtensions && npm run build:workerLib && vitest run --config src/backend/vitest.config.ts ",
"test:backend:postgres": "npm run setupExtensions && npm run build:workerLib && PUTER_TEST_DB_ENGINE=postgres vitest run --config src/backend/vitest.config.ts ",
"test:puterjs": "npm run setupExtensions && vitest run --config src/puter-js/tests/api/vitest.config.ts",
"test:puterjs:node": "npm run test:puterjs -- src/puter-js/tests/api/runners/node.test.ts",
"test:puterjs:browser": "npm run test:puterjs -- src/puter-js/tests/api/runners/browser.test.ts",
@@ -60,20 +49,20 @@
"test:puterjs:coverage": "npm run build:workerLib:coverage && npm run setupExtensions && rm -rf src/puter-js/coverage && PUTER_COVERAGE=1 vitest run --config src/puter-js/tests/api/vitest.config.ts && node ./tools/puterjsCoverageReport.mjs",
"build:workerLib:coverage": "cd src/puter-js && npm run build:coverage && cd ../worker && npm run build",
"start:gui": "nodemon --exec \"node dev-server.js\" ",
"start": "node --enable-source-maps -r ./dist/src/backend/telemetry.js ./dist/src/backend/index.js",
"prestart": "npm run setupExtensions && npm run build:ts",
"start": "node ./tools/start.mjs",
"dev": "npm start",
"build": "npm run setupExtensions && npm run build:ts && cd src/gui && node ./build.js && cd ../puter-js && npm run build",
"build:workerLib": "cd src/puter-js && npm run build && cd ../worker && npm run build",
"check-translations": "node tools/check-translations.js",
"prepare": "husky",
"build:ts": "tsc -p tsconfig.build.json && node ./tools/write-dist-package-json.mjs",
"check:puterjs:types": "node tools/checkPuterjsTypes.mjs",
"typecheck": "node tools/typecheck.mjs",
"typecheck:update": "node tools/typecheck.mjs --update",
"setupExtensions": "node ./tools/extensionSetup.mjs"
},
"workspaces": [
"src/*",
"tools/*",
"experiments/js-parse-and-output"
"src/*"
],
"nodemonConfig": {
"ext": "js, json, mjs, jsx, svg, css",
@@ -83,11 +72,8 @@
]
},
"dependencies": {
"@ai-sdk/openai": "^3.0.25",
"@aws-sdk/client-s3": "^3.1020.0",
"@aws-sdk/s3-request-presigner": "^3.1028.0",
"@heyputer/putility": "^1.0.2",
"ai": "^6.0.73",
"dedent": "^1.5.3",
"javascript-time-ago": "^2.5.11",
"libphonenumber-js": "1.13.6",
@@ -99,12 +85,17 @@
},
"allowScripts": {
"@google/genai": false,
"bcrypt@5.1.1": true,
"better-sqlite3@12.11.1": true,
"browser-tabs-lock@1.3.0": true,
"classic-level@3.0.0": true,
"[email protected]": true,
"[email protected]": true,
"[email protected]": true
"bcrypt": true,
"better-sqlite3": true,
"browser-tabs-lock": true,
"classic-level": true,
"esbuild": true,
"fsevents": true,
"protobufjs": true,
"sharp": true,
"workerd": true
},
"overrides": {
"undici": "^7.29.0"
}
}
@@ -0,0 +1,521 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AlarmClient } from './AlarmClient';
import type { IConfig, IPagerConfig } from '../../types';
import type { AlertPayload } from './types';
const pdEvent = vi.hoisted(() => vi.fn(async () => ({})));
vi.mock('@pagerduty/pdjs', () => ({ event: pdEvent }));
const makeClient = (pager: IPagerConfig = {}) =>
new AlarmClient({ serverId: 'test-node', pager } as unknown as IConfig);
/** Register a capturing handler in place of a real transport. */
const capture = (
client: AlarmClient,
minSeverity?: 'critical' | 'error' | 'warning' | 'info',
maxSeverity?: 'critical' | 'error' | 'warning' | 'info',
) => {
const seen: AlertPayload[] = [];
client.addAlertHandler(
async (alert) => {
seen.push(alert);
},
{ name: 'capture', minSeverity, maxSeverity },
);
return seen;
};
describe('AlarmClient severity routing', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
pdEvent.mockClear();
});
it('defaults to critical when the call site says nothing', () => {
const client = makeClient();
const seen = capture(client);
client.create('boom', 'everything is on fire');
expect(seen).toHaveLength(1);
expect(seen[0].severity).toBe('critical');
});
it('honours a configured default severity', () => {
const client = makeClient({ defaultSeverity: 'info' });
const seen = capture(client);
client.create('boom', 'everything is on fire');
expect(seen[0].severity).toBe('info');
});
it('skips handlers whose floor the alarm does not reach', () => {
const client = makeClient();
const paging = capture(client, 'warning');
const chat = capture(client, 'info');
client.create('rate-limit', 'a user hit a limit', {}, 'info');
expect(paging).toHaveLength(0);
expect(chat).toHaveLength(1);
});
it('skips handlers whose ceiling the alarm exceeds', () => {
const client = makeClient();
const chat = capture(client, 'info', 'info');
client.create('rate-limit', 'a user hit a limit', {}, 'info');
client.create('outage', 'everything is on fire', {}, 'critical');
expect(chat.map((alert) => alert.id)).toEqual(['rate-limit']);
});
it('retiers an alarm from config', () => {
const client = makeClient({
severityOverrides: { 'noisy:*': 'info' },
});
const paging = capture(client, 'warning');
const chat = capture(client, 'info');
client.create('noisy:thing', 'used to page', {}, 'critical');
expect(paging).toHaveLength(0);
expect(chat[0].severity).toBe('info');
});
it('mutes an alarm from config', () => {
const client = makeClient({
severityOverrides: { 'noisy:thing': 'mute' },
});
const chat = capture(client, 'info');
client.create('noisy:thing', 'not worth reporting');
client.create('noisy:thing', 'still not worth reporting');
expect(chat).toHaveLength(0);
});
it('lets config override a known-error rule', () => {
const client = makeClient({
severityOverrides: { 'known:thing': 'critical' },
});
client.setKnownErrors([
{
match: { id: 'known:thing' },
action: { type: 'severity', value: 'info' },
},
]);
const paging = capture(client, 'warning');
client.create('known:thing', 'known but escalated');
expect(paging[0].severity).toBe('critical');
});
it('still respects a no-alert known-error rule', () => {
const client = makeClient();
client.setKnownErrors([
{ match: { id: 'known:quiet' }, action: { type: 'no-alert' } },
]);
const chat = capture(client, 'info');
client.create('known:quiet', 'suppressed');
expect(chat).toHaveLength(0);
});
});
describe('AlarmClient alert payload', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
it('reports occurrence counts across repeats', () => {
const client = makeClient();
const seen = capture(client);
client.create('flap', 'first');
client.create('flap', 'second');
expect(seen[0]).toMatchObject({ repeatCount: 1, isRepeat: false });
expect(seen[1]).toMatchObject({ repeatCount: 2, isRepeat: true });
});
it('renders fields as strings and lifts the stack out of the error', () => {
const client = makeClient();
const seen = capture(client);
const error = new Error('kaboom');
client.create('boom', 'failed', { error, status: 500 }, 'critical');
expect(seen[0].fields.status).toBe('500');
expect(seen[0].trace).toBe(error.stack);
expect(seen[0].shortId).toMatch(/^[a-z]+-[a-z]+-[a-z]+$/);
});
it('keeps one failing handler from starving the others', async () => {
const client = makeClient();
client.addAlertHandler(
async () => {
throw new Error('transport down');
},
{ name: 'broken' },
);
const seen = capture(client);
client.create('boom', 'failed');
await Promise.resolve();
expect(seen).toHaveLength(1);
});
it('suppresses alarms once draining', () => {
const client = makeClient();
const seen = capture(client);
client.onServerPrepareShutdown();
client.create('boom', 'too late');
expect(seen).toHaveLength(0);
});
});
describe('AlarmClient transport registration', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
pdEvent.mockClear();
});
it('splits info to Slack and everything above it to PagerDuty', async () => {
const fetchMock = vi.fn(async () => ({ ok: true, status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const client = makeClient({
pagerduty: { enabled: true, routingKey: 'rk' },
slack: { enabled: true, webhookUrl: 'https://hooks.example/abc' },
});
await client.onServerStart();
client.create('quiet:thing', 'informational', {}, 'info');
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
expect(pdEvent).not.toHaveBeenCalled();
client.create('loud:thing', 'paging', {}, 'critical');
await vi.waitFor(() => expect(pdEvent).toHaveBeenCalledTimes(1));
// The pager has it; chat doesn't repeat it.
expect(fetchMock).toHaveBeenCalledTimes(1);
vi.unstubAllGlobals();
});
it('sends every severity to Slack when there is no pager', async () => {
const fetchMock = vi.fn(async () => ({ ok: true, status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const client = makeClient({
slack: { enabled: true, webhookUrl: 'https://hooks.example/abc' },
});
await client.onServerStart();
client.create(
'loud:thing',
'nowhere else to send this',
{},
'critical',
);
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
vi.unstubAllGlobals();
});
it('lets config widen the Slack ceiling back out', async () => {
const fetchMock = vi.fn(async () => ({ ok: true, status: 200 }));
vi.stubGlobal('fetch', fetchMock);
const client = makeClient({
pagerduty: { enabled: true, routingKey: 'rk' },
slack: {
enabled: true,
webhookUrl: 'https://hooks.example/abc',
maxSeverity: 'critical',
},
});
await client.onServerStart();
client.create('loud:thing', 'paging', {}, 'critical');
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
vi.unstubAllGlobals();
});
it('gives each occurrence its own PagerDuty incident by default', async () => {
const client = makeClient({
pagerduty: { enabled: true, routingKey: 'rk' },
});
await client.onServerStart();
client.create('scan:failed', 'first', {}, 'warning');
client.create('scan:failed', 'second', {}, 'warning');
await vi.waitFor(() => expect(pdEvent).toHaveBeenCalledTimes(2));
const keys = pdEvent.mock.calls.map(
([arg]: [{ data: { dedup_key: string } }]) => arg.data.dedup_key,
);
expect(keys[0]).not.toBe(keys[1]);
});
it('collapses repeats of a dedup alarm onto one incident', async () => {
const client = makeClient({
pagerduty: { enabled: true, routingKey: 'rk' },
});
await client.onServerStart();
const raise = () =>
client.create(
'http_500:POST:/notif/mark-ack:deadlock',
'HTTP 500 on POST /notif/mark-ack: deadlock',
{},
'critical',
{ dedup: true },
);
raise();
raise();
await vi.waitFor(() => expect(pdEvent).toHaveBeenCalledTimes(2));
const keys = pdEvent.mock.calls.map(
([arg]: [{ data: { dedup_key: string } }]) => arg.data.dedup_key,
);
expect(keys[0]).toBe('http_500:POST:/notif/mark-ack:deadlock');
expect(keys[1]).toBe(keys[0]);
});
it('skips transports that are enabled but not configured', async () => {
const client = makeClient({
pagerduty: { enabled: true },
slack: { enabled: true },
});
await client.onServerStart();
const seen = capture(client);
client.create('boom', 'nowhere to send this');
// Only the capturing handler is registered.
expect(seen).toHaveLength(1);
expect(pdEvent).not.toHaveBeenCalled();
});
});
describe('AlarmClient alarm registry', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
});
it('finds an alarm by its full id or its short id', () => {
const client = makeClient();
client.create('disk-pressure', 'nearly full');
const alarm = client.get('disk-pressure');
expect(alarm?.message).toBe('nearly full');
expect(client.get(alarm!.shortId)).toBe(alarm);
});
it('returns nothing for an id it has never seen', () => {
expect(makeClient().get('never-raised')).toBeUndefined();
});
it('forgets an alarm once cleared, under both ids', () => {
const client = makeClient();
client.create('disk-pressure', 'nearly full');
const shortId = client.get('disk-pressure')!.shortId;
client.clear('disk-pressure');
expect(client.get('disk-pressure')).toBeUndefined();
expect(client.get(shortId)).toBeUndefined();
});
it('ignores a clear for an alarm that is not active', () => {
const client = makeClient();
expect(() => client.clear('never-raised')).not.toThrow();
});
it('abbreviates long ids in the log line but keeps the short id usable', () => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
const client = makeClient();
const longId = 'a-very-long-alarm-identifier-that-wraps';
client.create(longId, 'noisy');
const shortId = client.get(longId)!.shortId;
expect(log).toHaveBeenCalledWith(
`[alarm] ACTIVE ${shortId} (${longId.slice(0, 20)}...) :: noisy`,
);
});
it('accumulates fields across repeats of the same alarm', () => {
const client = makeClient();
const seen = capture(client);
client.create('flap', 'first', { a: 1 });
client.create('flap', 'second', { b: 2 });
expect(seen[1].fields).toEqual({ a: '1', b: '2' });
expect(client.get('flap')?.occurrences).toHaveLength(2);
});
it('caps retained occurrences while still counting every repeat', () => {
const client = makeClient();
const seen = capture(client);
for (let i = 0; i < 50; i++) {
client.create('hot', `occurrence ${i}`, { i });
}
const alarm = client.get('hot')!;
expect(alarm.count).toBe(50);
expect(alarm.occurrences).toHaveLength(20);
expect(alarm.timestamps).toHaveLength(20);
// The window kept is the most recent one, not the oldest.
expect(alarm.occurrences[19].message).toBe('occurrence 49');
// Trimming history must not rewind what the transports are told.
expect(seen[49]).toMatchObject({ repeatCount: 50, isRepeat: true });
});
it('names anonymous handlers by their registration order', () => {
const client = makeClient();
client.addAlertHandler(async () => {
throw new Error('down');
});
expect(() => client.create('boom', 'x')).not.toThrow();
});
it('only logs the drain notice once', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
log.mockClear();
const client = makeClient();
client.onServerPrepareShutdown();
// A second prepare must not restart the drain.
client.onServerPrepareShutdown();
client.create('a', 'x');
client.create('b', 'y');
const drainLogs = log.mock.calls.filter(
([message]) =>
message === '[alarm] suppressing alarm while draining',
);
expect(drainLogs).toHaveLength(1);
});
it('substitutes placeholders for an empty id and message', () => {
const client = makeClient();
const seen = capture(client);
client.create('', '');
expect(seen[0]).toMatchObject({
id: 'something-bad',
message: 'something bad happened',
});
});
});
describe('AlarmClient known-error rules', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
});
it('suppresses alerts for a matching rule', () => {
const client = makeClient();
const seen = capture(client);
client.setKnownErrors([
{ match: { id: 'noisy' }, action: { type: 'no-alert' } },
]);
client.create('noisy', 'ignore me');
client.create('noisy', 'ignore me again');
expect(seen).toHaveLength(0);
});
it('leaves alarms with a different id alone', () => {
const client = makeClient();
const seen = capture(client);
client.setKnownErrors([
{ match: { id: 'noisy' }, action: { type: 'no-alert' } },
]);
client.create('real', 'page me');
expect(seen).toHaveLength(1);
});
it('only matches when the message matches too', () => {
const rules = [
{
match: { id: 'timeout', message: 'upstream timed out' },
action: { type: 'no-alert' as const },
},
];
// Separate clients: suppression is recorded on the alarm, so a
// second occurrence of the same id would inherit it.
const matching = makeClient();
const matchingSeen = capture(matching);
matching.setKnownErrors(rules);
matching.create('timeout', 'upstream timed out');
expect(matchingSeen).toHaveLength(0);
const differing = makeClient();
const differingSeen = capture(differing);
differing.setKnownErrors(rules);
differing.create('timeout', 'something else entirely');
expect(differingSeen.map((alert) => alert.message)).toEqual([
'something else entirely',
]);
});
it('only matches when every named field matches', () => {
const client = makeClient();
const seen = capture(client);
client.setKnownErrors([
{
match: { id: 'http', fields: { status: 404 } },
action: { type: 'no-alert' },
},
]);
client.create('http', 'not found', { status: 404 });
client.create('http-2', 'server error', { status: 500 });
expect(seen.map((alert) => alert.id)).toEqual(['http-2']);
});
it('retiers a matching alarm to a lower severity', () => {
const client = makeClient();
const paging = capture(client, 'error');
const chat = capture(client, 'info');
client.setKnownErrors([
{
match: { id: 'flaky' },
action: { type: 'severity', value: 'info' },
},
]);
client.create('flaky', 'transient', {}, 'critical');
expect(paging).toHaveLength(0);
expect(chat).toHaveLength(1);
expect(chat[0].severity).toBe('info');
});
});
+243 -112
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -20,64 +20,65 @@
import { event as pdEvent } from '@pagerduty/pdjs';
import { inspect } from 'node:util';
import { createHash } from 'node:crypto';
import type { IConfig } from '../../types';
import type { IConfig, PagerSeverity, SeverityRule } from '../../types';
import { PuterClient } from '../types';
import {
meetsMinSeverity,
resolveSeverityOverride,
withinMaxSeverity,
} from './severity';
import { createSlackAlertHandler } from './slack';
import type {
Alarm,
AlarmFields,
AlarmOptions,
AlertHandler,
AlertPayload,
KnownErrorRule,
} from './types';
export type {
Alarm,
AlarmFields,
AlarmOptions,
AlertHandler,
AlertPayload,
KnownErrorRule,
} from './types';
export type { PagerSeverity } from '../../types';
// -- Types ------------------------------------------------------------
export interface AlarmFields {
error?: Error;
[key: string]: unknown;
interface RegisteredHandler {
name: string;
/** Lowest severity this transport accepts. */
minSeverity: PagerSeverity;
/** Highest severity this transport accepts. */
maxSeverity: PagerSeverity;
handler: AlertHandler;
}
interface AlarmOccurrence {
message: string;
fields: AlarmFields;
timestamp: number;
}
interface Alarm {
id: string;
shortId: string;
message: string;
fields: AlarmFields;
error?: Error;
started: number;
timestamps: number[];
occurrences: AlarmOccurrence[];
severity?: PagerSeverity;
noAlert?: boolean;
}
export type PagerSeverity = 'critical' | 'error' | 'warning' | 'info';
export interface AlertPayload {
id: string;
message: string;
source: string;
severity: PagerSeverity;
custom?: Record<string, unknown>;
}
type AlertHandler = (alert: AlertPayload) => Promise<void>;
interface KnownErrorRule {
match: {
id: string;
message?: string;
fields?: Record<string, unknown>;
};
action: {
type: 'no-alert' | 'severity';
value?: PagerSeverity;
};
}
/** Severity used when neither the call site nor config picks one. */
const FALLBACK_SEVERITY: PagerSeverity = 'critical';
/**
* How many recent occurrences an alarm keeps. An alarm is never cleared unless
* something calls `clear`, and a hot one repeats for as long as the fault lasts
* — so retaining every occurrence means retaining every message and field set
* it was ever raised with, request bodies and actors included, for the life of
* the process. The last few are what a human reads; the rest is only a count,
* and `count` keeps that.
*/
const OCCURRENCE_HISTORY_LIMIT = 20;
/** Keeps `info` alarms out of the paging system unless config says otherwise. */
const DEFAULT_PAGERDUTY_MIN_SEVERITY: PagerSeverity = 'warning';
/** Slack's ceiling once a pager exists: chat gets what doesn't page. */
const DEFAULT_SLACK_MAX_SEVERITY_WITH_PAGER: PagerSeverity = 'info';
// -- Helpers ----------------------------------------------------------
/**
* Deterministic short identifier derived from an alarm ID.
* Produces a readable 3-word slug like "amber-delta-fox".
* Deterministic short identifier derived from an alarm ID. Produces a readable
* 3-word slug like "amber-delta-fox".
*/
const WORD_POOL = [
'alpha',
@@ -169,13 +170,17 @@ function cleanFields(fields: AlarmFields): Record<string, string> {
// -- AlarmClient ------------------------------------------------------
/**
* Manages system alarms and dispatches alerts to external paging
* services (PagerDuty, or any registered handler).
* Manages system alarms and routes them to alert transports by severity.
*
* Severity is the routing decision: each transport declares the severity window
* it accepts, so `critical` pages on-call while `info` only reaches the chat
* channel. Config can retier or mute any alarm id after the fact — see
* `pager.severityOverrides` in {@link IConfig}.
*/
export class AlarmClient extends PuterClient {
private alarms = new Map<string, Alarm>();
private aliases = new Map<string, Alarm>();
private alertHandlers: AlertHandler[] = [];
private alertHandlers: RegisteredHandler[] = [];
private knownErrors: KnownErrorRule[] = [];
private draining = false;
private drainLogged = false;
@@ -187,39 +192,8 @@ export class AlarmClient extends PuterClient {
// -- Lifecycle ----------------------------------------------------
override async onServerStart(): Promise<void> {
const pagerConf = this.config.pager;
if (!pagerConf?.pagerduty?.enabled) return;
const routingKey = pagerConf.pagerduty.routingKey;
if (!routingKey) {
console.warn(
'[alarm] PagerDuty enabled but no routingKey configured',
);
return;
}
const serverId = this.config.serverId;
this.alertHandlers.push(async (alert) => {
await pdEvent({
data: {
routing_key: routingKey,
event_action: 'trigger',
dedup_key: alert.id,
payload: {
summary: alert.message,
source: alert.source,
severity: alert.severity,
custom_details: {
...alert.custom,
server_id: serverId,
},
},
},
});
});
console.log('[alarm] PagerDuty handler registered');
const paging = this.registerPagerDuty();
this.registerSlack({ paging });
}
override onServerPrepareShutdown(): void {
@@ -228,22 +202,107 @@ export class AlarmClient extends PuterClient {
console.log('[alarm] entering drain mode — suppressing new alarms');
}
/** @returns Whether a working PagerDuty transport was registered. */
private registerPagerDuty(): boolean {
const pagerDutyConf = this.config.pager?.pagerduty;
if (!pagerDutyConf?.enabled) return false;
const routingKey = pagerDutyConf.routingKey;
if (!routingKey) {
console.warn(
'[alarm] PagerDuty enabled but no routingKey configured',
);
return false;
}
const serverId = this.config.serverId;
const minSeverity =
pagerDutyConf.minSeverity ?? DEFAULT_PAGERDUTY_MIN_SEVERITY;
this.addAlertHandler(
async (alert) => {
await pdEvent({
data: {
routing_key: routingKey,
event_action: 'trigger',
dedup_key: alert.dedupKey,
payload: {
summary: alert.message,
source: alert.source,
severity: alert.severity,
custom_details: {
...alert.custom,
server_id: serverId,
},
},
},
});
},
{ name: 'pagerduty', minSeverity },
);
console.log(
`[alarm] PagerDuty handler registered (min severity: ${minSeverity})`,
);
return true;
}
private registerSlack({ paging }: { paging: boolean }): void {
const slackConf = this.config.pager?.slack;
if (!slackConf?.enabled) return;
if (!slackConf.webhookUrl) {
console.warn('[alarm] Slack enabled but no webhookUrl configured');
return;
}
const minSeverity = slackConf.minSeverity ?? 'info';
// With a pager taking everything from `warning` up, chat is where the
// rest is recorded — reposting the paging tiers there only trains
// people to skim the channel. Without one, Slack is the only place an
// alarm can land, so it takes all of them.
const maxSeverity =
slackConf.maxSeverity ??
(paging ? DEFAULT_SLACK_MAX_SEVERITY_WITH_PAGER : 'critical');
this.addAlertHandler(
createSlackAlertHandler(slackConf, {
serverId: this.config.serverId,
}),
{ name: 'slack', minSeverity, maxSeverity },
);
console.log(
`[alarm] Slack handler registered (severity ${minSeverity}..${maxSeverity})`,
);
}
// -- Public API ---------------------------------------------------
/**
* Create or update an alarm. If the alarm ID already exists, the
* occurrence count is incremented and a repeat alert is dispatched.
* Create or update an alarm. If the alarm ID already exists, the occurrence
* count is incremented and a repeat alert is dispatched.
*
* `severity` is the PagerDuty severity for this alarm; omit for the
* default 'critical'. Use 'info' / 'warning' for expected-but-worth-
* tracking signals (e.g. a user hitting a rate limit) so they record
* and de-dupe like any other alarm but don't page on-call.
* `severity` decides where the alarm lands:
*
* Critical — a real outage; pages on-call. Reserve it for unhandled server
* errors. error — pages on-call as well; prefer `critical` or `warning`.
* warning — worth a look soon, but nobody gets woken up. info — a record in
* the chat channel; never pages.
*
* Omit it to take `pager.defaultSeverity` (itself defaulting to
* 'critical'). Operators can retier or mute any alarm id from config
* afterwards, so the value here is the starting point, not the last word.
*
* Pass `{ dedup: true }` when repeats of this id are one recurring fault
* that should collapse into a single incident — see {@link AlarmOptions}.
*/
create(
id: string,
message: string,
fields: AlarmFields = {},
severity?: PagerSeverity,
opts: AlarmOptions = {},
): void {
if (this.draining) {
if (!this.drainLogged) {
@@ -267,8 +326,12 @@ export class AlarmClient extends PuterClient {
message,
fields,
severity,
dedup: opts.dedup,
started: Date.now(),
timestamps: [Date.now()],
// `recordOccurrence` below stamps the first occurrence; seeding one
// here too would report every alarm as one occurrence ahead.
count: 0,
timestamps: [],
occurrences: [],
};
if (fields.error) alarm.error = fields.error;
@@ -295,16 +358,28 @@ export class AlarmClient extends PuterClient {
}
/**
* Register an additional alert handler. Handlers are called for
* every alarm that isn't suppressed by a known-error rule.
* Register an additional alert handler. Handlers are called for every alarm
* that isn't suppressed by a known-error rule or muted by config, and whose
* severity falls inside the handler's own `minSeverity`..`maxSeverity`
* window (default: everything).
*/
addAlertHandler(handler: AlertHandler): void {
this.alertHandlers.push(handler);
addAlertHandler(
handler: AlertHandler,
opts: {
name?: string;
minSeverity?: PagerSeverity;
maxSeverity?: PagerSeverity;
} = {},
): void {
this.alertHandlers.push({
name: opts.name ?? `handler-${this.alertHandlers.length}`,
minSeverity: opts.minSeverity ?? 'info',
maxSeverity: opts.maxSeverity ?? 'critical',
handler,
});
}
/**
* Add rules that can suppress or adjust severity of known errors.
*/
/** Add rules that can suppress or adjust severity of known errors. */
setKnownErrors(rules: KnownErrorRule[]): void {
this.knownErrors = rules;
}
@@ -316,16 +391,25 @@ export class AlarmClient extends PuterClient {
message: string,
fields: AlarmFields,
): void {
const now = Date.now();
alarm.message = message;
alarm.fields = { ...alarm.fields, ...fields };
alarm.timestamps.push(Date.now());
alarm.count++;
if (fields.error) alarm.error = fields.error;
alarm.occurrences.push({
message,
fields,
timestamp: Date.now(),
});
alarm.timestamps.push(now);
alarm.occurrences.push({ message, fields, timestamp: now });
if (alarm.timestamps.length > OCCURRENCE_HISTORY_LIMIT) {
alarm.timestamps.splice(
0,
alarm.timestamps.length - OCCURRENCE_HISTORY_LIMIT,
);
alarm.occurrences.splice(
0,
alarm.occurrences.length - OCCURRENCE_HISTORY_LIMIT,
);
}
}
private applyKnownErrors(alarm: Alarm): void {
@@ -373,7 +457,7 @@ export class AlarmClient extends PuterClient {
this.applyKnownErrors(alarm);
console.warn(
`[alarm] REPEAT ${displayId(alarm)} :: ${alarm.message} (${alarm.timestamps.length})`,
`[alarm] REPEAT ${displayId(alarm)} :: ${alarm.message} (${alarm.count})`,
);
if (alarm.noAlert) return;
@@ -381,25 +465,72 @@ export class AlarmClient extends PuterClient {
this.dispatchAlert(alarm);
}
/**
* Call-site severity, then any known-error rule (both already on the
* alarm), then the config override — so an operator always has the last
* word over what the code asked for.
*/
private resolveSeverity(alarm: Alarm): SeverityRule {
const base =
alarm.severity ??
this.config.pager?.defaultSeverity ??
FALLBACK_SEVERITY;
return (
resolveSeverityOverride(
alarm.id,
this.config.pager?.severityOverrides,
) ?? base
);
}
private dispatchAlert(alarm: Alarm): void {
const severity = alarm.severity ?? 'critical';
const resolved = this.resolveSeverity(alarm);
if (resolved === 'mute') {
if (!alarm.muteLogged) {
alarm.muteLogged = true;
console.log(`[alarm] MUTED by config ${displayId(alarm)}`);
}
return;
}
alarm.severity = resolved;
const fieldsClean = cleanFields(alarm.fields);
const repeatCount = alarm.count;
const id = alarm.id || 'something-bad';
const payload: AlertPayload = {
id: alarm.id || 'something-bad',
id,
// A de-duplicating transport should fold repeats of a recurring
// fault into one incident, but everything else is a fresh event
// each time it fires — the start time keeps occurrence numbering
// from colliding with an incident left open by an earlier boot.
dedupKey: alarm.dedup
? id
: `${id}#${alarm.started}.${repeatCount}`,
shortId: alarm.shortId,
message: alarm.message || alarm.id || 'something bad happened',
source: 'alarm',
severity,
severity: resolved,
fields: fieldsClean,
trace: alarm.error?.stack,
repeatCount,
isRepeat: repeatCount > 1,
custom: {
fields: fieldsClean,
trace: alarm.error?.stack,
repeat_count: alarm.timestamps.length,
repeat_count: repeatCount,
},
};
for (const handler of this.alertHandlers) {
for (const { name, minSeverity, maxSeverity, handler } of this
.alertHandlers) {
if (!meetsMinSeverity(resolved, minSeverity)) continue;
if (!withinMaxSeverity(resolved, maxSeverity)) continue;
handler(payload).catch((err) => {
console.error(`[alarm] alert handler failed: ${err?.message}`);
console.error(
`[alarm] ${name} alert handler failed: ${err?.message}`,
);
});
}
}
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { meetsMinSeverity, resolveSeverityOverride } from './severity';
describe('meetsMinSeverity', () => {
it('accepts everything at or above the floor', () => {
expect(meetsMinSeverity('critical', 'warning')).toBe(true);
expect(meetsMinSeverity('error', 'warning')).toBe(true);
expect(meetsMinSeverity('warning', 'warning')).toBe(true);
expect(meetsMinSeverity('info', 'warning')).toBe(false);
});
it('lets an info floor take every severity', () => {
for (const severity of [
'critical',
'error',
'warning',
'info',
] as const) {
expect(meetsMinSeverity(severity, 'info')).toBe(true);
}
});
});
describe('resolveSeverityOverride', () => {
it('returns undefined without overrides or on no match', () => {
expect(resolveSeverityOverride('a:b', undefined)).toBeUndefined();
expect(
resolveSeverityOverride('a:b', { 'c:*': 'info' }),
).toBeUndefined();
});
it('matches an exact id', () => {
expect(
resolveSeverityOverride('cronMonitor:lowSignupRate', {
'cronMonitor:lowSignupRate': 'info',
}),
).toBe('info');
});
it('matches a prefix pattern', () => {
expect(
resolveSeverityOverride('cronMonitor:high_aiLogEntries', {
'cronMonitor:*': 'warning',
}),
).toBe('warning');
});
it('prefers the exact id over a prefix pattern', () => {
expect(
resolveSeverityOverride('cronMonitor:lowSignupRate', {
'cronMonitor:*': 'warning',
'cronMonitor:lowSignupRate': 'mute',
}),
).toBe('mute');
});
it('prefers the longest matching prefix', () => {
expect(
resolveSeverityOverride('abuse:card-verification:setup-failed', {
'abuse:*': 'info',
'abuse:card-verification:*': 'mute',
}),
).toBe('mute');
});
it('drops an unrecognized rule rather than guessing', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(
resolveSeverityOverride('a:b', {
'a:b': 'silent' as unknown as 'mute',
}),
).toBeUndefined();
expect(warn).toHaveBeenCalled();
warn.mockRestore();
});
});
+94
View File
@@ -0,0 +1,94 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import type { PagerSeverity, SeverityRule } from '../../types';
/** Ascending urgency. A transport takes everything at or above its floor. */
const RANK: Record<PagerSeverity, number> = {
info: 0,
warning: 1,
error: 2,
critical: 3,
};
const SEVERITIES = Object.keys(RANK) as PagerSeverity[];
export function isPagerSeverity(value: unknown): value is PagerSeverity {
return typeof value === 'string' && value in RANK;
}
/** True when `severity` is urgent enough for a transport whose floor is `min`. */
export function meetsMinSeverity(
severity: PagerSeverity,
min: PagerSeverity,
): boolean {
return RANK[severity] >= RANK[min];
}
/**
* True when `severity` is quiet enough for a transport whose ceiling is `max`.
* A ceiling is what keeps a chat transport from repeating everything the pager
* already delivered.
*/
export function withinMaxSeverity(
severity: PagerSeverity,
max: PagerSeverity,
): boolean {
return RANK[severity] <= RANK[max];
}
/**
* Look up the operator override for an alarm id. Exact ids win over prefix
* patterns (`cronMonitor:*`); among patterns the longest prefix wins, so a
* specific rule can carve an exception out of a broad one.
*/
export function resolveSeverityOverride(
id: string,
overrides: Record<string, SeverityRule> | undefined,
): SeverityRule | undefined {
if (!overrides) return undefined;
const exact = overrides[id];
if (exact !== undefined) return validRule(id, exact);
let bestLength = -1;
let best: SeverityRule | undefined;
for (const [pattern, rule] of Object.entries(overrides)) {
if (!pattern.endsWith('*')) continue;
const prefix = pattern.slice(0, -1);
if (!id.startsWith(prefix)) continue;
if (prefix.length <= bestLength) continue;
bestLength = prefix.length;
best = rule;
}
return best === undefined ? undefined : validRule(id, best);
}
/**
* A typo in the override map would otherwise silently mute or escalate an
* alarm, so an unrecognized value is dropped with a warning instead.
*/
function validRule(id: string, rule: SeverityRule): SeverityRule | undefined {
if (rule === 'mute' || isPagerSeverity(rule)) return rule;
console.warn(
`[alarm] ignoring invalid severity override "${rule}" for ${id} ` +
`(expected mute or one of ${SEVERITIES.join(', ')})`,
);
return undefined;
}
+206
View File
@@ -0,0 +1,206 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildSlackMessage, createSlackAlertHandler } from './slack';
import type { AlertPayload } from './types';
const alert = (over: Partial<AlertPayload> = {}): AlertPayload => ({
id: 'cronMonitor:high_aiLogEntries',
dedupKey: 'cronMonitor:high_aiLogEntries#1.1',
shortId: 'amber-delta-fox',
message: 'High AI log entries: 1200 in the last 10 minutes',
source: 'alarm',
severity: 'warning',
fields: { count: '1200', threshold: '1000' },
repeatCount: 1,
isRepeat: false,
...over,
});
describe('buildSlackMessage', () => {
it('renders severity, message and fields', () => {
const msg = buildSlackMessage(alert(), {
channel: '#alerts',
username: 'puter-alarms',
serverId: 'oregon',
});
expect(msg.text).toContain('[WARNING]');
expect(msg.text).toContain('High AI log entries');
expect(msg.channel).toBe('#alerts');
expect(msg.username).toBe('puter-alarms');
expect(msg.attachments[0].fields).toEqual([
{ title: 'count', value: '1200', short: true },
{ title: 'threshold', value: '1000', short: true },
]);
expect(msg.attachments[0].footer).toBe(
'amber-delta-fox • cronMonitor:high_aiLogEntries • oregon',
);
});
it('marks repeats with an occurrence count', () => {
const msg = buildSlackMessage(
alert({ repeatCount: 7, isRepeat: true }),
);
expect(msg.text).toContain('(x7)');
});
it('colours each severity differently', () => {
const colors = (['critical', 'error', 'warning', 'info'] as const).map(
(severity) =>
buildSlackMessage(alert({ severity })).attachments[0].color,
);
expect(new Set(colors).size).toBe(4);
});
it('puts the stack in a code block and keeps it out of the fields', () => {
const msg = buildSlackMessage(
alert({
fields: { error: 'Error: boom', path: '/api/x' },
trace: 'Error: boom\n at handler',
}),
);
expect(msg.attachments[0].text).toBe(
'```Error: boom\n at handler```',
);
expect(msg.attachments[0].fields.map((f) => f.title)).toEqual(['path']);
});
it('truncates long values and caps the field count', () => {
const fields: Record<string, string> = { long: 'x'.repeat(1000) };
for (let i = 0; i < 30; i++) fields[`f${i}`] = String(i);
const msg = buildSlackMessage(alert({ fields }));
expect(msg.attachments[0].fields.length).toBe(12);
expect(msg.attachments[0].fields[0].value).toHaveLength(400);
expect(msg.attachments[0].fields[0].value.endsWith('…')).toBe(true);
});
it('omits channel and username when unset', () => {
const msg = buildSlackMessage(alert());
expect(msg.channel).toBeUndefined();
expect(msg.username).toBeUndefined();
});
});
describe('createSlackAlertHandler', () => {
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.useFakeTimers();
fetchMock = vi.fn(async () => ({ ok: true, status: 200 }));
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('posts the payload to the webhook', async () => {
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
channel: '#alerts',
});
await handler(alert());
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://hooks.example/abc');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body).channel).toBe('#alerts');
});
it('throttles repeats of the same alarm and lets other ids through', async () => {
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
repeatThrottleMs: 60_000,
});
await handler(alert());
await handler(alert({ repeatCount: 2, isRepeat: true }));
expect(fetchMock).toHaveBeenCalledTimes(1);
await handler(alert({ id: 'other:alarm' }));
expect(fetchMock).toHaveBeenCalledTimes(2);
vi.advanceTimersByTime(60_000);
await handler(alert({ repeatCount: 3, isRepeat: true }));
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('posts every occurrence when throttling is disabled', async () => {
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
repeatThrottleMs: 0,
});
await handler(alert());
await handler(alert({ repeatCount: 2, isRepeat: true }));
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('does not let a failed post consume the throttle slot', async () => {
fetchMock.mockResolvedValueOnce({ ok: false, status: 500 });
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
repeatThrottleMs: 60_000,
});
await expect(handler(alert())).rejects.toThrow('500');
await handler(alert());
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('releases the throttle slot when the post itself errors', async () => {
fetchMock.mockRejectedValueOnce(new Error('socket hang up'));
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
repeatThrottleMs: 60_000,
});
await expect(handler(alert())).rejects.toThrow('socket hang up');
await handler(alert());
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('evicts throttle entries that have aged out once the map fills', async () => {
const throttleMs = 60_000;
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
repeatThrottleMs: throttleMs,
});
// Fill to the high-water mark, then age every entry past the window.
for (let i = 0; i < 5000; i++) {
await handler(alert({ id: `aged:${i}` }));
}
vi.advanceTimersByTime(throttleMs);
await handler(alert({ id: 'fresh' }));
expect(fetchMock).toHaveBeenCalledTimes(5001);
// The aged ids were pruned, so they post again immediately.
await handler(alert({ id: 'aged:0' }));
expect(fetchMock).toHaveBeenCalledTimes(5002);
});
it('drops the oldest entry when the map is full of live ones', async () => {
const handler = createSlackAlertHandler({
webhookUrl: 'https://hooks.example/abc',
repeatThrottleMs: 60_000,
});
for (let i = 0; i < 5000; i++) {
await handler(alert({ id: `live:${i}` }));
}
// Nothing has aged out, so the oldest id makes room for the new one.
await handler(alert({ id: 'newcomer' }));
expect(fetchMock).toHaveBeenCalledTimes(5001);
await handler(alert({ id: 'live:0' }));
expect(fetchMock).toHaveBeenCalledTimes(5002);
// The newcomer is still throttled.
await handler(alert({ id: 'newcomer' }));
expect(fetchMock).toHaveBeenCalledTimes(5002);
});
});
+178
View File
@@ -0,0 +1,178 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import type { ISlackAlertConfig, PagerSeverity } from '../../types';
import type { AlertHandler, AlertPayload } from './types';
const REQUEST_TIMEOUT_MS = 5000;
export const DEFAULT_REPEAT_THROTTLE_MS = 15 * 60 * 1000;
/** Beyond this many tracked alarm ids, throttle state is pruned. */
const MAX_THROTTLE_ENTRIES = 5000;
const MAX_FIELDS = 12;
const MAX_FIELD_VALUE = 400;
const MAX_TRACE = 1500;
/** Values under this length sit two-per-row in the Slack attachment. */
const SHORT_FIELD_LENGTH = 40;
const STYLE: Record<PagerSeverity, { emoji: string; color: string }> = {
critical: { emoji: ':rotating_light:', color: '#d64545' },
error: { emoji: ':red_circle:', color: '#e08d4c' },
warning: { emoji: ':warning:', color: '#e0b84c' },
info: { emoji: ':information_source:', color: '#4c8de0' },
};
interface SlackField {
title: string;
value: string;
short: boolean;
}
export interface SlackMessage {
text: string;
channel?: string;
username?: string;
icon_emoji?: string;
attachments: Array<{
color: string;
fallback: string;
fields: SlackField[];
footer: string;
mrkdwn_in: string[];
text?: string;
}>;
}
function truncate(value: string, max: number): string {
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
}
/**
* Render an alert as an incoming-webhook payload: severity-coloured attachment,
* the alarm's fields as a table, and the stack (when there is one) as a code
* block. Split out from the handler so the formatting is testable on its own.
*/
export function buildSlackMessage(
alert: AlertPayload,
opts: { channel?: string; username?: string; serverId?: string } = {},
): SlackMessage {
const style = STYLE[alert.severity] ?? STYLE.info;
const repeat = alert.isRepeat ? ` (x${alert.repeatCount})` : '';
const headline = `${style.emoji} *[${alert.severity.toUpperCase()}]* ${alert.message}${repeat}`;
const fields: SlackField[] = [];
for (const [key, value] of Object.entries(alert.fields)) {
if (fields.length >= MAX_FIELDS) break;
// `error` is already rendered as the trace block below.
if (key === 'error') continue;
const rendered = truncate(value, MAX_FIELD_VALUE);
fields.push({
title: key,
value: rendered,
short: rendered.length <= SHORT_FIELD_LENGTH,
});
}
const footerParts = [alert.shortId, alert.id];
if (opts.serverId) footerParts.push(opts.serverId);
return {
text: headline,
...(opts.channel ? { channel: opts.channel } : {}),
...(opts.username ? { username: opts.username } : {}),
attachments: [
{
color: style.color,
fallback: `[${alert.severity}] ${alert.message}`,
fields,
footer: footerParts.join(' • '),
mrkdwn_in: ['text'],
...(alert.trace
? { text: '```' + truncate(alert.trace, MAX_TRACE) + '```' }
: {}),
},
],
};
}
/**
* Post alerts to a Slack incoming webhook. Repeats of the same alarm id are
* throttled so a hot loop doesn't flood the channel — the occurrence count on
* the next post that gets through tells the reader what they missed.
*/
export function createSlackAlertHandler(
conf: ISlackAlertConfig,
opts: { serverId?: string } = {},
): AlertHandler {
const webhookUrl = conf.webhookUrl as string;
const throttleMs = conf.repeatThrottleMs ?? DEFAULT_REPEAT_THROTTLE_MS;
const lastPosted = new Map<string, number>();
const shouldPost = (alert: AlertPayload): boolean => {
if (throttleMs <= 0) return true;
const now = Date.now();
const previous = lastPosted.get(alert.id);
if (previous !== undefined && now - previous < throttleMs) return false;
if (lastPosted.size >= MAX_THROTTLE_ENTRIES) {
for (const [id, at] of lastPosted) {
if (now - at >= throttleMs) lastPosted.delete(id);
}
// Still full of live entries — drop the oldest to stay bounded.
if (lastPosted.size >= MAX_THROTTLE_ENTRIES) {
const oldest = lastPosted.keys().next().value;
if (oldest !== undefined) lastPosted.delete(oldest);
}
}
lastPosted.set(alert.id, now);
return true;
};
return async (alert) => {
if (!shouldPost(alert)) return;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
try {
const res = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(
buildSlackMessage(alert, {
channel: conf.channel,
username: conf.username,
serverId: opts.serverId,
}),
),
signal: controller.signal,
});
if (!res.ok) {
// A rejected post shouldn't leave the id marked as delivered.
lastPosted.delete(alert.id);
throw new Error(`Slack webhook returned ${res.status}`);
}
} catch (err) {
lastPosted.delete(alert.id);
throw err;
} finally {
clearTimeout(timer);
}
};
}
+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 type { PagerSeverity } from '../../types';
export interface AlarmFields {
error?: Error;
[key: string]: unknown;
}
export interface AlarmOccurrence {
message: string;
fields: AlarmFields;
timestamp: number;
}
export interface AlarmOptions {
/**
* Collapse repeats of this alarm id into a single incident on transports
* that de-duplicate (PagerDuty). Only right when the id already pins down
* one recurring fault — an uncaught error on a route, say — so that N
* occurrences really are one thing to fix. Off by default: every other
* alarm raises its own incident per occurrence.
*/
dedup?: boolean;
}
export interface Alarm extends AlarmOptions {
id: string;
shortId: string;
message: string;
fields: AlarmFields;
error?: Error;
started: number;
/**
* Every occurrence ever counted, including those aged out of the two lists
* below.
*/
count: number;
/**
* Timestamps of the most recent occurrences only — see
* `OCCURRENCE_HISTORY_LIMIT`.
*/
timestamps: number[];
/** The most recent occurrences only — see `OCCURRENCE_HISTORY_LIMIT`. */
occurrences: AlarmOccurrence[];
severity?: PagerSeverity;
noAlert?: boolean;
/** Set once a config mute has been logged, so it's reported only once. */
muteLogged?: boolean;
}
export interface AlertPayload {
id: string;
/**
* Key a de-duplicating transport groups by. Equal to `id` for alarms raised
* with `dedup`, and unique per occurrence for everything else.
*/
dedupKey: string;
/** Readable slug for the same alarm, for humans quoting it back. */
shortId: string;
message: string;
source: string;
severity: PagerSeverity;
/** Field values rendered as strings, ready to display. */
fields: Record<string, string>;
/** Stack of the attached error, when the alarm carried one. */
trace?: string;
/** Total occurrences of this alarm so far, including this one. */
repeatCount: number;
/** False for the first occurrence of an alarm id. */
isRepeat: boolean;
/** PagerDuty `custom_details` payload. */
custom?: Record<string, unknown>;
}
export type AlertHandler = (alert: AlertPayload) => Promise<void>;
export interface KnownErrorRule {
match: {
id: string;
message?: string;
fields?: Record<string, unknown>;
};
action: {
type: 'no-alert' | 'severity';
value?: PagerSeverity;
};
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -0,0 +1,247 @@
/**
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, expect, it } from 'vitest';
import type { IConfig } from '../../types';
import { AbstractDatabaseClient, type WriteResult } from './DatabaseClient';
import { DatabaseClientFactory } from './index.js';
import { MySQLDatabaseClient } from './MySQLDatabaseClient.js';
import { PostgresDatabaseClient } from './PostgresDatabaseClient.js';
import { SqliteDatabaseClient } from './SqliteDatabaseClient.js';
const config = (engine: string): IConfig =>
({ port: 0, extensions: [], database: { engine } }) as IConfig;
const sqlite = () => new SqliteDatabaseClient(config('sqlite'));
const mysql = () => new MySQLDatabaseClient(config('mysql'));
const postgres = () => new PostgresDatabaseClient(config('postgres'));
/**
* Minimal concrete client backed by fixture rows — exercises the shared helpers
* on `AbstractDatabaseClient` that the real engines inherit.
*/
class FixtureDatabaseClient extends AbstractDatabaseClient {
override readonly engineName = 'fixture';
readonly reads: string[] = [];
readonly preads: string[] = [];
readonly writes: { query: string; params: unknown[] }[] = [];
constructor(
private readonly replicaRows: Record<string, unknown>[] | Error,
private readonly primaryRows: Record<string, unknown>[] = [],
) {
super(config('fixture'));
}
override async read(query: string): Promise<Record<string, unknown>[]> {
this.reads.push(query);
if (this.replicaRows instanceof Error) throw this.replicaRows;
return this.replicaRows;
}
override async pread(query: string): Promise<Record<string, unknown>[]> {
this.preads.push(query);
return this.primaryRows;
}
override async write(
query: string,
params: unknown[] = [],
): Promise<WriteResult> {
this.writes.push({ query, params });
return { insertId: 1, affectedRows: 1, anyRowsAffected: true };
}
}
describe('DatabaseClientFactory', () => {
it('picks sqlite when no engine is configured', () => {
expect(
new DatabaseClientFactory({ port: 0, extensions: [] } as IConfig),
).toBeInstanceOf(SqliteDatabaseClient);
});
it('refuses an unknown engine name', () => {
expect(() => new DatabaseClientFactory(config('cassandra'))).toThrow(
'Unknown database engine: cassandra',
);
});
});
describe('AbstractDatabaseClient — unimplemented surface', () => {
const bare = () => new AbstractDatabaseClient(config('none'));
it('refuses to run queries until a subclass implements them', async () => {
await expect(bare().read('SELECT 1')).rejects.toThrow(
'DatabaseClient.read() not implemented',
);
await expect(bare().pread('SELECT 1')).rejects.toThrow(
'DatabaseClient.pread() not implemented',
);
await expect(bare().write('DELETE FROM x')).rejects.toThrow(
'DatabaseClient.write() not implemented',
);
await expect(bare().batchWrite([])).rejects.toThrow(
'DatabaseClient.batchWrite() not implemented',
);
});
});
describe('AbstractDatabaseClient — replica-aware reads', () => {
it('returns replica rows without waiting on the primary', async () => {
const client = new FixtureDatabaseClient([{ id: 1 }], [{ id: 2 }]);
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ id: 1 },
]);
});
it('falls back to the primary when the replica has not caught up', async () => {
const client = new FixtureDatabaseClient([], [{ id: 2 }]);
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ id: 2 },
]);
});
it('falls back to the primary when the replica read throws', async () => {
const client = new FixtureDatabaseClient(
new Error('replica unavailable'),
[{ id: 3 }],
);
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ id: 3 },
]);
});
it('names the failing query when a required read finds nothing', async () => {
const client = new FixtureDatabaseClient([], []);
await expect(
client.requireRead('SELECT * FROM `user` WHERE `id` = ?'),
).rejects.toThrow(
'required read returned no rows: SELECT * FROM `user` WHERE `id` = ?',
);
});
});
describe('AbstractDatabaseClient — SQL generation', () => {
it('generates an INSERT with quoted columns and placeholders', async () => {
const client = new FixtureDatabaseClient([]);
await client.insert('user', { username: 'ada', email: null });
expect(client.writes).toEqual([
{
query: 'INSERT INTO `user` (`username`, `email`) VALUES (?, ?)',
params: ['ada', null],
},
]);
});
it('quotes each dotted segment and escapes embedded backticks', () => {
const client = sqlite();
expect(client.quoteIdentifier('user')).toBe('`user`');
expect(client.quoteIdentifier('db.user.id')).toBe('`db`.`user`.`id`');
expect(client.quoteIdentifier('user.*')).toBe('`user`.*');
expect(client.quoteIdentifier('we`ird')).toBe('`we``ird`');
});
it('quotes postgres identifiers with double quotes', () => {
const client = postgres();
expect(client.quoteIdentifier('db.user')).toBe('"db"."user"');
expect(client.quoteIdentifier('we"ird')).toBe('"we""ird"');
expect(client.quoteIdentifier('user.*')).toBe('"user".*');
});
it('renders booleans the way each engine expects', () => {
expect(sqlite().booleanLiteral(true)).toBe('1');
expect(sqlite().booleanValue(false)).toBe(0);
expect(postgres().booleanLiteral(true)).toBe('TRUE');
expect(postgres().booleanLiteral(false)).toBe('FALSE');
expect(postgres().booleanValue(true)).toBe(true);
});
it('picks the engine-specific ignore-conflict syntax', () => {
expect(sqlite().insertIgnoreInto('kv')).toBe(
'INSERT OR IGNORE INTO `kv`',
);
expect(sqlite().insertIgnoreSuffix()).toBe('');
expect(postgres().insertIgnoreInto('kv')).toBe('INSERT INTO "kv"');
expect(postgres().insertIgnoreSuffix()).toBe(' ON CONFLICT DO NOTHING');
expect(mysql().insertIgnoreInto('kv')).toBe('INSERT IGNORE INTO `kv`');
expect(mysql().insertIgnoreSuffix()).toBe('');
});
it('builds an upsert clause per engine', () => {
expect(mysql().upsertClause(['user_id'], ['value', 'dt'])).toBe(
'ON DUPLICATE KEY UPDATE `value` = ?, `dt` = ?',
);
expect(sqlite().upsertClause(['user_id', 'app'], ['value'])).toBe(
'ON CONFLICT(`user_id`, `app`) DO UPDATE SET `value` = ?',
);
expect(postgres().upsertClause(['user_id'], ['value'])).toBe(
'ON CONFLICT("user_id") DO UPDATE SET "value" = ?',
);
});
it('rejects an upsert with nothing to update', () => {
expect(() => sqlite().upsertClause(['user_id'], [])).toThrow(
'upsertClause requires at least one update column',
);
});
it('extracts JSON text using each engine dialect', () => {
expect(sqlite().jsonTextExtract('`metadata`', ['a', 'b'])).toBe(
"json_extract(`metadata`, '$.a.b')",
);
expect(mysql().jsonTextExtract('`metadata`', ['a'])).toBe(
"JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.a'))",
);
expect(postgres().jsonTextExtract('"metadata"', ['a', 'b'])).toBe(
`"metadata" #>> ARRAY['a', 'b']`,
);
});
it('escapes quotes inside JSON path segments', () => {
expect(sqlite().jsonTextExtract('`m`', ["it's"])).toBe(
"json_extract(`m`, '$.it''s')",
);
});
it('coalesces expressions and rejects an empty list', () => {
expect(sqlite().nullCoalesce('`a`', '`b`', '0')).toBe(
'COALESCE(`a`, `b`, 0)',
);
expect(() => sqlite().nullCoalesce()).toThrow(
'nullCoalesce requires at least one expression',
);
});
it('only postgres needs a RETURNING clause to learn the insert id', () => {
expect(postgres().returningIdClause()).toBe(' RETURNING id');
expect(sqlite().returningIdClause()).toBe('');
expect(mysql().returningIdClause()).toBe('');
});
it('falls back to `otherwise` for an engine with no explicit choice', () => {
const client = new FixtureDatabaseClient([]);
expect(
client.case({ sqlite: 'a', mysql: 'b', otherwise: 'fallback' }),
).toBe('fallback');
expect(client.case({ fixture: 'exact', otherwise: 'fallback' })).toBe(
'exact',
);
});
});
+19 -24
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -37,8 +37,8 @@ type SqlJsonPath = readonly [string, ...string[]];
* Base database client. Subclasses must override every method that throws here.
*
* Do not instantiate directly — use the factory exported from
* `clients/database/index.ts` which picks the right implementation
* based on `config.database.engine`.
* `clients/database/index.ts` which picks the right implementation based on
* `config.database.engine`.
*/
export class AbstractDatabaseClient extends PuterClient {
/** Short name used by `case()` to pick engine-specific values. */
@@ -52,9 +52,7 @@ export class AbstractDatabaseClient extends PuterClient {
// Abstract interface — subclasses MUST override
// ------------------------------------------------------------------
/**
* Execute a read query. Returns an array of row objects.
*/
/** Execute a read query. Returns an array of row objects. */
async read(
_query: string,
_params: unknown[] = [],
@@ -63,9 +61,9 @@ export class AbstractDatabaseClient extends PuterClient {
}
/**
* Read that prefers the primary database (useful when read-replicas
* may have replication lag). In single-node setups this is identical
* to `read()`.
* Read that prefers the primary database (useful when read-replicas may
* have replication lag). In single-node setups this is identical to
* `read()`.
*/
async pread(
_query: string,
@@ -74,16 +72,12 @@ export class AbstractDatabaseClient extends PuterClient {
throw new Error('DatabaseClient.pread() not implemented');
}
/**
* Execute a write query (INSERT / UPDATE / DELETE).
*/
/** Execute a write query (INSERT / UPDATE / DELETE). */
async write(_query: string, _params: unknown[] = []): Promise<WriteResult> {
throw new Error('DatabaseClient.write() not implemented');
}
/**
* Execute multiple write statements in a single transaction.
*/
/** Execute multiple write statements in a single transaction. */
async batchWrite(_entries: BatchEntry[]): Promise<void> {
throw new Error('DatabaseClient.batchWrite() not implemented');
}
@@ -111,9 +105,9 @@ export class AbstractDatabaseClient extends PuterClient {
}
/**
* Like `read()` but falls back to the primary when read-replicas are
* in use. Subclasses may override with replica-aware logic; the
* default delegates to `pread()`.
* Like `read()` but falls back to the primary when read-replicas are in
* use. Subclasses may override with replica-aware logic; the default
* delegates to `pread()`.
*/
async tryHardRead(
query: string,
@@ -133,9 +127,7 @@ export class AbstractDatabaseClient extends PuterClient {
return primary;
}
/**
* Like `tryHardRead()` but throws when the result set is empty.
*/
/** Like `tryHardRead()` but throws when the result set is empty. */
async requireRead(
query: string,
params: unknown[] = [],
@@ -151,9 +143,12 @@ export class AbstractDatabaseClient extends PuterClient {
* Return the value from `choices` that matches the current engine.
*
* Usage:
* ```
* db.case({ sqlite: "datetime('now')", mysql: 'NOW()', otherwise: 'NOW()' })
* ```
*
* db.case({
* sqlite: "datetime('now')",
* mysql: 'NOW()',
* otherwise: 'NOW()',
* });
*
* If the engine name isn't present in `choices`, falls back to
* `choices.otherwise`.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -17,13 +17,95 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, expect, it, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { IConfig } from '../../types';
import {
MySQLDatabaseClient,
compareMigrationFilenames,
} from './MySQLDatabaseClient.js';
interface FakeConnection {
query: ReturnType<typeof vi.fn>;
execute: ReturnType<typeof vi.fn>;
beginTransaction: ReturnType<typeof vi.fn>;
commit: ReturnType<typeof vi.fn>;
rollback: ReturnType<typeof vi.fn>;
release: ReturnType<typeof vi.fn>;
}
interface FakePool {
poolConfig: Record<string, unknown>;
connectionHandlers: ((conn: unknown) => void)[];
connections: FakeConnection[];
calls: { sql: string; values?: unknown[] }[];
ended: boolean;
endError: unknown;
endThrows: unknown;
respond: (sql: string, values?: unknown[]) => unknown;
on: (event: string, handler: (conn: unknown) => void) => FakePool;
promise: () => { getConnection: () => Promise<FakeConnection> };
end: (cb: (err?: unknown) => void) => void;
}
// mysql2 is the wire boundary: stub the driver's pool so we can assert on
// the exact SQL, parameters and connection choreography the adapter emits.
const { createPoolMock, createdPools } = vi.hoisted(() => {
const createdPools: FakePool[] = [];
const createPoolMock = vi.fn((poolConfig: Record<string, unknown>) => {
const pool: FakePool = {
poolConfig,
connectionHandlers: [],
connections: [],
calls: [],
ended: false,
endError: null,
endThrows: null,
respond: () => [[], undefined],
on(event, handler) {
if (event === 'connection') {
pool.connectionHandlers.push(handler);
}
return pool;
},
promise() {
return {
getConnection: async () => {
const run = async (sql: string, values?: unknown[]) => {
pool.calls.push({ sql, values });
return pool.respond(sql, values);
};
const conn: FakeConnection = {
query: vi.fn(run),
execute: vi.fn(run),
beginTransaction: vi.fn(async () => {}),
commit: vi.fn(async () => {}),
rollback: vi.fn(async () => {}),
release: vi.fn(),
};
pool.connections.push(conn);
return conn;
},
};
},
end(cb) {
if (pool.endThrows) throw pool.endThrows;
pool.ended = true;
cb(pool.endError ?? undefined);
},
};
createdPools.push(pool);
return pool;
});
return { createPoolMock, createdPools };
});
vi.mock('mysql2', () => ({ createPool: createPoolMock }));
describe('compareMigrationFilenames', () => {
it('orders numbered migrations numerically, not lexically', () => {
const input = [
@@ -132,7 +214,9 @@ const codedError = (code: string) => {
describe('MySQLDatabaseClient.read — replica failover', () => {
it('fails over to the primary on batcher load-shed errors', async () => {
const replica = { execute: vi.fn().mockRejectedValue(codedError('dbBatchFailed')) };
const replica = {
execute: vi.fn().mockRejectedValue(codedError('dbBatchFailed')),
};
const primary = { execute: vi.fn().mockResolvedValue([[{ ok: 1 }]]) };
const client = makeClient({ replica, primary });
@@ -141,7 +225,9 @@ describe('MySQLDatabaseClient.read — replica failover', () => {
});
it('fails over on transient connection errors', async () => {
const replica = { execute: vi.fn().mockRejectedValue(codedError('ECONNRESET')) };
const replica = {
execute: vi.fn().mockRejectedValue(codedError('ECONNRESET')),
};
const primary = { execute: vi.fn().mockResolvedValue([[{ ok: 1 }]]) };
const client = makeClient({ replica, primary });
@@ -149,7 +235,9 @@ describe('MySQLDatabaseClient.read — replica failover', () => {
});
it('rethrows deterministic SQL errors without touching the primary', async () => {
const replica = { execute: vi.fn().mockRejectedValue(codedError('ER_PARSE_ERROR')) };
const replica = {
execute: vi.fn().mockRejectedValue(codedError('ER_PARSE_ERROR')),
};
const primary = { execute: vi.fn() };
const client = makeClient({ replica, primary });
@@ -160,7 +248,9 @@ describe('MySQLDatabaseClient.read — replica failover', () => {
});
it('does not fail over in single-node configuration', async () => {
const replica = { execute: vi.fn().mockRejectedValue(codedError('dbBatchFailed')) };
const replica = {
execute: vi.fn().mockRejectedValue(codedError('dbBatchFailed')),
};
const primary = { execute: vi.fn() };
const client = makeClient({ replica, primary, multiNode: false });
@@ -170,3 +260,588 @@ describe('MySQLDatabaseClient.read — replica failover', () => {
expect(primary.execute).not.toHaveBeenCalled();
});
});
// -- Driver-level behaviour (stubbed mysql2 pool) ---------------------
const mysqlConfig = (
database: Partial<NonNullable<IConfig['database']>> = {},
): IConfig =>
({
port: 0,
extensions: [],
database: { engine: 'mysql', ...database },
}) as IConfig;
const startClient = async (
database: Partial<NonNullable<IConfig['database']>> = {},
): Promise<MySQLDatabaseClient> => {
const client = new MySQLDatabaseClient(mysqlConfig(database));
await client.onServerStart();
return client;
};
// The batcher coalesces a batch into `stmt1;stmt2; SELECT 1`, so the driver
// must answer with one row-set per statement plus one for the SELECT 1.
const rowSets = (...sets: unknown[][]) => [[...sets, [{ 1: 1 }]], undefined];
beforeEach(() => {
createdPools.length = 0;
createPoolMock.mockClear();
});
describe('MySQLDatabaseClient — pool construction', () => {
it('builds the primary pool from config with multi-statement support', async () => {
await startClient({
host: 'db.internal',
port: 3307,
user: 'puter',
password: 'hunter2',
database: 'puterdb',
});
expect(createPoolMock).toHaveBeenCalledTimes(1);
expect(createdPools[0].poolConfig).toEqual({
maxPreparedStatements: 900,
connectionLimit: 30,
enableKeepAlive: true,
host: 'db.internal',
port: 3307,
user: 'puter',
password: 'hunter2',
database: 'puterdb',
multipleStatements: true,
});
});
it('falls back to loopback defaults when the endpoint is unspecified', async () => {
await startClient();
expect(createdPools[0].poolConfig).toMatchObject({
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '',
database: 'puter',
});
});
it('arms a server-side statement timeout on every new connection', async () => {
await startClient({ selectTimeoutMs: 12_000 });
const pool = createdPools[0];
expect(pool.connectionHandlers).toHaveLength(1);
const conn = { query: vi.fn() };
pool.connectionHandlers[0](conn);
expect(conn.query).toHaveBeenCalledWith(
'SET SESSION max_execution_time = 12000',
);
});
it('omits the statement timeout when configured to 0', async () => {
await startClient({ selectTimeoutMs: 0 });
expect(createdPools[0].connectionHandlers).toHaveLength(0);
});
it('shares one pool between reads and writes without a replica', async () => {
await startClient();
expect(createPoolMock).toHaveBeenCalledTimes(1);
});
it('creates a second pool when a read-replica is configured', async () => {
await startClient({
replica: { host: 'replica.internal', port: 3306 },
});
expect(createPoolMock).toHaveBeenCalledTimes(2);
expect(createdPools[1].poolConfig).toMatchObject({
host: 'replica.internal',
multipleStatements: true,
});
});
});
describe('MySQLDatabaseClient — query interface', () => {
it('sends the query and its parameters through to the driver', async () => {
const client = await startClient();
const pool = createdPools[0];
pool.respond = () => rowSets([{ id: 1, username: 'ada' }]);
await expect(
client.read('SELECT * FROM `user` WHERE `id` = ?', [1]),
).resolves.toEqual([{ id: 1, username: 'ada' }]);
expect(pool.calls).toEqual([
{
sql: 'SELECT * FROM `user` WHERE `id` = ?; SELECT 1',
values: [1],
},
]);
});
it('returns an empty array when the driver yields no row-set', async () => {
const client = await startClient();
createdPools[0].respond = () => [[], undefined];
await expect(client.read('SELECT 1')).resolves.toEqual([]);
await expect(client.pread('SELECT 1')).resolves.toEqual([]);
});
it('reads from the replica pool and primary-reads from the primary', async () => {
const client = await startClient({ replica: { host: 'replica' } });
const [primary, replica] = createdPools;
primary.respond = () => rowSets([{ from: 'primary' }]);
replica.respond = () => rowSets([{ from: 'replica' }]);
await expect(client.read('SELECT 1')).resolves.toEqual([
{ from: 'replica' },
]);
await expect(client.pread('SELECT 1')).resolves.toEqual([
{ from: 'primary' },
]);
});
it('maps the mysql result header onto the shared write result', async () => {
const client = await startClient();
createdPools[0].respond = () =>
rowSets({ insertId: 42, affectedRows: 2 } as unknown as unknown[]);
await expect(
client.write('UPDATE `user` SET `username` = ? WHERE `id` = ?', [
'ada',
1,
]),
).resolves.toEqual({
insertId: 42,
affectedRows: 2,
anyRowsAffected: true,
});
});
it('reports no rows affected when the header omits the counters', async () => {
const client = await startClient();
createdPools[0].respond = () => rowSets({} as unknown as unknown[]);
await expect(client.write('DELETE FROM `user`')).resolves.toEqual({
insertId: 0,
affectedRows: 0,
anyRowsAffected: false,
});
});
it('builds an INSERT with quoted identifiers and positional params', async () => {
const client = await startClient();
const pool = createdPools[0];
pool.respond = () =>
rowSets({ insertId: 7, affectedRows: 1 } as unknown as unknown[]);
await expect(
client.insert('user', { username: 'ada', email: null }),
).resolves.toMatchObject({ insertId: 7 });
expect(pool.calls[0]).toEqual({
sql:
'INSERT INTO `user` (`username`, `email`) VALUES (?, ?); ' +
'SELECT 1',
values: ['ada', null],
});
});
});
describe('MySQLDatabaseClient — batchWrite transactions', () => {
it('runs every statement on one connection inside a transaction', async () => {
const client = await startClient();
const pool = createdPools[0];
await client.batchWrite([
{ statement: 'UPDATE `user` SET `x` = ?', values: [1] },
{
statement: 'DELETE FROM `sessions` WHERE `uuid` = ?',
values: ['s'],
},
]);
expect(pool.connections).toHaveLength(1);
const conn = pool.connections[0];
expect(conn.beginTransaction).toHaveBeenCalledTimes(1);
expect(conn.execute.mock.calls).toEqual([
['UPDATE `user` SET `x` = ?', [1]],
['DELETE FROM `sessions` WHERE `uuid` = ?', ['s']],
]);
expect(conn.commit).toHaveBeenCalledTimes(1);
expect(conn.rollback).not.toHaveBeenCalled();
expect(conn.release).toHaveBeenCalledTimes(1);
});
it('rolls back and releases the connection when a statement fails', async () => {
const client = await startClient();
const pool = createdPools[0];
pool.respond = (sql) => {
if (sql.startsWith('DELETE')) throw new Error('constraint blew up');
return [[], undefined];
};
await expect(
client.batchWrite([
{ statement: 'UPDATE `user` SET `x` = ?', values: [1] },
{ statement: 'DELETE FROM `user`', values: [] },
]),
).rejects.toThrow('constraint blew up');
const conn = pool.connections[0];
expect(conn.commit).not.toHaveBeenCalled();
expect(conn.rollback).toHaveBeenCalledTimes(1);
expect(conn.release).toHaveBeenCalledTimes(1);
});
it('still rethrows the original failure when the rollback also fails', async () => {
const client = await startClient();
const pool = createdPools[0];
pool.respond = () => {
throw new Error('statement blew up');
};
const original = client.batchWrite([
{ statement: 'UPDATE `user` SET `x` = ?', values: [1] },
]);
// The rollback is attached after the connection is handed out, so
// patch it once the adapter has acquired one.
await Promise.resolve();
pool.connections[0]?.rollback.mockRejectedValue(
new Error('rollback blew up'),
);
await expect(original).rejects.toThrow('statement blew up');
expect(pool.connections[0].release).toHaveBeenCalledTimes(1);
});
it('never acquires a connection for an empty batch', async () => {
const client = await startClient();
await client.batchWrite([]);
expect(createdPools[0].connections).toHaveLength(0);
});
});
describe('MySQLDatabaseClient — tryHardRead', () => {
it('issues exactly one query in single-node configuration', async () => {
const client = await startClient();
const pool = createdPools[0];
pool.respond = () => rowSets([{ id: 1 }]);
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ id: 1 },
]);
expect(pool.calls).toHaveLength(1);
});
it('prefers replica rows when the replica has them', async () => {
const client = await startClient({ replica: { host: 'replica' } });
const [primary, replica] = createdPools;
primary.respond = () => rowSets([{ from: 'primary' }]);
replica.respond = () => rowSets([{ from: 'replica' }]);
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ from: 'replica' },
]);
});
it('falls back to the primary when the replica is behind', async () => {
const client = await startClient({ replica: { host: 'replica' } });
const [primary, replica] = createdPools;
primary.respond = () => rowSets([{ from: 'primary' }]);
replica.respond = () => rowSets([]);
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ from: 'primary' },
]);
});
it('falls back to the primary when the replica query throws', async () => {
const client = await startClient({ replica: { host: 'replica' } });
const [primary, replica] = createdPools;
primary.respond = () => rowSets([{ from: 'primary' }]);
replica.respond = () => {
throw new Error('replica down');
};
await expect(client.tryHardRead('SELECT 1')).resolves.toEqual([
{ from: 'primary' },
]);
});
});
describe('MySQLDatabaseClient — migrations', () => {
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'puter-mysql-mig-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it('applies mysql migrations in numeric order, one statement at a time', async () => {
writeFileSync(
join(dir, 'mysql_mig_2.sql'),
'CREATE TABLE b (id INT);\nCREATE TABLE c (id INT);\n',
);
writeFileSync(
join(dir, 'mysql_mig_10.sql'),
'CREATE TABLE d (id INT);',
);
// Other engines' files and non-SQL noise must be ignored.
writeFileSync(join(dir, 'postgres_mig_1.sql'), 'CREATE TABLE nope ();');
writeFileSync(join(dir, 'mysql_notes.txt'), 'not sql');
await startClient({ migrationPaths: [dir] });
const pool = createdPools[0];
expect(pool.calls.map((c) => c.sql)).toEqual([
'CREATE TABLE b (id INT)',
'CREATE TABLE c (id INT)',
'CREATE TABLE d (id INT)',
]);
expect(pool.connections[0].release).toHaveBeenCalledTimes(1);
});
it('reports which file and statement index failed', async () => {
writeFileSync(
join(dir, 'mysql_mig_1.sql'),
'CREATE TABLE ok (id INT);\nCREATE TABLE bad (id INT);',
);
const client = new MySQLDatabaseClient(
mysqlConfig({ migrationPaths: [dir] }),
);
const cause = new Error('ER_PARSE_ERROR');
// The pool only exists once onServerStart runs, so arm the failure
// through the factory.
createPoolMock.mockImplementationOnce((poolConfig) => {
const pool = createPoolMock.getMockImplementation()!(poolConfig);
pool.respond = (sql: string) => {
if (sql.includes('bad')) throw cause;
return [[], undefined];
};
return pool;
});
await expect(client.onServerStart()).rejects.toThrow(
'[mysql] failed to apply mysql_mig_1.sql at statement 1',
);
});
it('fails loudly when a configured migration path is unreadable', async () => {
await expect(
startClient({ migrationPaths: [join(dir, 'does-not-exist')] }),
).rejects.toThrow('[mysql] migration path is unreadable');
});
it('skips a configured directory that holds no mysql migrations', async () => {
writeFileSync(join(dir, 'readme.md'), '# nothing here');
await startClient({ migrationPaths: [dir] });
expect(createdPools[0].calls).toEqual([]);
});
});
describe('MySQLDatabaseClient — pool lifecycle', () => {
it('replaces and closes the previous primary pool on reinit', async () => {
const client = await startClient();
const original = createdPools[0];
client.reinitPrimary();
expect(createdPools).toHaveLength(2);
expect(original.ended).toBe(true);
// Single-node: the replica batcher must follow the new primary.
createdPools[1].respond = () => rowSets([{ from: 'new-primary' }]);
await expect(client.read('SELECT 1')).resolves.toEqual([
{ from: 'new-primary' },
]);
});
it('replaces only the replica pool on replica reinit', async () => {
const client = await startClient({ replica: { host: 'replica' } });
const [primary, originalReplica] = createdPools;
client.reinitReplica();
expect(createdPools).toHaveLength(3);
expect(originalReplica.ended).toBe(true);
expect(primary.ended).toBe(false);
});
it('ignores a replica reinit when no replica is configured', async () => {
const client = await startClient();
client.reinitReplica();
expect(createdPools).toHaveLength(1);
});
it('ignores reinit once shutdown has started', async () => {
const client = await startClient();
await client.onServerPrepareShutdown();
client.reinitPrimary();
expect(createdPools).toHaveLength(1);
await client.onServerShutdown();
});
it('closes both pools on shutdown when a replica is configured', async () => {
const client = await startClient({ replica: { host: 'replica' } });
await client.onServerShutdown();
expect(createdPools[0].ended).toBe(true);
expect(createdPools[1].ended).toBe(true);
});
it('closes the pools once the drain window elapses', async () => {
vi.useFakeTimers();
try {
const client = await startClient();
await client.onServerPrepareShutdown();
expect(createdPools[0].ended).toBe(false);
await vi.advanceTimersByTimeAsync(60_000);
expect(createdPools[0].ended).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('cancels the drain timer when shutdown arrives first', async () => {
vi.useFakeTimers();
try {
const client = await startClient();
await client.onServerPrepareShutdown();
// A second prepare is a no-op — only one drain timer may exist.
await client.onServerPrepareShutdown();
expect(vi.getTimerCount()).toBe(1);
await client.onServerShutdown();
expect(vi.getTimerCount()).toBe(0);
expect(createdPools[0].ended).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('surfaces a driver error raised while closing the pool', async () => {
const client = await startClient();
createdPools[0].endError = new Error('pool refused to close');
await expect(client.onServerShutdown()).rejects.toThrow(
'pool refused to close',
);
});
it('surfaces a driver error thrown synchronously by end()', async () => {
const client = await startClient();
createdPools[0].endThrows = new Error('end exploded');
await expect(client.onServerShutdown()).rejects.toThrow('end exploded');
});
});
describe('MySQLDatabaseClient.readWithRetry', () => {
const codedFailure = (code: string) => {
const err = new Error(code) as Error & { code: string };
err.code = code;
return err;
};
it('classifies transient connection failures as retriable', () => {
expect(
MySQLDatabaseClient.isRetriableError(codedFailure('ECONNRESET')),
).toBe(true);
expect(
MySQLDatabaseClient.isRetriableError(codedFailure('ER_DUP_ENTRY')),
).toBe(false);
expect(
MySQLDatabaseClient.isRetriableError(new Error('Connection lost')),
).toBe(true);
});
it('retries a transient failure and returns the eventual result', async () => {
const client = await startClient();
let attempts = 0;
const operation = vi.fn(async () => {
attempts += 1;
if (attempts < 3) throw codedFailure('PROTOCOL_CONNECTION_LOST');
return [{ ok: 1 }];
});
await expect(
client.readWithRetry('health', operation, { baseBackoffMs: 0 }),
).resolves.toEqual([{ ok: 1 }]);
expect(operation).toHaveBeenCalledTimes(3);
});
it('gives up after the attempt budget is spent', async () => {
const client = await startClient();
const operation = vi.fn(async () => {
throw codedFailure('ETIMEDOUT');
});
await expect(
client.readWithRetry('health', operation, {
maxAttempts: 2,
baseBackoffMs: 0,
}),
).rejects.toMatchObject({ code: 'ETIMEDOUT' });
expect(operation).toHaveBeenCalledTimes(2);
});
it('never retries a deterministic SQL error', async () => {
const client = await startClient();
const operation = vi.fn(async () => {
throw codedFailure('ER_PARSE_ERROR');
});
await expect(
client.readWithRetry('health', operation, { baseBackoffMs: 0 }),
).rejects.toMatchObject({ code: 'ER_PARSE_ERROR' });
expect(operation).toHaveBeenCalledTimes(1);
});
it('stops retrying once shutdown has started', async () => {
const client = await startClient();
await client.onServerPrepareShutdown();
const operation = vi.fn(async () => {
throw codedFailure('ECONNRESET');
});
await expect(
client.readWithRetry('health', operation, { baseBackoffMs: 0 }),
).rejects.toMatchObject({ code: 'ECONNRESET' });
expect(operation).toHaveBeenCalledTimes(1);
await client.onServerShutdown();
});
it('applies jittered exponential backoff capped at maxBackoffMs', async () => {
const client = await startClient();
const delays: number[] = [];
const realSetTimeout = globalThis.setTimeout;
const timeoutSpy = vi
.spyOn(globalThis, 'setTimeout')
.mockImplementation(((fn: () => void, ms?: number) => {
delays.push(ms ?? 0);
return realSetTimeout(fn, 0);
}) as typeof setTimeout);
try {
const operation = vi.fn(async () => {
throw codedFailure('ECONNRESET');
});
await expect(
client.readWithRetry('health', operation, {
maxAttempts: 4,
baseBackoffMs: 100,
maxBackoffMs: 150,
jitterRatio: 0,
}),
).rejects.toMatchObject({ code: 'ECONNRESET' });
expect(delays).toEqual([100, 150, 150]);
} finally {
timeoutSpy.mockRestore();
}
});
});
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -248,9 +248,9 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient {
/**
* Apply `.sql` files from each configured migration directory in order.
* Files within a directory are sorted lexically. Files MUST be
* idempotent — there is no per-file applied-state tracking. Failures
* abort startup so operators see schema problems loud.
* Files within a directory are sorted lexically. Files MUST be idempotent —
* there is no per-file applied-state tracking. Failures abort startup so
* operators see schema problems loud.
*/
private async runMigrations(): Promise<void> {
const paths = this.config.database?.migrationPaths;
@@ -414,8 +414,10 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient {
return isRetriableError(error);
}
/** Replica failures worth retrying on the primary: batcher load-shed
* or transient connection errors — never deterministic SQL errors. */
/**
* Replica failures worth retrying on the primary: batcher load-shed or
* transient connection errors — never deterministic SQL errors.
*/
private static isFailoverWorthy(error: unknown): boolean {
const code = (error as { code?: string })?.code;
return code === 'dbBatchFailed' || isRetriableError(error);
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
+24 -15
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -22,6 +22,7 @@ import {
POOL_ACQUIRE_TIMEOUT,
isNeverSentError,
isRetriableError,
isRolledBackError,
} from './retriableErrors.js';
const DEFAULT_MAX_QUEUE_SIZE = 1000;
@@ -89,20 +90,22 @@ export class SQLBatcher {
#metricAttrs;
/**
* @param {object} dbPool mysql2 pool
* @param {object} dbPool Mysql2 pool
* @param {object} [opts]
* @param {number} [opts.maxTimeInQueue] ms an item may wait before flush
* @param {number} [opts.maxBatchSize] items coalesced per flush
* @param {number} [opts.maxQueueSize] drop-oldest high-water mark
* @param {number} [opts.failureThreshold] consecutive failures to open the breaker
* @param {number} [opts.cooldownMs] breaker open duration after last failure
* @param {'primary'|'replica'} [opts.poolLabel] role label on metrics; in
* @param {number} [opts.maxTimeInQueue] Ms an item may wait before flush
* @param {number} [opts.maxBatchSize] Items coalesced per flush
* @param {number} [opts.maxQueueSize] Drop-oldest high-water mark
* @param {number} [opts.failureThreshold] Consecutive failures to open the
* breaker
* @param {number} [opts.cooldownMs] Breaker open duration after last
* failure
* @param {'primary' | 'replica'} [opts.poolLabel] Role label on metrics; in
* single-node setups the 'replica' batcher shares the primary pool, so
* this reflects the read/write role rather than a physical instance
* @param {boolean} [opts.readOnly] this batcher only ever carries SELECTs,
* @param {boolean} [opts.readOnly] This batcher only ever carries SELECTs,
* so any transient failure is safe to retry
* @param {number} [opts.acquireTimeoutMs] max wait for a pooled
* connection; 0 disables the bound
* @param {number} [opts.acquireTimeoutMs] Max wait for a pooled connection;
* 0 disables the bound
*/
constructor(
dbPool,
@@ -359,8 +362,14 @@ export class SQLBatcher {
// Run one fallback item, retrying transient failures with backoff.
// A read-only batcher may retry anything transient; a batcher that
// carries writes only retries failures where the statement provably
// never reached the server — a write that died mid-flight may have
// committed, and re-running it would double-apply.
// did not apply — either it never reached the server, or the server
// rolled it back itself. A write that died mid-flight may have
// committed, and re-running that one would double-apply.
//
// Lock contention lands in the second group and is worth retrying rather
// than surfacing: an item is a single statement, so a deadlock victim has
// been fully undone, and the caller sees an unhandled 500 for what the
// database is telling us to just run again.
async #runFallbackItem(b) {
let attempt = 0;
while (true) {
@@ -377,8 +386,8 @@ export class SQLBatcher {
};
} catch (error) {
const canRetry = this.readOnly
? isRetriableError(error)
: isNeverSentError(error);
? isRetriableError(error) || isRolledBackError(error)
: isNeverSentError(error) || isRolledBackError(error);
if (!canRetry || attempt >= ITEM_RETRY_ATTEMPTS) {
return { ok: false, error };
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -208,6 +208,36 @@ describe('SQLBatcher', () => {
expect(fallbackAttempts).toBe(2);
});
it('retries a deadlocked write instead of surfacing it', async () => {
let fallbackAttempts = 0;
const conn = makeConnection((sql) => {
if (isBatchQuery(sql)) throw makeError('ER_LOCK_DEADLOCK');
fallbackAttempts++;
if (fallbackAttempts === 1) throw makeError('ER_LOCK_DEADLOCK');
return [[{ ok: 1 }], undefined];
});
const { pool } = makePool(conn);
const batcher = new SQLBatcher(pool, { maxTimeInQueue: 5 });
// The victim statement was rolled back by the server, so re-running it
// can't double-apply — the caller should never see the deadlock.
const result = await batcher.query('UPDATE notification SET x', []);
expect(result[0]).toEqual([{ ok: 1 }]);
expect(fallbackAttempts).toBe(2);
});
it('gives up on a write that deadlocks past the retry budget', async () => {
const conn = makeConnection(() => {
throw makeError('ER_LOCK_DEADLOCK');
});
const { pool } = makePool(conn);
const batcher = new SQLBatcher(pool, { maxTimeInQueue: 5 });
await expect(batcher.query('UPDATE hot SET x', [])).rejects.toMatchObject(
{ code: 'ER_LOCK_DEADLOCK' },
);
});
it('never retries deterministic row-level errors and does not escalate the breaker', async () => {
let fallbackAttempts = 0;
const conn = makeConnection((sql) => {
@@ -0,0 +1,547 @@
/**
* 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 Database from 'better-sqlite3';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { IConfig } from '../../types';
import { DatabaseClientFactory } from './index.js';
import { SqliteDatabaseClient } from './SqliteDatabaseClient.js';
/** Highest schema version the migration table can reach. */
const CURRENT_SCHEMA_VERSION = 66;
/**
* These suites migrate real files on disk. Idle they finish in well under a
* second, but the whole migration chain runs against the filesystem — enough
* that a loaded runner blows the 5s default and reports a timeout where there
* is no fault.
*/
const DISK_MIGRATION_TIMEOUT_MS = 30_000;
const SYSTEM_USER_UUID = '5d4adce0-a381-4982-9c02-6e2540026238';
const sqliteConfig = (
database: Partial<NonNullable<IConfig['database']>> = {},
): IConfig =>
({
port: 0,
extensions: [],
database: { engine: 'sqlite', inMemory: true, ...database },
}) as IConfig;
const bootClient = async (
database: Partial<NonNullable<IConfig['database']>> = {},
): Promise<SqliteDatabaseClient> => {
const client = new SqliteDatabaseClient(sqliteConfig(database));
await client.onServerStart();
return client;
};
const userVersionOf = async (client: SqliteDatabaseClient): Promise<number> => {
const [row] = await client.read('PRAGMA user_version');
return row.user_version as number;
};
describe('SqliteDatabaseClient — boot and migrations', { timeout: DISK_MIGRATION_TIMEOUT_MS }, () => {
let client: SqliteDatabaseClient;
beforeEach(async () => {
client = await bootClient();
});
afterEach(() => {
client.onServerShutdown();
});
it('is what the factory picks for the sqlite engine', () => {
expect(new DatabaseClientFactory(sqliteConfig())).toBeInstanceOf(
SqliteDatabaseClient,
);
});
it('migrates a fresh database all the way to the current version', async () => {
expect(await userVersionOf(client)).toBe(CURRENT_SCHEMA_VERSION);
});
it('runs the javascript migrations, not just the .sql ones', async () => {
// The `system` user only exists because 0025 (a .dbmig.js file) ran
// inside the migration VM.
const rows = await client.read(
'SELECT `username` FROM `user` WHERE `uuid` = ?',
[SYSTEM_USER_UUID],
);
expect(rows).toEqual([{ username: 'system' }]);
});
// 0070 sweeps three by-hand groups no code reads. Both tables it can reach
// cascade on delete, so the guard is the point: a group that still carries
// permissions or members has to survive, or the sweep silently revokes
// them. Re-running the statement is safe — it is a plain conditional DELETE.
describe('0070 drop-orphaned-default-groups', () => {
const MIGRATION = readFileSync(
new URL(
'./migrations/sqlite/0070_drop-orphaned-default-groups.sql',
import.meta.url,
),
'utf8',
);
const seedGroup = async (name: string): Promise<number> => {
const [system] = await client.read(
'SELECT `id` FROM `user` WHERE `uuid` = ?',
[SYSTEM_USER_UUID],
);
const uid = `grp-${name}-${Math.random().toString(36).slice(2, 10)}`;
await client.write(
'INSERT INTO `group` (`uid`, `owner_user_id`, `extra`, `metadata`) ' +
'VALUES (?, ?, ?, ?)',
[uid, system.id, JSON.stringify({ name }), '{}'],
);
const [row] = await client.read(
'SELECT `id` FROM `group` WHERE `uid` = ?',
[uid],
);
return Number(row.id);
};
const stillThere = async (id: number): Promise<boolean> => {
const rows = await client.read(
'SELECT `id` FROM `group` WHERE `id` = ?',
[id],
);
return rows.length > 0;
};
it('drops an orphaned freeai/experimental/dangerous group', async () => {
const ids = await Promise.all(
['freeai', 'experimental', 'dangerous'].map(seedGroup),
);
await client.write(MIGRATION);
for (const id of ids) expect(await stillThere(id)).toBe(false);
});
it('spares one that still carries a permission row', async () => {
const id = await seedGroup('freeai');
const [system] = await client.read(
'SELECT `id` FROM `user` WHERE `uuid` = ?',
[SYSTEM_USER_UUID],
);
await client.write(
'INSERT INTO `user_to_group_permissions` ' +
'(`user_id`, `group_id`, `permission`, `extra`) VALUES (?, ?, ?, ?)',
[system.id, id, 'service:some-paid-thing', '{}'],
);
await client.write(MIGRATION);
expect(await stillThere(id)).toBe(true);
// And the grant it carries is still intact, not cascaded away.
const perms = await client.read(
'SELECT `permission` FROM `user_to_group_permissions` WHERE `group_id` = ?',
[id],
);
expect(perms).toEqual([{ permission: 'service:some-paid-thing' }]);
});
it('spares one that still has members', async () => {
const id = await seedGroup('experimental');
const [system] = await client.read(
'SELECT `id` FROM `user` WHERE `uuid` = ?',
[SYSTEM_USER_UUID],
);
await client.write(
'INSERT INTO `jct_user_group` (`user_id`, `group_id`) VALUES (?, ?)',
[system.id, id],
);
await client.write(MIGRATION);
expect(await stillThere(id)).toBe(true);
});
it('leaves the groups the platform actually depends on alone', async () => {
// system, admin, user and temp are named by config or code.
await client.write(MIGRATION);
const rows = await client.read(
"SELECT json_extract(`extra`, '$.name') AS name FROM `group`",
);
const names = rows.map((r) => String(r.name));
for (const name of ['system', 'admin', 'user']) {
expect(names).toContain(name);
}
});
});
it('leaves an already-migrated database untouched on a second boot', async () => {
const dir = mkdtempSync(join(tmpdir(), 'puter-sqlite-'));
const path = join(dir, 'nested', 'puter.sqlite');
try {
const first = new SqliteDatabaseClient(
sqliteConfig({ inMemory: false, path }),
);
await first.onServerStart();
await first.write(
'INSERT INTO `kv` (`user_id`, `kkey_hash`, `kkey`, `value`) ' +
'VALUES (?, ?, ?, ?)',
[1, 1, 'boot-marker', '"kept"'],
);
first.onServerShutdown();
expect(existsSync(path)).toBe(true);
const second = new SqliteDatabaseClient(
sqliteConfig({ inMemory: false, path }),
);
await second.onServerStart();
await expect(
second.read('SELECT `value` FROM `kv` WHERE `kkey` = ?', [
'boot-marker',
]),
).resolves.toEqual([{ value: '"kept"' }]);
expect(await userVersionOf(second)).toBe(CURRENT_SCHEMA_VERSION);
second.onServerShutdown();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it('stops early at a configured target version', async () => {
const partial = await bootClient({ targetVersion: 5 });
try {
expect(await userVersionOf(partial)).toBe(5);
// 0005 landed (apps.background); 0011 (notification) did not.
await expect(
partial.read(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'notification'",
),
).resolves.toEqual([]);
await expect(
partial.read(
"SELECT 1 FROM pragma_table_info('apps') WHERE name = 'background'",
),
).resolves.toHaveLength(1);
} finally {
partial.onServerShutdown();
}
});
});
describe(
'SqliteDatabaseClient — legacy version inference',
{ timeout: DISK_MIGRATION_TIMEOUT_MS },
() => {
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'puter-sqlite-legacy-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it('treats user_version=0 with no bootstrap tables as uninitialized', async () => {
const path = join(dir, 'blank.sqlite');
new Database(path).close();
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const client = new SqliteDatabaseClient(
sqliteConfig({ inMemory: false, path }),
);
try {
await client.onServerStart();
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('bootstrap tables are missing'),
);
// A full migration run followed, so the schema is current.
expect(await userVersionOf(client)).toBe(CURRENT_SCHEMA_VERSION);
} finally {
client.onServerShutdown();
warn.mockRestore();
}
});
it('infers the schema version from table and column markers', async () => {
const path = join(dir, 'legacy.sqlite');
const seed = new Database(path);
seed.exec(`
CREATE TABLE user (
id INTEGER PRIMARY KEY,
username TEXT,
otp_secret TEXT,
otp_enabled INTEGER,
otp_recovery_codes TEXT
);
CREATE TABLE apps (
id INTEGER PRIMARY KEY,
uid TEXT,
background INTEGER,
metadata TEXT
);
CREATE TABLE user_to_user_permissions (id INTEGER PRIMARY KEY);
CREATE TABLE audit_user_to_user_permissions (
id INTEGER PRIMARY KEY,
issuer_user_id INTEGER,
holder_user_id INTEGER
);
CREATE TABLE sessions (
id INTEGER PRIMARY KEY,
created_at INTEGER,
last_activity INTEGER
);
CREATE TABLE kv (id INTEGER PRIMARY KEY, value JSON);
INSERT INTO apps (uid)
VALUES ('app-e3ac5486-da8c-42ad-8377-8728086e0980');
`);
seed.close();
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
// targetVersion just past the inferred version keeps the run a
// no-op, so the assertion is about inference alone.
const client = new SqliteDatabaseClient(
sqliteConfig({ inMemory: false, path, targetVersion: 22 }),
);
try {
await client.onServerStart();
expect(warn).toHaveBeenCalledWith(
'[sqlite] user_version=0; inferred legacy schema version 21',
);
// Nothing was applied, so user_version stays where it was.
expect(await userVersionOf(client)).toBe(0);
} finally {
client.onServerShutdown();
warn.mockRestore();
}
});
it('reports version 0 when only the bootstrap tables exist', async () => {
const path = join(dir, 'bootstrap-only.sqlite');
const seed = new Database(path);
seed.exec(`
CREATE TABLE user (id INTEGER PRIMARY KEY);
CREATE TABLE apps (id INTEGER PRIMARY KEY);
`);
seed.close();
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const client = new SqliteDatabaseClient(
sqliteConfig({ inMemory: false, path, targetVersion: 1 }),
);
try {
await client.onServerStart();
expect(log).toHaveBeenCalledWith('[sqlite] database version: 0');
} finally {
client.onServerShutdown();
log.mockRestore();
}
});
});
describe('SqliteDatabaseClient — query interface', () => {
let client: SqliteDatabaseClient;
beforeEach(async () => {
client = await bootClient();
await client.write(
'CREATE TABLE `widget` (`id` INTEGER PRIMARY KEY, ' +
'`name` TEXT, `enabled` INTEGER, `seen_at` TEXT)',
);
});
afterEach(() => {
client.onServerShutdown();
});
it('reports lastInsertRowid and change counts on write', async () => {
const inserted = await client.write(
'INSERT INTO `widget` (`name`) VALUES (?)',
['spanner'],
);
expect(inserted).toEqual({
insertId: 1,
affectedRows: 1,
anyRowsAffected: true,
});
const missed = await client.write(
'UPDATE `widget` SET `name` = ? WHERE `id` = ?',
['nope', 999],
);
expect(missed).toMatchObject({
affectedRows: 0,
anyRowsAffected: false,
});
});
it('binds booleans as sqlite integers', async () => {
await client.write(
'INSERT INTO `widget` (`name`, `enabled`) VALUES (?, ?)',
['toggled', true],
);
await client.write(
'INSERT INTO `widget` (`name`, `enabled`) VALUES (?, ?)',
['untoggled', false],
);
await expect(
client.read('SELECT `name`, `enabled` FROM `widget` ORDER BY `id`'),
).resolves.toEqual([
{ name: 'toggled', enabled: 1 },
{ name: 'untoggled', enabled: 0 },
]);
});
it('rewrites now() into the sqlite equivalent', async () => {
await client.write(
'INSERT INTO `widget` (`name`, `seen_at`) VALUES (?, NOW())',
['stamped'],
);
const [row] = await client.read(
'SELECT `seen_at` FROM `widget` WHERE `name` = ?',
['stamped'],
);
expect(row.seen_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
});
it('generates an INSERT from a data object', async () => {
await client.insert('widget', { name: 'generated', enabled: true });
await expect(
client.read('SELECT `name`, `enabled` FROM `widget`'),
).resolves.toEqual([{ name: 'generated', enabled: 1 }]);
});
it('primary-reads through the same single-node connection', async () => {
await client.write('INSERT INTO `widget` (`name`) VALUES (?)', ['p']);
await expect(
client.pread('SELECT `name` FROM `widget`'),
).resolves.toEqual([{ name: 'p' }]);
});
it('applies a batch write atomically', async () => {
await client.batchWrite([
{
statement:
'INSERT INTO `widget` (`name`, `enabled`) VALUES (?, ?)',
values: ['one', true],
},
{
statement: 'INSERT INTO `widget` (`name`) VALUES (?)',
values: ['two'],
},
]);
await expect(
client.read('SELECT `name` FROM `widget` ORDER BY `id`'),
).resolves.toEqual([{ name: 'one' }, { name: 'two' }]);
});
it('rolls the whole batch back when one statement fails', async () => {
await expect(
client.batchWrite([
{
statement: 'INSERT INTO `widget` (`name`) VALUES (?)',
values: ['kept-if-broken'],
},
{
statement: 'INSERT INTO `nonexistent` (`name`) VALUES (?)',
values: ['boom'],
},
]),
).rejects.toThrow(/no such table/i);
await expect(
client.read('SELECT `name` FROM `widget`'),
).resolves.toEqual([]);
});
it('surfaces sqlite errors for malformed SQL', async () => {
await expect(client.read('SELEC oops')).rejects.toThrow(
/syntax error/i,
);
});
it('closes the database on shutdown', async () => {
const closable = await bootClient();
closable.onServerShutdown();
await expect(closable.read('SELECT 1')).rejects.toThrow(
'The database connection is not open',
);
});
});
// Single-node engines have no replica to race, so `tryHardRead` must not
// issue the query twice — the base-class default fires `pread()` and
// `read()` in parallel, which on sqlite is the same connection.
describe('SqliteDatabaseClient — tryHardRead', () => {
let client: SqliteDatabaseClient;
beforeEach(async () => {
client = await bootClient();
await client.write(
'CREATE TABLE `widget` (`id` INTEGER PRIMARY KEY, `name` TEXT)',
);
});
afterEach(() => {
client.onServerShutdown();
});
it('executes the statement exactly once', async () => {
await client.write('INSERT INTO `widget` (`name`) VALUES (?)', ['one']);
const readSpy = vi.spyOn(client, 'read');
const preadSpy = vi.spyOn(client, 'pread');
await expect(
client.tryHardRead('SELECT `name` FROM `widget`'),
).resolves.toEqual([{ name: 'one' }]);
expect(readSpy).toHaveBeenCalledTimes(1);
expect(preadSpy).not.toHaveBeenCalled();
});
it('executes the statement exactly once when it matches no rows', async () => {
const readSpy = vi.spyOn(client, 'read');
const preadSpy = vi.spyOn(client, 'pread');
await expect(
client.tryHardRead('SELECT `name` FROM `widget`'),
).resolves.toEqual([]);
expect(readSpy).toHaveBeenCalledTimes(1);
expect(preadSpy).not.toHaveBeenCalled();
});
it('throws from requireRead when nothing matches', async () => {
await expect(
client.requireRead(
'SELECT `name` FROM `widget` WHERE `id` = ?',
[42],
),
).rejects.toThrow('required read returned no rows');
});
it('returns the rows from requireRead when something matches', async () => {
await client.write('INSERT INTO `widget` (`name`) VALUES (?)', ['ok']);
await expect(
client.requireRead('SELECT `name` FROM `widget`'),
).resolves.toEqual([{ name: 'ok' }]);
});
});
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -27,9 +27,9 @@ import { AbstractDatabaseClient, type WriteResult } from './DatabaseClient';
const MIGRATIONS_DIR = resolve(__dirname, './migrations/sqlite');
/**
* Ordered list of [threshold_version, files[]] pairs.
* A database whose `user_version` is <= threshold_version will have
* the corresponding files applied.
* Ordered list of [threshold_version, files[]] pairs. A database whose
* `user_version` is <= threshold_version will have the corresponding files
* applied.
*/
const AVAILABLE_MIGRATIONS: [number, string[]][] = [
[-1, ['0001_create-tables.sql', '0002_add-default-apps.sql']],
@@ -94,6 +94,12 @@ const AVAILABLE_MIGRATIONS: [number, string[]][] = [
[57, ['0062_blocked-app-origins.sql']],
[58, ['0063_add_suspended_reason.sql']],
[59, ['0064_abuse-moderation-events.sql']],
[60, ['0065_app-feedback.sql']],
[61, ['0066_owned-email-unique.sql']],
[62, ['0067_share_entries.sql']],
[63, ['0068_referral-code-unique.sql']],
[64, ['0069_user-block.sql']],
[65, ['0070_drop-orphaned-default-groups.sql']],
];
export class SqliteDatabaseClient extends AbstractDatabaseClient {
@@ -158,6 +164,16 @@ export class SqliteDatabaseClient extends AbstractDatabaseClient {
return this.read(query, params);
}
override async tryHardRead(
query: string,
params: unknown[] = [],
): Promise<Record<string, unknown>[]> {
// No replica to race, so the base class's parallel
// primary-plus-replica read would run the same statement twice on
// the one connection.
return this.read(query, params);
}
@Span('db.write', (query: string) => ({ 'db.statement': query }))
override async write(
query: string,
+4 -4
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -33,9 +33,9 @@ import { PostgresDatabaseClient } from './PostgresDatabaseClient';
import { SqliteDatabaseClient } from './SqliteDatabaseClient';
/**
* Factory class registered in `puterClients`. PuterServer calls
* `new DatabaseClientFactory(config)` — the constructor returns the
* concrete subclass selected by `config.database.engine`.
* Factory class registered in `puterClients`. PuterServer calls `new
* DatabaseClientFactory(config)` — the constructor returns the concrete
* subclass selected by `config.database.engine`.
*/
export const DatabaseClientFactory = class DatabaseClientFactory {
constructor(config: IConfig) {
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -0,0 +1,48 @@
-- 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/>.
-- User-to-developer feedback for apps that opt in. Mirrors SQLite migration
-- 0065. Opt-in is the new `apps.feedback_enabled` column (developer-writable
-- through the regular `puter.apps.update` path). Each row of `app_feedback`
-- is one message a signed-in user submitted through the GUI feedback dialog;
-- a copy is emailed to the app owner unless the per-app daily email cap
-- suppressed it (`email_sent` records which). `app_uid` is denormalized
-- alongside `app_id` so rows stay attributable after an app is deleted.
-- `created_at` is unix seconds.
--
-- Idempotent: the column add uses _puter_add_col (defined in mig_1, which
-- always runs first) and the table uses `CREATE TABLE IF NOT EXISTS`, so the
-- directory can replay safely.
CALL _puter_add_col('apps', 'feedback_enabled', '`feedback_enabled` tinyint(1) DEFAULT ''0''');
CREATE TABLE IF NOT EXISTS `app_feedback` (
`id` INT NOT NULL AUTO_INCREMENT,
`uid` CHAR(36) NOT NULL,
`app_id` INT NOT NULL,
`app_uid` CHAR(40) NOT NULL,
`user_id` INT NOT NULL,
`message` TEXT NOT NULL,
`source_env` VARCHAR(16) DEFAULT NULL,
`source_origin` VARCHAR(2048) DEFAULT NULL,
`email_sent` TINYINT(1) NOT NULL DEFAULT 0,
`created_at` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_app_feedback_uid` (`uid`),
KEY `idx_app_feedback_app_created` (`app_id`, `created_at`),
KEY `idx_app_feedback_user_created` (`user_id`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,128 @@
-- 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/>.
-- Enforce "at most one account owns an email address". Mirrors SQLite
-- migration 0066.
--
-- `user.email` is deliberately not UNIQUE: several rows may legitimately hold
-- the same address while unconfirmed (admin-provisioned placeholders, signups
-- that were never confirmed, temp accounts on their way to becoming real). What
-- must never happen is two rows both *owning* an address — owning meaning the
-- row is confirmed, or holds a password and so can drive password recovery for
-- that inbox.
--
-- Signup, save-account, change-email, OIDC and admin provisioning each check for
-- an owner before writing, but a check and an insert are not one operation: two
-- requests can both read "free" and both write. This index is what actually
-- holds the invariant; the application checks just produce a nicer error most of
-- the time.
--
-- SQLite expresses that with a partial index. MySQL has none, so the predicate
-- lives in a generated column that evaluates to NULL for every row that does not
-- own its address — and NULLs do not collide in an InnoDB unique index, which is
-- exactly the "unlimited unconfirmed placeholders" behaviour we need.
--
-- The column is VIRTUAL, not STORED, on purpose: adding a stored generated
-- column rebuilds the table, while a virtual one is a metadata-only change and
-- the index that follows builds INPLACE. On a `user` table of any size with
-- read replicas attached, that is the difference between a routine change and an
-- outage. The ALGORITHM/LOCK clauses are spelled out so a server that cannot
-- honour them refuses the statement instead of quietly copying the table.
--
-- Matching is on the canonical address so provider aliases
-- (`[email protected]` vs `[email protected]`) collide. `clean_email` is
-- written on every modern write path; the COALESCE covers rows old enough to
-- predate the column. Run the `clean_email` backfill before this migration or
-- alias collisions among those rows go unnoticed.
--
-- Idempotent: both steps are guarded on INFORMATION_SCHEMA so the directory
-- replays safely.
--
-- If the index creation fails with ER_DUP_ENTRY, the DB already contains
-- duplicate owners. Collapse them first (admin → One-off Jobs → Collapse
-- Duplicate Emails) — there is no safe automatic merge of two accounts.
DROP PROCEDURE IF EXISTS _puter_add_owned_email;
DELIMITER //
CREATE PROCEDURE _puter_add_owned_email()
BEGIN
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user'
AND COLUMN_NAME = 'owned_email'
) THEN
ALTER TABLE `user`
ADD COLUMN `owned_email` VARCHAR(256)
CHARACTER SET latin1 COLLATE latin1_swedish_ci
GENERATED ALWAYS AS (
CASE
WHEN `email` IS NOT NULL
AND (`email_confirmed` = 1 OR `password` IS NOT NULL)
THEN COALESCE(`clean_email`, LOWER(`email`))
ELSE NULL
END
) VIRTUAL,
ALGORITHM=INSTANT;
END IF;
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user'
AND INDEX_NAME = 'idx_user_owned_email'
) THEN
ALTER TABLE `user`
ADD UNIQUE KEY `idx_user_owned_email` (`owned_email`),
ALGORITHM=INPLACE, LOCK=NONE;
END IF;
END//
DELIMITER ;
CALL _puter_add_owned_email();
DROP PROCEDURE IF EXISTS _puter_add_owned_email;
-- One Puter account per external identity. OIDCStore.link already assumes this
-- constraint exists — it catches the unique violation to tell "re-linking the
-- same account" apart from "this sub belongs to someone else" — but the table
-- never actually had it, so two concurrent first-time logins could each create
-- an account and each link the same sub. Subsequent logins then resolved to
-- whichever row came back first.
--
-- Dedupe `user_oidc_providers` before applying this: keep the lowest `id` per
-- (provider, provider_sub) and point it at the account the collapse job kept.
DROP PROCEDURE IF EXISTS _puter_add_oidc_sub_unique;
DELIMITER //
CREATE PROCEDURE _puter_add_oidc_sub_unique()
BEGIN
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_oidc_providers'
AND INDEX_NAME = 'idx_user_oidc_provider_sub'
) THEN
ALTER TABLE `user_oidc_providers`
ADD UNIQUE KEY `idx_user_oidc_provider_sub` (`provider`, `provider_sub`);
END IF;
END//
DELIMITER ;
CALL _puter_add_oidc_sub_unique();
DROP PROCEDURE IF EXISTS _puter_add_oidc_sub_unique;
@@ -0,0 +1,106 @@
-- 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/>.
-- Grow `share` from a pending-email-invite table into the index of active
-- shares. See sqlite/0067_share_entries.sql for the column rationale.
--
-- Idempotent: columns go through _puter_add_col (from mig_1), indexes and
-- foreign keys through the guarded procedure below. There is no per-file
-- applied-state tracking, so every statement must tolerate a re-run.
CALL _puter_add_col('share', 'holder_user_id', '`holder_user_id` int unsigned DEFAULT NULL');
CALL _puter_add_col('share', 'fsentry_id', '`fsentry_id` int unsigned DEFAULT NULL');
CALL _puter_add_col('share', 'mode', '`mode` varchar(20) DEFAULT NULL');
CALL _puter_add_col('share', 'applied_at', '`applied_at` timestamp NULL DEFAULT NULL');
DROP PROCEDURE IF EXISTS _puter_add_share_index_constraints;
DELIMITER //
CREATE PROCEDURE _puter_add_share_index_constraints()
BEGIN
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'share'
AND INDEX_NAME = 'idx_share_holder'
) THEN
ALTER TABLE `share` ADD INDEX `idx_share_holder` (`holder_user_id`, `id`);
END IF;
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'share'
AND INDEX_NAME = 'idx_share_fsentry'
) THEN
ALTER TABLE `share` ADD INDEX `idx_share_fsentry` (`fsentry_id`);
END IF;
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'share'
AND INDEX_NAME = 'idx_share_holder_entry_issuer'
) THEN
ALTER TABLE `share` ADD UNIQUE INDEX `idx_share_holder_entry_issuer`
(`holder_user_id`, `fsentry_id`, `issuer_user_id`);
END IF;
-- Retiring a deleted node's grants looks them up by permission text
-- (`fs:<uuid>` and `fs:<uuid>:%`); the subject lives in that text rather
-- than a column, so no foreign key can cascade it. The primary key is
-- (issuer, holder, permission), which never puts `permission` first, so
-- without this both the equality and the left-anchored LIKE degrade to a
-- full scan on the delete path. The column is ascii varchar(255), well
-- inside InnoDB's key limit, so it is indexed whole.
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_to_user_permissions'
AND INDEX_NAME = 'idx_user_to_user_permissions_permission'
) THEN
ALTER TABLE `user_to_user_permissions`
ADD INDEX `idx_user_to_user_permissions_permission` (`permission`);
END IF;
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'share'
AND CONSTRAINT_NAME = 'share_holder_user_fk'
) THEN
ALTER TABLE `share` ADD CONSTRAINT `share_holder_user_fk`
FOREIGN KEY (`holder_user_id`) REFERENCES `user` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE;
END IF;
-- The cascade that retires a share with its file.
IF NOT EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'share'
AND CONSTRAINT_NAME = 'share_fsentry_fk'
) THEN
ALTER TABLE `share` ADD CONSTRAINT `share_fsentry_fk`
FOREIGN KEY (`fsentry_id`) REFERENCES `fsentries` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE;
END IF;
END//
DELIMITER ;
CALL _puter_add_share_index_constraints();
DROP PROCEDURE IF EXISTS _puter_add_share_index_constraints;
@@ -0,0 +1,35 @@
-- 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/>.
-- One user refusing contact from another. See sqlite/0068_user-block.sql for
-- the rationale. `created_at` is unix seconds.
--
-- Idempotent: `CREATE TABLE IF NOT EXISTS` with the indexes declared inline,
-- so the directory can replay safely.
CREATE TABLE IF NOT EXISTS `user_block` (
`id` INT NOT NULL AUTO_INCREMENT,
`blocker_user_id` INT UNSIGNED NOT NULL,
`blocked_user_id` INT UNSIGNED NOT NULL,
`created_at` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_user_block_pair` (`blocker_user_id`, `blocked_user_id`),
CONSTRAINT `fk_user_block_blocker` FOREIGN KEY (`blocker_user_id`)
REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_user_block_blocked` FOREIGN KEY (`blocked_user_id`)
REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,61 @@
-- 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/>.
-- Widen `notification.shown` and `notification.acknowledged` to hold the unix
-- second the store has been writing to them since the backend rework.
--
-- Both arrived from the v1 schema as `tinyint(1)`, where they were flags. The
-- rework changed the writes to timestamps and sqlite (`INTEGER`) and postgres
-- (`bigint`) took them; only mysql was left too narrow, so every `markShown`
-- and `markAcknowledged` there fails with ER_WARN_DATA_OUT_OF_RANGE and the
-- column stays NULL. Dismissing a notification therefore never sticks, and one
-- already delivered is re-sent on every reconnect.
--
-- No backfill: every reader tests `IS NULL` / `IS NOT NULL` only, so a legacy
-- `1` keeps meaning "yes" once widened.
--
-- Guarded on the current type rather than run unconditionally. Changing a
-- column type copies the table, and this one grows without bound — a migration
-- directory that replays on every boot must not rebuild it every time.
DROP PROCEDURE IF EXISTS _puter_widen_notification_stamps;
DELIMITER //
CREATE PROCEDURE _puter_widen_notification_stamps()
BEGIN
IF EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'notification'
AND COLUMN_NAME = 'shown'
AND DATA_TYPE = 'tinyint'
) THEN
ALTER TABLE `notification` MODIFY `shown` BIGINT DEFAULT NULL;
END IF;
IF EXISTS (
SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'notification'
AND COLUMN_NAME = 'acknowledged'
AND DATA_TYPE = 'tinyint'
) THEN
ALTER TABLE `notification` MODIFY `acknowledged` BIGINT DEFAULT NULL;
END IF;
END //
DELIMITER ;
CALL _puter_widen_notification_stamps();
DROP PROCEDURE IF EXISTS _puter_widen_notification_stamps;
@@ -0,0 +1,22 @@
-- Drops three groups that no code has ever read: `freeai`, `experimental` and
-- `dangerous`. No migration creates them — they were added by hand back when
-- hardcoded permissions were keyed by group name. That map is now a flat
-- per-user floor (`default_user_permissions` in data/hardcoded-permissions.js),
-- so a group nothing looks up grants nothing, and the rows are dead weight.
--
-- Guarded, and deliberately so: `user_to_group_permissions.group_id` and
-- `jct_user_group.group_id` both cascade on delete, so removing a group that
-- still carries permissions or members would silently revoke them from every
-- member. Only a group with neither is dropped. A group that survives this
-- migration has dependents and needs a deliberate decision, not a sweep --
-- query `user_to_group_permissions` by `group_id` to see what it holds.
--
-- The joins rather than `NOT IN` subqueries: MySQL will not read from the table
-- it is deleting from inside a subquery on the same statement.
DELETE g FROM `group` g
LEFT JOIN `user_to_group_permissions` p ON p.`group_id` = g.`id`
LEFT JOIN `jct_user_group` j ON j.`group_id` = g.`id`
WHERE JSON_UNQUOTE(JSON_EXTRACT(g.`extra`, '$.name'))
IN ('freeai', 'experimental', 'dangerous')
AND p.`group_id` IS NULL
AND j.`group_id` IS NULL;
@@ -0,0 +1,40 @@
-- 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/>.
-- Enforce "at most one account owns an email address". Mirrors SQLite
-- migration 0066 and MySQL migration 21; see those for the full rationale.
--
-- In short: `user.email` is deliberately not UNIQUE because several rows may
-- hold the same address while unconfirmed. What must not happen is two rows
-- both owning it — confirmed, or holding a password and so able to drive
-- password recovery for that inbox. The application checks for an owner before
-- every write, but a check and a write are not one operation.
--
-- If this fails, the DB already contains duplicate owners; collapse them first
-- (admin → One-off Jobs → Collapse Duplicate Emails).
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_owned_email
ON "user" (COALESCE(clean_email, LOWER(email)))
WHERE email IS NOT NULL
AND (email_confirmed = TRUE OR password IS NOT NULL);
-- One Puter account per external identity. OIDCStore.link already assumes this
-- constraint exists — it catches the unique violation to tell "re-linking the
-- same account" apart from "this sub belongs to someone else" — but the table
-- never actually had it.
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_oidc_provider_sub
ON user_oidc_providers (provider, provider_sub);
@@ -0,0 +1,42 @@
-- 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/>.
-- Grow share from a pending-email-invite table into the index of active
-- shares. See sqlite/0067_share_entries.sql for the column rationale.
ALTER TABLE share
ADD COLUMN IF NOT EXISTS holder_user_id integer
REFERENCES "user" (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD COLUMN IF NOT EXISTS fsentry_id integer
REFERENCES fsentries (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD COLUMN IF NOT EXISTS mode varchar(20),
ADD COLUMN IF NOT EXISTS applied_at timestamp;
CREATE INDEX IF NOT EXISTS idx_share_holder
ON share (holder_user_id, id);
CREATE INDEX IF NOT EXISTS idx_share_fsentry
ON share (fsentry_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_share_holder_entry_issuer
ON share (holder_user_id, fsentry_id, issuer_user_id);
-- Retiring a deleted node's grants looks them up by permission text, and the
-- primary key is (issuer, holder, permission) — `permission` is never the
-- leading column, so the delete path would otherwise scan the table. The
-- text_pattern_ops class is what makes the left-anchored LIKE a range scan
-- under a non-C collation; plain equality still uses it.
CREATE INDEX IF NOT EXISTS idx_user_to_user_permissions_permission
ON user_to_user_permissions (permission text_pattern_ops);
@@ -0,0 +1,33 @@
-- 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/>.
-- One user refusing contact from another. See sqlite/0068_user-block.sql for
-- the rationale. `created_at` is unix seconds.
--
-- Idempotent via IF NOT EXISTS.
CREATE TABLE IF NOT EXISTS user_block (
id BIGSERIAL PRIMARY KEY,
blocker_user_id integer NOT NULL
REFERENCES "user" (id) ON DELETE CASCADE ON UPDATE CASCADE,
blocked_user_id integer NOT NULL
REFERENCES "user" (id) ON DELETE CASCADE ON UPDATE CASCADE,
created_at BIGINT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_block_pair
ON user_block (blocker_user_id, blocked_user_id);
@@ -0,0 +1,20 @@
-- Drops three groups that no code has ever read: `freeai`, `experimental` and
-- `dangerous`. No migration creates them — they were added by hand back when
-- hardcoded permissions were keyed by group name. That map is now a flat
-- per-user floor (`default_user_permissions` in data/hardcoded-permissions.js),
-- so a group nothing looks up grants nothing, and the rows are dead weight.
--
-- Guarded, and deliberately so: user_to_group_permissions.group_id and
-- jct_user_group.group_id both cascade on delete, so removing a group that
-- still carries permissions or members would silently revoke them from every
-- member. Only a group with neither is dropped. A group that survives this
-- migration has dependents and needs a deliberate decision, not a sweep --
-- query user_to_group_permissions by group_id to see what it holds.
DELETE FROM "group" g
WHERE g.extra ->> 'name' IN ('freeai', 'experimental', 'dangerous')
AND NOT EXISTS (
SELECT 1 FROM user_to_group_permissions p WHERE p.group_id = g.id
)
AND NOT EXISTS (
SELECT 1 FROM jct_user_group j WHERE j.group_id = g.id
);
@@ -0,0 +1,47 @@
-- 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/>.
-- User-to-developer feedback for apps that opt in. Mirrors SQLite migration
-- 0065 / MySQL mysql_mig_20. Opt-in is the new `apps.feedback_enabled` column
-- (developer-writable through the regular `puter.apps.update` path). Each row
-- of `app_feedback` is one message a signed-in user submitted through the GUI
-- feedback dialog; a copy is emailed to the app owner unless the per-app
-- daily email cap suppressed it (`email_sent` records which). `app_uid` is
-- denormalized alongside `app_id` so rows stay attributable after an app is
-- deleted. `created_at` is unix seconds.
--
-- Idempotent via IF NOT EXISTS.
ALTER TABLE apps ADD COLUMN IF NOT EXISTS feedback_enabled boolean NOT NULL DEFAULT FALSE;
CREATE TABLE IF NOT EXISTS app_feedback (
id BIGSERIAL PRIMARY KEY,
uid CHAR(36) NOT NULL UNIQUE,
app_id BIGINT NOT NULL,
app_uid VARCHAR(40) NOT NULL,
user_id BIGINT NOT NULL,
message TEXT NOT NULL,
source_env VARCHAR(16) DEFAULT NULL,
source_origin VARCHAR(2048) DEFAULT NULL,
email_sent BOOLEAN NOT NULL DEFAULT FALSE,
created_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_app_feedback_app_created
ON app_feedback (app_id, created_at);
CREATE INDEX IF NOT EXISTS idx_app_feedback_user_created
ON app_feedback (user_id, created_at);
@@ -0,0 +1,51 @@
-- 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/>.
-- User-to-developer feedback for apps that opt in. Opt-in is the new
-- `apps.feedback_enabled` column (developer-writable through the regular
-- `puter.apps.update` path; a dedicated column rather than a `metadata` key
-- because Dev Center saves replace the whole metadata blob and would erase
-- it). Each row of `app_feedback` is one message a signed-in user submitted
-- through the GUI feedback dialog; a copy is emailed to the app owner unless
-- the per-app daily email cap suppressed it (`email_sent` records which).
-- `app_uid` is denormalized alongside `app_id` so rows stay attributable
-- after an app is deleted (abuse forensics). `source_env` is 'app' (desktop
-- dialog) or 'web' (puter.com popup opened from an external site);
-- `source_origin` is the popup opener's browser-attested origin, null for
-- desktop submissions. `created_at` is unix seconds. The (user_id,
-- created_at) and (app_id, created_at) indexes serve the sliding-window
-- rate-limit counts in AppFeedbackStore.
ALTER TABLE apps ADD COLUMN "feedback_enabled" tinyint(1) DEFAULT '0';
CREATE TABLE IF NOT EXISTS `app_feedback` (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"uid" TEXT NOT NULL UNIQUE,
"app_id" INTEGER NOT NULL,
"app_uid" TEXT NOT NULL,
"user_id" INTEGER NOT NULL,
"message" TEXT NOT NULL,
"source_env" TEXT DEFAULT NULL, -- 'app' | 'web'
"source_origin" TEXT DEFAULT NULL, -- attested opener origin (web popups)
"email_sent" INTEGER NOT NULL DEFAULT 0,
"created_at" INTEGER NOT NULL -- unix seconds
);
CREATE INDEX IF NOT EXISTS idx_app_feedback_app_created
ON `app_feedback` (`app_id`, `created_at`);
CREATE INDEX IF NOT EXISTS idx_app_feedback_user_created
ON `app_feedback` (`user_id`, `created_at`);
@@ -0,0 +1,53 @@
-- 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/>.
-- Enforce "at most one account owns an email address".
--
-- `user.email` is deliberately not UNIQUE: several rows may legitimately hold
-- the same address while unconfirmed (admin-provisioned placeholders, signups
-- that were never confirmed, temp accounts on their way to becoming real). What
-- must never happen is two rows both *owning* an address — owning meaning the
-- row is confirmed, or holds a password and so can drive password recovery for
-- that inbox.
--
-- Signup, save-account, change-email, OIDC and admin provisioning each check for
-- an owner before writing, but a check and an insert are not one operation: two
-- requests can both read "free" and both write. This index is what actually
-- holds the invariant; the application checks just produce a nicer error most of
-- the time.
--
-- Matching is on the canonical address so provider aliases
-- (`[email protected]` vs `[email protected]`) collide. `clean_email` is
-- written on every modern write path; the COALESCE covers rows old enough to
-- predate the column.
--
-- If this CREATE fails, the DB already contains duplicate owners. Collapse them
-- first (admin → One-off Jobs → Collapse Duplicate Emails) — there is no safe
-- automatic merge of two accounts.
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_owned_email
ON user(COALESCE(clean_email, lower(email)))
WHERE email IS NOT NULL
AND (email_confirmed = 1 OR password IS NOT NULL);
-- One Puter account per external identity. OIDCStore.link already assumes this
-- constraint exists — it catches the unique violation to tell "re-linking the
-- same account" apart from "this sub belongs to someone else" — but the table
-- never actually had it, so two concurrent first-time logins could each create
-- an account and each link the same sub. Subsequent logins then resolved to
-- whichever row came back first.
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_oidc_provider_sub
ON user_oidc_providers(provider, provider_sub);
@@ -0,0 +1,60 @@
-- 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/>.
-- Grow `share` from a pending-email-invite table into the index of active
-- shares. Permissions stay the source of truth for access; this is what makes
-- shares listable and gives them a lifecycle.
--
-- - `holder_user_id` : NULL while an invite awaits signup.
-- - `fsentry_id` : the shared node. ON DELETE CASCADE retires the share
-- with the file, which permissions alone don't do.
-- - `mode` : see|list|read|write|manage. Unconstrained on purpose —
-- ACLService owns the mode set and adding one shouldn't
-- need a three-dialect migration.
-- - `applied_at` : set when an invite is claimed. Claiming updates the
-- row rather than deleting it, so the share stays
-- queryable.
ALTER TABLE `share` ADD COLUMN `holder_user_id` INTEGER DEFAULT NULL
REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `share` ADD COLUMN `fsentry_id` INTEGER DEFAULT NULL
REFERENCES `fsentries` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `share` ADD COLUMN `mode` TEXT DEFAULT NULL;
ALTER TABLE `share` ADD COLUMN `applied_at` TIMESTAMP DEFAULT NULL;
-- "Shared with me", keyset-paginated: ORDER BY ends in `id` as the tiebreaker.
CREATE INDEX IF NOT EXISTS `idx_share_holder`
ON `share` (`holder_user_id`, `id`);
-- Who has access to one node — also how an owner sees a manage-delegate's
-- re-grants, which the issuer/holder permission tables can't answer.
CREATE INDEX IF NOT EXISTS `idx_share_fsentry` ON `share` (`fsentry_id`);
-- One row per (holder, node, issuer). Pending invites have a NULL
-- holder_user_id and so aren't covered here; dedup for those belongs with the
-- invite flow.
CREATE UNIQUE INDEX IF NOT EXISTS `idx_share_holder_entry_issuer`
ON `share` (`holder_user_id`, `fsentry_id`, `issuer_user_id`);
-- Retiring a deleted node's grants looks them up by permission text
-- (`fs:<uuid>` and `fs:<uuid>:%`), and the subject only lives in that text —
-- no column, so no foreign key can cascade it. The table's primary key is
-- (issuer, holder, permission), which never puts `permission` first, so
-- without this the equality and the left-anchored LIKE both degrade to a full
-- scan on the delete path. With it, each is a range scan.
CREATE INDEX IF NOT EXISTS `idx_user_to_user_permissions_permission`
ON `user_to_user_permissions` (`permission`);
@@ -0,0 +1,32 @@
-- 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/>.
-- One referral code, one account. The mysql and postgres baselines have
-- declared `user.referral_code` UNIQUE since the column was introduced; the
-- sqlite baseline only declared the column, so the invariant held on hosted
-- deployments and not on self-hosted ones.
--
-- Codes are minted by picking at random and writing, so this index is not a
-- nicety: it is what makes "did anyone already take this code" a decision the
-- database makes once, instead of a read the next mint can race. A caller that
-- loses the race sees a unique violation and picks again.
--
-- NULL is distinct from NULL in a sqlite unique index, so accounts that have
-- never asked for a code (the majority) are unaffected.
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_referral_code
ON user(referral_code)
WHERE referral_code IS NOT NULL;
@@ -0,0 +1,39 @@
-- 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/>.
-- One user refusing contact from another. Sharing is what reads it today —
-- a blocked sender's share is refused outright, and their pending invite is
-- dropped when the blocker confirms the address it was aimed at — but the
-- table is deliberately not share-specific: the same answer serves anything
-- else one person can push at another.
--
-- Rows are read on the share path by exact (blocker, blocked) pair, which the
-- unique index answers as a point lookup; the same index's leading column
-- serves "who have I blocked". `created_at` is unix seconds, matching
-- `app_feedback`.
CREATE TABLE IF NOT EXISTS `user_block` (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"blocker_user_id" INTEGER NOT NULL
REFERENCES `user` ("id") ON DELETE CASCADE ON UPDATE CASCADE,
"blocked_user_id" INTEGER NOT NULL
REFERENCES `user` ("id") ON DELETE CASCADE ON UPDATE CASCADE,
"created_at" INTEGER NOT NULL -- unix seconds
);
CREATE UNIQUE INDEX IF NOT EXISTS `idx_user_block_pair`
ON `user_block` (`blocker_user_id`, `blocked_user_id`);
@@ -0,0 +1,33 @@
-- 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/>.
-- Drops three groups that no code has ever read: `freeai`, `experimental` and
-- `dangerous`. No migration creates them — they were added by hand back when
-- hardcoded permissions were keyed by group name. That map is now a flat
-- per-user floor (`default_user_permissions` in data/hardcoded-permissions.js),
-- so a group nothing looks up grants nothing, and the rows are dead weight.
--
-- Guarded, and deliberately so: `user_to_group_permissions.group_id` and
-- `jct_user_group.group_id` both cascade on delete, so removing a group that
-- still carries permissions or members would silently revoke them from every
-- member. Only a group with neither is dropped. A group that survives this
-- migration has dependents and needs a deliberate decision, not a sweep --
-- query `user_to_group_permissions` by `group_id` to see what it holds.
DELETE FROM `group`
WHERE json_extract(`extra`, '$.name') IN ('freeai', 'experimental', 'dangerous')
AND `id` NOT IN (SELECT `group_id` FROM `user_to_group_permissions`)
AND `id` NOT IN (SELECT `group_id` FROM `jct_user_group`);
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
+38 -10
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -41,11 +41,10 @@ const RETRIABLE_ERROR_MESSAGES = [
];
/**
* Failures where the statement provably never reached the server, so a
* retry can never double-apply it — safe even for writes. Anything that
* can occur after the statement was sent (resets, protocol drops) is
* deliberately excluded: the server may have committed before the
* connection died.
* Failures where the statement provably never reached the server, so a retry
* can never double-apply it — safe even for writes. Anything that can occur
* after the statement was sent (resets, protocol drops) is deliberately
* excluded: the server may have committed before the connection died.
*/
const NEVER_SENT_ERROR_CODES = new Set([
'ECONNREFUSED',
@@ -55,14 +54,33 @@ const NEVER_SENT_ERROR_CODES = new Set([
POOL_ACQUIRE_TIMEOUT,
]);
/**
* Failures the server itself rolled back before returning. The statement did
* reach the database, so this is not `NEVER_SENT`, but InnoDB guarantees it
* left no effect — which makes a retry just as safe for writes.
*
* Only true for a _single_ statement: under autocommit each statement is its
* own transaction, so "the transaction was rolled back" means "this statement
* was rolled back". Retrying a multi-statement string on one of these would
* re-run the statements that already committed ahead of the failure.
*/
const ROLLED_BACK_ERROR_CODES = new Set([
// Deadlock — InnoDB picked this transaction as the victim and undid it.
// MySQL's own message for it is "try restarting transaction".
'ER_LOCK_DEADLOCK',
// Lock wait timeout. Rolls back the statement rather than the transaction
// unless innodb_rollback_on_timeout is set — the same thing when the
// transaction is one statement.
'ER_LOCK_WAIT_TIMEOUT',
]);
const errorCode = (error: unknown): string | undefined =>
(error as { code?: string } | null)?.code;
/**
* Transient connection-level failures worth retrying — but only for
* statements that are safe to run twice (reads). Row-level errors
* (duplicate key, constraint violations) are deterministic and never
* match.
* Transient connection-level failures worth retrying — but only for statements
* that are safe to run twice (reads). Row-level errors (duplicate key,
* constraint violations) are deterministic and never match.
*/
export const isRetriableError = (error: unknown): boolean => {
const code = errorCode(error);
@@ -76,3 +94,13 @@ export const isNeverSentError = (error: unknown): boolean => {
const code = errorCode(error);
return Boolean(code && NEVER_SENT_ERROR_CODES.has(code));
};
/**
* Lock-contention failures the server rolled back on its own. Safe to retry a
* single statement on, writes included — see `ROLLED_BACK_ERROR_CODES` for the
* one-statement precondition.
*/
export const isRolledBackError = (error: unknown): boolean => {
const code = errorCode(error);
return Boolean(code && ROLLED_BACK_ERROR_CODES.has(code));
};
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -20,12 +20,11 @@
/**
* DELIMITER-aware splitter for MySQL dump / migration files.
*
* Splits `sql` into individual statements using the active statement
* delimiter (default `;`). Recognises `DELIMITER X` lines, single-quoted
* strings, double-quoted strings, backtick-quoted identifiers, line
* comments (`-- `, `#`) and block comments (`/* ... *\/`). DELIMITER
* directives are stripped from the output (they're a client-side concept,
* not server SQL).
* Splits `sql` into individual statements using the active statement delimiter
* (default `;`). Recognises `DELIMITER X` lines, single-quoted strings,
* double-quoted strings, backtick-quoted identifiers, line comments (`-- `,
* `#`) and block comments (`/* ... *\/`). DELIMITER directives are stripped
* from the output (they're a client-side concept, not server SQL).
*
* Returns trimmed, non-empty statements without the trailing delimiter.
*/
@@ -0,0 +1,116 @@
/**
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, expect, it } from 'vitest';
import { splitPostgresStatements } from './splitPostgresStatements';
describe('splitPostgresStatements', () => {
it('splits on semicolons and trims each statement', () => {
expect(
splitPostgresStatements('SELECT 1;\n SELECT 2 ;\nSELECT 3'),
).toEqual(['SELECT 1', 'SELECT 2', 'SELECT 3']);
});
it('drops empty statements from stray semicolons', () => {
expect(splitPostgresStatements(';;SELECT 1;;')).toEqual(['SELECT 1']);
});
it('returns nothing for whitespace-only input', () => {
expect(splitPostgresStatements(' \n\t ')).toEqual([]);
});
it('keeps semicolons inside single-quoted literals', () => {
expect(
splitPostgresStatements("INSERT INTO t VALUES ('a;b'); SELECT 1"),
).toEqual(["INSERT INTO t VALUES ('a;b')", 'SELECT 1']);
});
it('handles doubled and backslash-escaped quotes in literals', () => {
expect(
splitPostgresStatements("SELECT 'it''s; fine'; SELECT 2"),
).toEqual(["SELECT 'it''s; fine'", 'SELECT 2']);
expect(splitPostgresStatements("SELECT E'a\\'; b'; SELECT 2")).toEqual([
"SELECT E'a\\'; b'",
'SELECT 2',
]);
});
it('keeps semicolons inside quoted identifiers', () => {
expect(
splitPostgresStatements('SELECT "we;ird" FROM t; SELECT 2'),
).toEqual(['SELECT "we;ird" FROM t', 'SELECT 2']);
});
it('handles a doubled quote inside a quoted identifier', () => {
expect(
splitPostgresStatements('SELECT "we""ird;x" FROM t; SELECT 2'),
).toEqual(['SELECT "we""ird;x" FROM t', 'SELECT 2']);
});
it('ignores semicolons inside line comments', () => {
expect(
splitPostgresStatements('SELECT 1 -- trailing; note\n; SELECT 2'),
).toEqual(['SELECT 1 -- trailing; note', 'SELECT 2']);
});
it('ignores semicolons inside block comments', () => {
expect(
splitPostgresStatements('SELECT /* a; b */ 1; SELECT 2'),
).toEqual(['SELECT /* a; b */ 1', 'SELECT 2']);
});
it('keeps a whole dollar-quoted function body together', () => {
const sql = [
'CREATE FUNCTION bump() RETURNS trigger AS $$',
'BEGIN',
' NEW.updated_at := now();',
' RETURN NEW;',
'END;',
'$$ LANGUAGE plpgsql;',
'SELECT 1',
].join('\n');
const statements = splitPostgresStatements(sql);
expect(statements).toHaveLength(2);
expect(statements[0]).toContain('RETURN NEW;');
expect(statements[0].endsWith('$$ LANGUAGE plpgsql')).toBe(true);
expect(statements[1]).toBe('SELECT 1');
});
it('respects a tagged dollar quote and its nested untagged pair', () => {
const sql = 'SELECT $body$ inner $$ still; inside $body$; SELECT 2';
expect(splitPostgresStatements(sql)).toEqual([
'SELECT $body$ inner $$ still; inside $body$',
'SELECT 2',
]);
});
it('treats a bare dollar sign as ordinary text', () => {
expect(splitPostgresStatements('SELECT 1 $ 2; SELECT 3')).toEqual([
'SELECT 1 $ 2',
'SELECT 3',
]);
});
it('emits an unterminated final statement', () => {
expect(
splitPostgresStatements('SELECT 1; SELECT 2 -- no newline'),
).toEqual(['SELECT 1', 'SELECT 2 -- no newline']);
});
});
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -0,0 +1,561 @@
/**
* 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/](https://www.gnu.org/licenses/).
*/
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import type { IConfig } from '../../types';
import { DDBClient } from './DDBClient';
const TABLE = 'kv-items';
const GSI = 'by-kind';
const localConfig = (): IConfig =>
({
port: 0,
extensions: [],
dynamo: { inMemory: true, bootstrapTables: true },
}) as unknown as IConfig;
/**
* The emulator reports a table as CREATING for a tick after `CreateTable`
* returns, so wait until it actually answers a read before using it.
*/
const awaitTable = async (
client: DDBClient,
table: string,
key: Record<string, unknown>,
): Promise<void> => {
for (let attempt = 0; attempt < 100; attempt++) {
try {
await client.get(table, key);
return;
} catch (error) {
if ((error as Error).name !== 'ResourceNotFoundException')
throw error;
await new Promise((resolve) => setTimeout(resolve, 20));
}
}
throw new Error(`table ${table} never became queryable`);
};
const tableSchema = {
TableName: TABLE,
KeySchema: [
{ AttributeName: 'pk', KeyType: 'HASH' as const },
{ AttributeName: 'sk', KeyType: 'RANGE' as const },
],
AttributeDefinitions: [
{ AttributeName: 'pk', AttributeType: 'S' as const },
{ AttributeName: 'sk', AttributeType: 'S' as const },
{ AttributeName: 'kind', AttributeType: 'S' as const },
],
GlobalSecondaryIndexes: [
{
IndexName: GSI,
KeySchema: [{ AttributeName: 'kind', KeyType: 'HASH' as const }],
Projection: { ProjectionType: 'ALL' as const },
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5,
},
},
],
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 },
};
describe('DDBClient — item operations', () => {
let client: DDBClient;
beforeAll(async () => {
client = new DDBClient(localConfig());
await client.createTableIfNotExists(tableSchema);
await awaitTable(client, TABLE, { pk: 'ready', sk: 'ready' });
});
it('round-trips an item and reports consumed capacity', async () => {
await client.put(TABLE, { pk: 'u1', sk: 'profile', name: 'ada' });
const result = await client.get(TABLE, { pk: 'u1', sk: 'profile' });
expect(result.Item).toEqual({ pk: 'u1', sk: 'profile', name: 'ada' });
expect(result.ConsumedCapacity?.TableName).toBe(TABLE);
});
it('returns no Item for a key that does not exist', async () => {
const result = await client.get(TABLE, { pk: 'nobody', sk: 'here' });
expect(result.Item).toBeUndefined();
});
it('honours a strongly consistent read', async () => {
await client.put(TABLE, { pk: 'u2', sk: 'profile', name: 'grace' });
const result = await client.get(
TABLE,
{ pk: 'u2', sk: 'profile' },
true,
);
expect(result.Item?.name).toBe('grace');
});
it('applies an update expression and returns the new item', async () => {
await client.put(TABLE, { pk: 'u3', sk: 'counter', hits: 1 });
const updated = await client.update(
TABLE,
{ pk: 'u3', sk: 'counter' },
'SET #h = :next',
{ ':next': 5 },
{ '#h': 'hits' },
);
expect(updated.Attributes).toMatchObject({ hits: 5 });
});
it('supports an update expression with no values or names', async () => {
await client.put(TABLE, { pk: 'u4', sk: 'doc', stale: true });
const updated = await client.update(
TABLE,
{ pk: 'u4', sk: 'doc' },
'REMOVE stale',
);
expect(updated.Attributes).toEqual({ pk: 'u4', sk: 'doc' });
});
it('deletes an item', async () => {
await client.put(TABLE, { pk: 'u5', sk: 'temp' });
await client.del(TABLE, { pk: 'u5', sk: 'temp' });
const result = await client.get(TABLE, { pk: 'u5', sk: 'temp' });
expect(result.Item).toBeUndefined();
});
it('fetches keys from several tables in one batch', async () => {
await client.put(TABLE, { pk: 'b1', sk: 'a', v: 1 });
await client.put(TABLE, { pk: 'b1', sk: 'b', v: 2 });
const result = await client.batchGet([
{ table: TABLE, items: { pk: 'b1', sk: 'a' } },
{ table: TABLE, items: { pk: 'b1', sk: 'b' } },
]);
const values = (result.Responses?.[TABLE] ?? [])
.map((item) => item.v as number)
.sort();
expect(values).toEqual([1, 2]);
});
});
describe('DDBClient — queries', () => {
let client: DDBClient;
beforeAll(async () => {
client = new DDBClient(localConfig());
await client.createTableIfNotExists(tableSchema);
await awaitTable(client, TABLE, { pk: 'ready', sk: 'ready' });
for (const sk of ['post#1', 'post#2', 'post#3', 'note#1']) {
await client.put(TABLE, {
pk: 'q1',
sk,
kind: sk.split('#')[0],
size: sk === 'post#2' ? 10 : 1,
});
}
});
it('queries by partition key', async () => {
const result = await client.query(TABLE, { pk: 'q1' });
expect(result.Items).toHaveLength(4);
expect(result.ConsumedCapacity?.TableName).toBe(TABLE);
});
it('narrows the sort key with begins_with', async () => {
const result = await client.query(
TABLE,
{ pk: 'q1' },
0,
undefined,
'',
false,
{ beginsWith: { key: 'sk', value: 'post#' } },
);
expect(result.Items?.map((item) => item.sk)).toEqual([
'post#1',
'post#2',
'post#3',
]);
});
it('ignores an empty begins_with value', async () => {
const result = await client.query(
TABLE,
{ pk: 'q1' },
0,
undefined,
'',
false,
{ beginsWith: { key: 'sk', value: '' } },
);
expect(result.Items).toHaveLength(4);
});
it('applies a filter expression with its own names and values', async () => {
const result = await client.query(
TABLE,
{ pk: 'q1' },
0,
undefined,
'',
false,
{
filter: {
expression: '#s > :min',
names: { '#s': 'size' },
values: { ':min': 5 },
},
},
);
expect(result.Items?.map((item) => item.sk)).toEqual(['post#2']);
});
it('counts without returning items', async () => {
const result = await client.query(
TABLE,
{ pk: 'q1' },
0,
undefined,
'',
false,
{ select: 'COUNT' },
);
expect(result.Count).toBe(4);
expect(result.Items).toBeUndefined();
});
it('pages through results with the last evaluated key', async () => {
const seen: string[] = [];
let pageKey: Record<string, unknown> | undefined;
let pages = 0;
do {
const page = await client.query(TABLE, { pk: 'q1' }, 2, pageKey);
pages += 1;
expect(page.Items?.length).toBeLessThanOrEqual(2);
for (const item of page.Items ?? []) seen.push(item.sk as string);
pageKey = page.LastEvaluatedKey;
} while (pageKey && pages < 10);
expect(pages).toBeGreaterThan(1);
expect(new Set(seen).size).toBe(4);
});
it('queries a secondary index', async () => {
const result = await client.query(
TABLE,
{ kind: 'note' },
0,
undefined,
GSI,
);
expect(result.Items?.map((item) => item.sk)).toEqual(['note#1']);
});
});
describe('DDBClient — batch writes', () => {
let client: DDBClient;
beforeAll(async () => {
client = new DDBClient(localConfig());
await client.createTableIfNotExists(tableSchema);
await awaitTable(client, TABLE, { pk: 'ready', sk: 'ready' });
});
it('reports no consumed capacity for an empty batch', async () => {
await expect(client.batchPut([])).resolves.toEqual({
ConsumedCapacity: [],
});
});
it('splits a batch larger than the service limit into chunks', async () => {
const params = Array.from({ length: 60 }, (_, index) => ({
table: TABLE,
item: { pk: 'bulk', sk: `item-${index}`, index },
}));
const result = await client.batchPut(params);
expect(result.ConsumedCapacity).toHaveLength(1);
expect(result.ConsumedCapacity[0].TableName).toBe(TABLE);
expect(result.ConsumedCapacity[0].CapacityUnits).toBeGreaterThan(0);
const stored = await client.query(TABLE, { pk: 'bulk' });
expect(stored.Items).toHaveLength(60);
});
it('reports no consumed capacity for an empty delete batch', async () => {
await expect(client.batchDel([])).resolves.toEqual({
ConsumedCapacity: [],
});
});
it('batch-deletes across chunks, leaving unrelated items alone', async () => {
const items = Array.from({ length: 30 }, (_, index) => ({
table: TABLE,
item: { pk: 'bulk-del', sk: `item-${index}`, index },
}));
await client.batchPut(items);
// Delete all but the last item — 29 keys still exercises chunking
// paths shared with batchPut while proving deletion is targeted.
const result = await client.batchDel(
items.slice(0, -1).map(({ table, item }) => ({
table,
key: { pk: item.pk, sk: item.sk },
})),
);
expect(result.ConsumedCapacity).toHaveLength(1);
expect(result.ConsumedCapacity[0].TableName).toBe(TABLE);
const stored = await client.query(TABLE, { pk: 'bulk-del' });
expect(stored.Items?.map((item) => item.sk)).toEqual(['item-29']);
});
});
describe('DDBClient — expired item sweep', () => {
it('deletes only the items past their ttl when the table already existed', async () => {
const client = new DDBClient(localConfig());
const table = 'ttl-items';
const schema = {
TableName: table,
KeySchema: [{ AttributeName: 'pk', KeyType: 'HASH' as const }],
AttributeDefinitions: [
{ AttributeName: 'pk', AttributeType: 'S' as const },
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5,
},
};
await client.createTableIfNotExists(schema, 'expireAt');
await awaitTable(client, table, { pk: 'ready' });
const now = Math.floor(Date.now() / 1000);
await client.put(table, { pk: 'stale', expireAt: now - 60 });
await client.put(table, { pk: 'fresh', expireAt: now + 3600 });
await client.put(table, { pk: 'eternal' });
// Second call finds the table in use, so the sweep runs.
await client.createTableIfNotExists(schema, 'expireAt');
expect((await client.get(table, { pk: 'stale' })).Item).toBeUndefined();
expect((await client.get(table, { pk: 'fresh' })).Item).toBeDefined();
expect((await client.get(table, { pk: 'eternal' })).Item).toBeDefined();
});
});
describe('DDBClient — expired item sweep on an empty table', () => {
it('completes without deleting anything', async () => {
const client = new DDBClient(localConfig());
const table = 'ttl-empty';
const schema = {
TableName: table,
KeySchema: [{ AttributeName: 'pk', KeyType: 'HASH' as const }],
AttributeDefinitions: [
{ AttributeName: 'pk', AttributeType: 'S' as const },
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5,
},
};
await client.createTableIfNotExists(schema, 'expireAt');
await awaitTable(client, table, { pk: 'ready' });
await expect(
client.createTableIfNotExists(schema, 'expireAt'),
).resolves.toBeUndefined();
});
});
describe('DDBClient — credentialled configuration', () => {
it('refuses an aws config that is missing a key', () => {
expect(
() =>
new DDBClient({
port: 0,
extensions: [],
dynamo: { aws: { access_key: 'only-one' } },
} as unknown as IConfig),
).toThrow('requires both `access_key` and `secret_key`');
});
it('skips table creation on a managed deployment', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const client = new DDBClient({
port: 0,
extensions: [],
dynamo: {
aws: { access_key: 'a', secret_key: 'b', region: 'us-west-2' },
endpoint: 'http://127.0.0.1:1',
},
} as unknown as IConfig);
// Would fail against the unreachable endpoint if it actually tried.
await client.createTableIfNotExists(tableSchema);
expect(warn).toHaveBeenCalledWith(
expect.stringContaining(
'Creating DynamoDB tables is disabled by default',
),
);
warn.mockRestore();
});
it('rebinds an aws-credentialled client on recreate', async () => {
const client = new DDBClient({
port: 0,
extensions: [],
dynamo: {
aws: { access_key: 'a', secret_key: 'b' },
endpoint: 'http://127.0.0.1:1',
},
} as unknown as IConfig);
await expect(client.recreateClient()).resolves.toBeUndefined();
});
it('rebinds the underlying client on recreate', async () => {
const client = new DDBClient(localConfig());
await client.createTableIfNotExists(tableSchema);
await awaitTable(client, TABLE, { pk: 'ready', sk: 'ready' });
await client.put(TABLE, { pk: 'recreate', sk: 'a', v: 1 });
await client.recreateClient();
// Same in-memory store: the recreated client sees earlier writes.
const result = await client.get(TABLE, { pk: 'recreate', sk: 'a' });
expect(result.Item?.v).toBe(1);
});
});
// Unprocessed items are a throttling signal the emulator never produces, so
// the retry loop is driven against a stub speaking the DynamoDB wire format.
describe('DDBClient — unprocessed batch items', () => {
let server: Server;
let endpoint: string;
let responses: unknown[];
let requestCount = 0;
beforeAll(async () => {
server = createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const next = responses.shift() ?? {};
requestCount += 1;
res.writeHead(200, {
'content-type': 'application/x-amz-json-1.0',
});
res.end(JSON.stringify(next));
});
});
await new Promise<void>((resolve) =>
server.listen(0, '127.0.0.1', resolve),
);
endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
const stubClient = () =>
new DDBClient({
port: 0,
extensions: [],
dynamo: {
aws: { access_key: 'a', secret_key: 'b', region: 'us-west-2' },
endpoint,
},
} as unknown as IConfig);
const unprocessed = (pk: string) => ({
UnprocessedItems: {
[TABLE]: [{ PutRequest: { Item: { pk: { S: pk } } } }],
},
ConsumedCapacity: [{ TableName: TABLE, CapacityUnits: 1 }],
});
it('retries the leftover items and sums capacity across attempts', async () => {
requestCount = 0;
responses = [
unprocessed('retry-me'),
{
UnprocessedItems: {},
ConsumedCapacity: [{ TableName: TABLE, CapacityUnits: 2 }],
},
];
const result = await stubClient().batchPut([
{ table: TABLE, item: { pk: 'retry-me' } },
]);
expect(requestCount).toBe(2);
expect(result.ConsumedCapacity).toEqual([
{ TableName: TABLE, CapacityUnits: 3 },
]);
});
it('gives up with a bad-request error when items never drain', async () => {
requestCount = 0;
responses = Array.from({ length: 12 }, () => unprocessed('stuck'));
await expect(
stubClient().batchPut([{ table: TABLE, item: { pk: 'stuck' } }]),
).rejects.toMatchObject({
statusCode: 400,
legacyCode: 'bad_request',
message: 'Failed to batch write all items to DynamoDB',
});
// One initial attempt plus the full retry budget.
expect(requestCount).toBe(9);
}, 30_000);
it('tolerates a response that reports no capacity at all', async () => {
requestCount = 0;
responses = [{ UnprocessedItems: {} }];
await expect(
stubClient().batchPut([{ table: TABLE, item: { pk: 'quiet' } }]),
).resolves.toEqual({ ConsumedCapacity: [] });
expect(requestCount).toBe(1);
});
it('ignores capacity entries with no table name', async () => {
requestCount = 0;
responses = [
{
UnprocessedItems: {},
ConsumedCapacity: [{ CapacityUnits: 7 }],
},
];
await expect(
stubClient().batchPut([{ table: TABLE, item: { pk: 'anon' } }]),
).resolves.toEqual({ ConsumedCapacity: [] });
});
});
+147 -42
View File
@@ -1,21 +1,20 @@
/**
/*
* 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.
* 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.
* 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/](https://www.gnu.org/licenses/).
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {
@@ -46,6 +45,11 @@ import { HttpError } from '../../core/http';
import type { IConfig, IDynamoConfig } from '../../types';
import { Span } from '../../util/span.js';
import { PuterClient } from '../types';
import {
clampStoredNumber,
isRepairableMarshallError,
repairForMarshall,
} from './marshallRepair.js';
const LOCAL_DYNAMO_MEMORY_PREFIX = ':memory:';
const localDynaliteEndpointPromises = new Map<string, Promise<string>>();
@@ -115,6 +119,49 @@ const sleep = async (ms: number) => {
await new Promise((resolve) => setTimeout(resolve, ms));
};
// One caller writing an out-of-range number usually keeps doing it, so the
// warning is per-target and throttled rather than one line per write.
const REPAIR_WARNING_INTERVAL_MS = 60_000;
const lastRepairWarningAt = new Map<string, number>();
const warnRepaired = (target: string, message: string): void => {
const now = Date.now();
const lastWarnedAt = lastRepairWarningAt.get(target) ?? 0;
if (now - lastWarnedAt < REPAIR_WARNING_INTERVAL_MS) return;
lastRepairWarningAt.set(target, now);
console.warn(
`[ddb] clamped an out-of-range value in ${target}: ${message}`,
);
};
/**
* Send a write, and if the payload was rejected while being encoded for a value
* the store cannot represent, clamp it and send it once more.
*
* Nothing is inspected on the way in: the payload of a successful write is
* never walked, so this costs one `try` on the hot path. The repair only runs
* on the failure, and only retries when it actually changed something —
* otherwise the original error stands.
*/
const sendRepairingValues = async <TPayload, TResult>(
payload: TPayload,
send: (payload: TPayload) => Promise<TResult>,
describe: () => string,
): Promise<TResult> => {
try {
return await send(payload);
} catch (error) {
if (!isRepairableMarshallError(error)) throw error;
const repaired = repairForMarshall(payload);
if (!repaired.changed) throw error;
warnRepaired(describe(), (error as Error).message);
return send(repaired.value as TPayload);
}
};
export class DDBClient extends PuterClient {
#documentClient: DynamoDBDocumentClient | null = null;
#localInitPromise: Promise<void> | null = null;
@@ -172,14 +219,19 @@ export class DDBClient extends PuterClient {
@Span('ddb.put', (table: string) => ({ 'db.table': table }))
async put<T extends Record<string, unknown>>(table: string, item: T) {
const command = new PutCommand({
TableName: table,
Item: item,
ReturnConsumedCapacity: 'TOTAL',
});
const client = await this.#getDocumentClient();
return client.send(command);
return sendRepairingValues(
item,
(itemToWrite) =>
client.send(
new PutCommand({
TableName: table,
Item: itemToWrite,
ReturnConsumedCapacity: 'TOTAL',
}),
),
() => `a put to ${table}`,
);
}
@Span('ddb.batchGet', (params: unknown[]) => ({
@@ -223,6 +275,37 @@ export class DDBClient extends PuterClient {
'db.batch_size': params.length,
}))
async batchPut(params: { table: string; item: Record<string, unknown> }[]) {
return this.#batchWrite(
params.map(({ table, item }) => ({
table,
request: { PutRequest: { Item: item } },
})),
);
}
@Span('ddb.batchDel', (params: unknown[]) => ({
'db.batch_size': params.length,
}))
async batchDel(params: { table: string; key: Record<string, unknown> }[]) {
return this.#batchWrite(
params.map(({ table, key }) => ({
table,
request: { DeleteRequest: { Key: key } },
})),
);
}
// Shared BatchWriteItem plumbing for batchPut/batchDel: 25-item chunks,
// UnprocessedItems retried with capped exponential backoff, consumed
// capacity accumulated per table across every request.
async #batchWrite(
params: {
table: string;
request: NonNullable<
BatchWriteCommandInput['RequestItems']
>[string][number];
}[],
) {
const consumedCapacityByTable = new Map<string, number>();
if (params.length === 0) {
return { ConsumedCapacity: [] };
@@ -259,11 +342,7 @@ export class DDBClient extends PuterClient {
let requestItems = chunk.reduce(
(acc, curr) => {
const tableRequests = acc[curr.table] ?? [];
tableRequests.push({
PutRequest: {
Item: curr.item,
},
});
tableRequests.push(curr.request);
acc[curr.table] = tableRequests;
return acc;
},
@@ -279,11 +358,17 @@ export class DDBClient extends PuterClient {
break;
}
const response = await client.send(
new BatchWriteCommand({
RequestItems: requestItems,
ReturnConsumedCapacity: 'TOTAL',
}),
const response = await sendRepairingValues(
requestItems,
(itemsToWrite) =>
client.send(
new BatchWriteCommand({
RequestItems: itemsToWrite,
ReturnConsumedCapacity: 'TOTAL',
}),
),
() =>
`a batch write to ${Object.keys(requestItems).join(', ')}`,
);
accumulateConsumedCapacity(
response.ConsumedCapacity as
@@ -329,11 +414,18 @@ export class DDBClient extends PuterClient {
}
@Span('ddb.del', (table: string) => ({ 'db.table': table }))
async del<T extends Record<string, unknown>>(table: string, key: T) {
async del<T extends Record<string, unknown>>(
table: string,
key: T,
opts?: { returnOld?: boolean },
) {
const command = new DeleteCommand({
TableName: table,
Key: key,
ReturnConsumedCapacity: 'TOTAL',
// ALL_OLD makes the delete an atomic claim: exactly one caller
// gets the attributes back.
...(opts?.returnOld ? { ReturnValues: 'ALL_OLD' as const } : {}),
});
const client = await this.#getDocumentClient();
@@ -424,20 +516,27 @@ export class DDBClient extends PuterClient {
!!expressionValues && Object.keys(expressionValues).length > 0;
const hasNames =
!!expressionNames && Object.keys(expressionNames).length > 0;
const command = new UpdateCommand({
TableName: table,
Key: key,
UpdateExpression: expression,
...(hasValues
? { ExpressionAttributeValues: expressionValues }
: {}),
...(hasNames ? { ExpressionAttributeNames: expressionNames } : {}),
ReturnValues: 'ALL_NEW',
ReturnConsumedCapacity: 'TOTAL',
});
const client = await this.#getDocumentClient();
return client.send(command);
return sendRepairingValues(
expressionValues,
(valuesToWrite) =>
client.send(
new UpdateCommand({
TableName: table,
Key: key,
UpdateExpression: expression,
...(hasValues
? { ExpressionAttributeValues: valuesToWrite }
: {}),
...(hasNames
? { ExpressionAttributeNames: expressionNames }
: {}),
ReturnValues: 'ALL_NEW',
ReturnConsumedCapacity: 'TOTAL',
}),
),
() => `an update to ${table}`,
);
}
async createTableIfNotExists(
@@ -539,6 +638,9 @@ export class DDBClient extends PuterClient {
marshallOptions: {
removeUndefinedValues: true,
},
unmarshallOptions: {
wrapNumbers: clampStoredNumber,
},
});
}
@@ -566,6 +668,9 @@ export class DDBClient extends PuterClient {
marshallOptions: {
removeUndefinedValues: true,
},
unmarshallOptions: {
wrapNumbers: clampStoredNumber,
},
});
}
@@ -0,0 +1,126 @@
import { describe, expect, it } from 'vitest';
import {
clampStoredNumber,
isRepairableMarshallError,
MAX_STORED_NUMBER,
MIN_STORED_NUMBER,
repairForMarshall,
} from './marshallRepair.ts';
describe('isRepairableMarshallError', () => {
it('recognizes the out-of-range and special-value failures', () => {
for (const message of [
'Number 1.6515584833071455e+55 is greater than Number.MAX_SAFE_INTEGER. Use NumberValue from @aws-sdk/lib-dynamodb.',
'Number -1e+55 is lesser than Number.MIN_SAFE_INTEGER. Use NumberValue from @aws-sdk/lib-dynamodb.',
'Special numeric value NaN is not allowed',
'Special numeric value Infinity is not allowed',
]) {
expect(isRepairableMarshallError(new Error(message))).toBe(true);
}
});
it('leaves every other failure alone', () => {
for (const error of [
new Error('Unsupported type passed: [object Symbol].'),
new Error('ValidationException'),
new Error(''),
undefined,
'not an error',
]) {
expect(isRepairableMarshallError(error)).toBe(false);
}
});
});
describe('repairForMarshall', () => {
it('clamps a number past the safe range in both directions', () => {
expect(repairForMarshall(1.6515584833071455e55)).toEqual({
value: MAX_STORED_NUMBER,
changed: true,
});
expect(repairForMarshall(-1e55)).toEqual({
value: MIN_STORED_NUMBER,
changed: true,
});
});
it('clamps infinities and nulls NaN', () => {
expect(repairForMarshall(Infinity).value).toBe(MAX_STORED_NUMBER);
expect(repairForMarshall(-Infinity).value).toBe(MIN_STORED_NUMBER);
expect(repairForMarshall(NaN)).toEqual({ value: null, changed: true });
});
it('repairs numbers nested in objects and arrays', () => {
const repaired = repairForMarshall({
profile: { netWorth: 1e55, level: 29 },
scores: [1, [2, -1e55]],
});
expect(repaired.changed).toBe(true);
expect(repaired.value).toEqual({
profile: { netWorth: MAX_STORED_NUMBER, level: 29 },
scores: [1, [2, MIN_STORED_NUMBER]],
});
});
it('returns the original payload untouched when nothing is out of range', () => {
const payload = {
a: MAX_STORED_NUMBER,
b: [1, 2, { c: 'three' }],
d: null,
};
const repaired = repairForMarshall(payload);
expect(repaired.changed).toBe(false);
expect(repaired.value).toBe(payload);
});
it('does not mutate the payload it repairs', () => {
const nested = { netWorth: 1e55 };
const payload = { nested };
repairForMarshall(payload);
expect(nested.netWorth).toBe(1e55);
});
it('keeps a `__proto__` key as data', () => {
const payload = JSON.parse('{"__proto__":{"big":1e55}}');
const repaired = repairForMarshall(payload) as {
value: Record<string, unknown>;
changed: boolean;
};
expect(repaired.changed).toBe(true);
expect(Object.getPrototypeOf(repaired.value)).toBe(Object.prototype);
expect(
Object.getOwnPropertyDescriptor(repaired.value, '__proto__')?.value,
).toEqual({ big: MAX_STORED_NUMBER });
});
it('leaves values it does not own alone', () => {
const date = new Date(0);
expect(repairForMarshall(date).value).toBe(date);
expect(repairForMarshall('str')).toEqual({
value: 'str',
changed: false,
});
});
});
describe('clampStoredNumber', () => {
it('decodes a number inside the range unchanged', () => {
expect(clampStoredNumber('42')).toBe(42);
expect(clampStoredNumber('-0.5')).toBe(-0.5);
expect(clampStoredNumber(String(MAX_STORED_NUMBER))).toBe(
MAX_STORED_NUMBER,
);
});
it('clamps a stored number past the range instead of decoding a BigInt', () => {
expect(clampStoredNumber('18014398509481982')).toBe(MAX_STORED_NUMBER);
expect(clampStoredNumber('-18014398509481982')).toBe(MIN_STORED_NUMBER);
expect(clampStoredNumber('1e400')).toBe(MAX_STORED_NUMBER);
});
});
@@ -0,0 +1,129 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* A stored number keeps its exact value only within the IEEE-754 safe integer
* range; a magnitude past this cannot round-trip, and the document client
* refuses to marshall one rather than write a value that reads back wrong.
*/
export const MAX_STORED_NUMBER = Number.MAX_SAFE_INTEGER;
export const MIN_STORED_NUMBER = Number.MIN_SAFE_INTEGER;
/**
* Marshalling failures a retry can fix by clamping: an out-of-range number, or
* a special numeric value (`NaN`, `±Infinity`) that has no representation at
* all. Matched on the message because they are plain `Error`s thrown while
* encoding the payload — no error name or code separates them from anything
* else, and they never reach the wire, so there is no response to inspect.
*/
const REPAIRABLE_MARSHALL_ERRORS = [
/is greater than Number\.MAX_SAFE_INTEGER/,
/is lesser than Number\.MIN_SAFE_INTEGER/,
/^Special numeric value /,
];
export const isRepairableMarshallError = (error: unknown): boolean => {
const message = (error as Error | undefined)?.message;
if (typeof message !== 'string') return false;
return REPAIRABLE_MARSHALL_ERRORS.some((pattern) => pattern.test(message));
};
/**
* The same bound, applied to what comes back. A stored number past the safe
* range — left by an older write, or reached by a counter incremented up to it
* — is otherwise decoded as a `BigInt`, which no JSON response can carry. This
* hands back the same kind of value a write accepts, and does less work per
* number than the default decoding it replaces.
*/
export const clampStoredNumber = (stored: string): number => {
const num = Number(stored);
if (num > MAX_STORED_NUMBER) return MAX_STORED_NUMBER;
if (num < MIN_STORED_NUMBER) return MIN_STORED_NUMBER;
return num;
};
export interface MarshallRepair {
value: unknown;
/** False when nothing in the payload was out of range — nothing to retry. */
changed: boolean;
}
const unchanged = (value: unknown): MarshallRepair => ({
value,
changed: false,
});
// Matches the shapes the marshaller walks into as a map: object literals and
// null-prototype objects, but not class instances (Date, Buffer, Set, …),
// which it encodes by their own rules.
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' &&
value !== null &&
(value.constructor === Object || value.constructor === undefined);
const repairNumber = (num: number): MarshallRepair => {
// No representation for these; JSON already turns them into null, so a
// caller that got one this far did not send it as JSON.
if (Number.isNaN(num)) return { value: null, changed: true };
if (num > MAX_STORED_NUMBER)
return { value: MAX_STORED_NUMBER, changed: true };
if (num < MIN_STORED_NUMBER)
return { value: MIN_STORED_NUMBER, changed: true };
return unchanged(num);
};
/**
* Clamp every number a payload holds into the range the store accepts,
* returning the original object untouched when nothing needed it — callers hold
* on to the values they pass (caches, retries), so a repair copies rather than
* mutating in place.
*
* Only run after a marshalling failure. Walking a payload this way costs as
* much as marshalling it, which is exactly why writes are not checked up
* front.
*/
export const repairForMarshall = (value: unknown): MarshallRepair => {
if (typeof value === 'number') return repairNumber(value);
if (Array.isArray(value)) {
let changed = false;
const repairedEntries = value.map((entry) => {
const repaired = repairForMarshall(entry);
changed = changed || repaired.changed;
return repaired.value;
});
return changed ? { value: repairedEntries, changed } : unchanged(value);
}
if (isPlainObject(value)) {
let changed = false;
const repairedEntries = Object.entries(value).map(([key, entry]) => {
const repaired = repairForMarshall(entry);
changed = changed || repaired.changed;
return [key, repaired.value] as const;
});
// `fromEntries` defines each property rather than assigning it, so a
// `__proto__` key in the payload stays data here.
return changed
? { value: Object.fromEntries(repairedEntries), changed }
: unchanged(value);
}
return unchanged(value);
};
@@ -0,0 +1,462 @@
/**
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, expect, it, vi } from 'vitest';
import type { IConfig } from '../../types';
import { EmailClient } from './EmailClient';
const FROM = '"Puter" <[email protected]>';
/**
* Nodemailer's JSON transport is a real transport that serializes the message
* instead of talking SMTP — the send path stays genuine while the wire stays
* local.
*/
const jsonTransportConfig = (overrides: Partial<IConfig> = {}): IConfig =>
({
port: 0,
extensions: [],
env: 'prod',
email: { jsonTransport: true, from: FROM },
...overrides,
}) as unknown as IConfig;
const startClient = (overrides: Partial<IConfig> = {}): EmailClient => {
const client = new EmailClient(jsonTransportConfig(overrides));
client.onServerStart();
return client;
};
/** The JSON transport reports the serialized message on `.message`. */
const sentMessage = (info: unknown) =>
JSON.parse((info as { message: string }).message) as {
from: { address: string; name: string };
to: { address: string }[];
subject: string;
html?: string;
headers?: Record<string, string>;
};
describe('EmailClient — transport lifecycle', () => {
it('stops sending once the transport is shut down', async () => {
const client = startClient();
expect(
await client.sendRaw({ to: '[email protected]', subject: 'up', text: 'x' }),
).not.toBeNull();
client.onServerShutdown();
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(
await client.sendRaw({ to: '[email protected]', subject: 'down', text: 'x' }),
).toBeNull();
warn.mockRestore();
});
it('warns at boot when no transport is set', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const client = new EmailClient({
port: 0,
extensions: [],
} as unknown as IConfig);
client.onServerStart();
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('no email transport configured'),
);
warn.mockRestore();
});
it('drops the send and returns null when no transport exists', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const client = new EmailClient({
port: 0,
extensions: [],
} as unknown as IConfig);
client.onServerStart();
await expect(
client.sendRaw({ to: '[email protected]', subject: 'hi', text: 'hi' }),
).resolves.toBeNull();
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('without transport'),
expect.objectContaining({ to: '[email protected]' }),
);
warn.mockRestore();
});
});
describe('EmailClient — sending', () => {
it('sends a rendered template through the transport', async () => {
const client = startClient();
const info = await client.sendRaw({
to: '[email protected]',
subject: 'raw subject',
html: '<p>hello</p>',
headers: { 'List-Unsubscribe': '<https://puter.test/u>' },
});
const message = sentMessage(info);
expect(message.subject).toBe('raw subject');
expect(message.to[0].address).toBe('[email protected]');
expect(message.from.address).toBe('[email protected]');
expect(message.headers?.['List-Unsubscribe']).toBe(
'<https://puter.test/u>',
);
});
it('lets the caller override the from address', async () => {
const client = startClient();
const info = await client.sendRaw({
from: '[email protected]',
to: '[email protected]',
subject: 's',
text: 't',
});
expect(sentMessage(info).from.address).toBe('[email protected]');
});
it('falls back to the built-in sender when config has none', async () => {
const client = startClient({
email: { jsonTransport: true },
} as unknown as Partial<IConfig>);
const info = await client.sendRaw({
to: '[email protected]',
subject: 's',
text: 't',
});
expect(sentMessage(info).from.address).toBe('[email protected]');
});
it('refuses an unknown template name', async () => {
const client = startClient();
await expect(
client.send('[email protected]', 'not-a-template' as never),
).rejects.toThrow('Unknown email template: not-a-template');
});
it('surfaces transport failures to the caller', async () => {
// Port 1 on loopback is never listening, so the send really fails.
const client = startClient({
email: { host: '127.0.0.1', port: 1, from: FROM },
} as unknown as Partial<IConfig>);
await expect(
client.sendRaw({
to: '[email protected]',
subject: 's',
text: 't',
}),
).rejects.toThrow();
});
});
describe('EmailClient — template rendering', () => {
it('renders the code into both subject and body', async () => {
const client = startClient();
const captured: { subject?: string; html?: string } = {};
const original = client.sendRaw.bind(client);
vi.spyOn(client, 'sendRaw').mockImplementation(async (options) => {
captured.subject = options.subject;
captured.html = options.html;
return original(options);
});
await client.send('[email protected]', 'email_verification_code', {
code: '424242',
});
expect(captured.subject).toBe('424242 is your confirmation code');
expect(captured.html).toContain('<strong>424242</strong>');
});
it('does not HTML-escape values in the plain-text subject header', async () => {
const client = startClient();
const captured: { subject?: string } = {};
vi.spyOn(client, 'sendRaw').mockImplementation(async (options) => {
captured.subject = options.subject;
return null;
});
await client.send('[email protected]', 'app-user-feedback', {
owner_username: 'dev',
sender_username: 'user',
sender_email: null,
app_title: "Bob's App & Games",
app_name: 'bobs-app',
app_link: 'https://puter.example/app/bobs-app',
message: 'hi',
});
// A subject is not HTML — entities would render literally in the
// recipient's mail client.
expect(captured.subject).toBe("New user feedback for Bob's App & Games");
});
it('escapes html and converts newlines in nl2br values', async () => {
const client = startClient();
let html = '';
vi.spyOn(client, 'sendRaw').mockImplementation(async (options) => {
html = options.html ?? '';
return null;
});
await client.send('[email protected]', 'listing-rejected', {
app_name: 'demo',
app_title: 'Demo',
reason: 'first & "only"\n<b>line</b>',
});
expect(html).toContain(
'first &amp; &quot;only&quot;<br />&lt;b&gt;line&lt;/b&gt;',
);
});
it('renders an empty string for a missing nl2br value', async () => {
const client = startClient();
let html = '';
vi.spyOn(client, 'sendRaw').mockImplementation(async (options) => {
html = options.html ?? '';
return null;
});
await client.send('[email protected]', 'listing-rejected', {
app_name: 'demo',
app_title: 'Demo',
});
expect(html).toContain('<blockquote></blockquote>');
});
});
describe('EmailClient — share notification templates', () => {
/** Captures both parts of a send without touching the transport. */
const renderShare = async (
template: 'file_shared_with_you' | 'file_shared_invite',
values: Record<string, unknown>,
) => {
const client = startClient();
const captured: { html: string; text: string } = { html: '', text: '' };
vi.spyOn(client, 'sendRaw').mockImplementation(async (options) => {
captured.html = options.html ?? '';
captured.text = options.text ?? '';
return null;
});
await client.send('[email protected]', template, values);
return captured;
};
const HOLDER = {
recipient: 'alice',
subject_line: 'bob shared notes.md with you',
shares: [
{ sender: 'bob', what: 'notes.md' },
{ sender: 'carol', what: '3 items — a.txt, b.txt, +1 more' },
],
link: 'https://puter.test',
unsubscribe_uuid: null,
};
it('sends a plain-text alternative beside the html', async () => {
const { html, text } = await renderShare(
'file_shared_with_you',
HOLDER,
);
expect(html).toContain('<!DOCTYPE html>');
// Every sender reaches both parts, so a text-only client loses nothing.
for (const part of [html, text]) {
expect(part).toContain('bob');
expect(part).toContain('notes.md');
expect(part).toContain('carol');
expect(part).toContain('+1 more');
}
expect(text).not.toContain('<');
});
it('escapes item names in the html and leaves them raw in the text', async () => {
const { html, text } = await renderShare('file_shared_with_you', {
...HOLDER,
shares: [{ sender: 'bob', what: 'r&d "notes".md' }],
});
expect(html).toContain('r&amp;d &quot;notes&quot;.md');
expect(text).toContain('r&d "notes".md');
});
it('renders as a responsive single column with no remote assets', async () => {
const { html } = await renderShare('file_shared_with_you', HOLDER);
expect(html).toContain(
'<meta name="viewport" content="width=device-width, initial-scale=1" />',
);
expect(html).toContain('@media only screen and (max-width: 600px)');
expect(html).toContain('@media (prefers-color-scheme: dark)');
expect(html).toContain('max-width: 600px');
// Images are the one thing a client can refuse to load, so the design
// does without them — the layout can't depend on a blocked asset.
expect(html).not.toContain('<img');
// The colors have to survive a client that drops the stylesheet.
expect(html).toContain('style="background-color: #ffffff;');
});
it('opens with a preview line that is hidden in the body', async () => {
const { html } = await renderShare('file_shared_with_you', HOLDER);
const preheader = html.indexOf('Waiting for you under Shared with me.');
expect(preheader).toBeGreaterThan(-1);
expect(html.slice(0, preheader)).toContain('mso-hide: all');
expect(preheader).toBeLessThan(html.indexOf('Hi alice,'));
});
it('points the call to action at the app and nowhere else', async () => {
const { html, text } = await renderShare(
'file_shared_with_you',
HOLDER,
);
expect(html).toContain('href="https://puter.test"');
expect(html).toContain('>Open Puter</a>');
expect(text).toContain('Open Puter: https://puter.test');
});
it('separates senders without a rule above the first', async () => {
const { html } = await renderShare('file_shared_with_you', HOLDER);
// One rule between two senders, none leading the list.
expect(html.split('border-top: 1px solid').length - 1).toBe(1);
});
it('offers the unsubscribe link only to a recipient who has an account', async () => {
const withAccount = await renderShare('file_shared_with_you', {
...HOLDER,
unsubscribe_uuid: 'a-uuid',
});
expect(withAccount.html).toContain(
'href="https://puter.test/unsubscribe?user_uuid=a-uuid"',
);
expect(withAccount.text).toContain(
'https://puter.test/unsubscribe?user_uuid=a-uuid',
);
const anonymous = await renderShare('file_shared_with_you', HOLDER);
expect(anonymous.html).not.toContain('/unsubscribe');
expect(anonymous.text).not.toContain('/unsubscribe');
});
it('tells an invited address what to do with it', async () => {
const { html, text } = await renderShare('file_shared_invite', {
email: '[email protected]',
subject_line: 'bob shared notes.md with you on Puter',
shares: [{ sender: 'bob', what: 'notes.md' }],
link: 'https://puter.test',
});
for (const part of [html, text]) {
expect(part).toContain('[email protected]');
expect(part).toContain('Create your free account');
// An invite has no account to unsubscribe from.
expect(part).not.toContain('/unsubscribe');
}
expect(html).toContain('href="https://puter.test"');
});
});
describe('EmailClient.clean', () => {
const clean = (email: string) => startClient().clean(email);
it('strips subaddressing on ordinary domains', () => {
expect(clean('[email protected]')).toBe('[email protected]');
});
it('ignores dots and subaddressing for gmail', () => {
expect(clean('[email protected]')).toBe('[email protected]');
});
it('canonicalizes googlemail onto gmail', () => {
expect(clean('[email protected]')).toBe('[email protected]');
});
it('keeps yahoo subaddressing, which yahoo treats as distinct', () => {
expect(clean('[email protected]')).toBe('[email protected]');
});
it('ignores dots for icloud aliases', () => {
expect(clean('[email protected]')).toBe('[email protected]');
});
it('returns anything that is not an address unchanged', () => {
expect(clean('not-an-email')).toBe('not-an-email');
expect(clean('@nolocal.test')).toBe('@nolocal.test');
});
});
describe('EmailClient.validate', () => {
it('waves everything through in a dev environment', async () => {
const client = startClient({ env: 'dev' } as Partial<IConfig>);
await expect(client.validate('[email protected]')).resolves.toBe(
true,
);
});
it('rejects a blocked domain suffix', async () => {
const client = startClient({
blockedEmailDomains: ['blocked.test'],
} as unknown as Partial<IConfig>);
await expect(client.validate('[email protected]')).resolves.toBe(
false,
);
await expect(client.validate('[email protected]')).resolves.toBe(
true,
);
});
it('matches the blocklist against the cleaned address', async () => {
const client = startClient({
blockedEmailDomains: ['@gmail.com'],
} as unknown as Partial<IConfig>);
await expect(
client.validate('[email protected]'),
).resolves.toBe(false);
});
it('lets a registered validator veto an address', async () => {
const client = startClient();
const seen: string[] = [];
client.addValidator((email) => {
seen.push(email);
return !email.startsWith('spam');
});
await expect(client.validate('[email protected]')).resolves.toBe(
false,
);
await expect(client.validate('[email protected]')).resolves.toBe(true);
// Validators always see the canonical form.
expect(seen).toEqual(['[email protected]', '[email protected]']);
});
it('supports asynchronous validators', async () => {
const client = startClient();
client.addValidator(async (email) => email !== '[email protected]');
await expect(client.validate('[email protected]')).resolves.toBe(false);
await expect(client.validate('[email protected]')).resolves.toBe(true);
});
});
+54 -28
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -22,7 +22,11 @@ import handlebars, { template } from 'handlebars';
import nodemailer from 'nodemailer';
import type { IConfig } from '../../types';
import { PuterClient } from '../types';
import { EMAIL_TEMPLATES, type EmailTemplateName } from './templates';
import {
EMAIL_TEMPLATES,
type EmailTemplate,
type EmailTemplateName,
} from './templates';
/** Attachment shape passed through to the underlying transport. */
export interface EmailAttachment {
@@ -64,6 +68,7 @@ export type EmailValidator = (email: string) => Promise<boolean> | boolean;
interface CompiledTemplate {
subject: ReturnType<typeof template>;
html: ReturnType<typeof template>;
text?: ReturnType<typeof template>;
}
// -- Clean-email rules ------------------------------------------------
@@ -110,10 +115,11 @@ const DOMAIN_ALIASES: Record<string, string> = {
/**
* Unified email client. Handles:
* - Template-based outbound mail (via `send`)
* - Raw nodemailer passthrough (via `sendRaw`)
* - Canonical-form normalization for dedup (via `clean`)
* - Policy + extensible validation (via `validate`)
*
* - Template-based outbound mail (via `send`)
* - Raw nodemailer passthrough (via `sendRaw`)
* - Canonical-form normalization for dedup (via `clean`)
* - Policy + extensible validation (via `validate`)
*/
export class EmailClient extends PuterClient {
private transport: ReturnType<typeof nodemailer.createTransport> | null =
@@ -152,12 +158,15 @@ export class EmailClient extends PuterClient {
// -- Public API: sending ------------------------------------------
/**
* Render a template and send it to `to`.
* Render a template and send it to `to`. `options.replyTo` sets the
* Reply-To header (e.g. so a recipient can respond to the originator of the
* message rather than the no-reply From address).
*/
async send<T extends EmailTemplateName>(
to: string,
template: T,
values: Record<string, unknown> = {},
options: { replyTo?: string } = {},
): Promise<void> {
const compiled = this.compiledTemplates[template];
if (!compiled) {
@@ -169,16 +178,19 @@ export class EmailClient extends PuterClient {
to,
subject: compiled.subject(values),
html: compiled.html(values),
...(compiled.text ? { text: compiled.text(values) } : {}),
...(options.replyTo ? { replyTo: options.replyTo } : {}),
});
}
/**
* Raw send — bypasses the template system. Useful for one-off
* admin emails that don't warrant a named template.
* Raw send — bypasses the template system. Useful for one-off admin emails
* that don't warrant a named template.
*
* Returns the transport's send result, or `null` when no transport
* is configured (the send is a no-op in that case — callers that
* must not silently drop mail should check `isConfigured` first).
* Returns the transport's send result, or `null` when no transport is
* configured (the send is a no-op in that case — callers that must not
* silently drop mail should check `config.email` before composing, or the
* `null` return after).
*/
async sendRaw(options: SendMailOptions) {
if (!this.transport) {
@@ -194,17 +206,12 @@ export class EmailClient extends PuterClient {
});
}
/** Whether an SMTP transport is configured (sends are no-ops otherwise). */
get isConfigured(): boolean {
return this.transport !== null;
}
// -- Public API: clean / validate ---------------------------------
/**
* Normalize an email to its canonical form for dedup comparisons.
* Applies provider-specific rules (e.g. Gmail ignores dots in
* the local part) plus generic subaddressing removal.
* Normalize an email to its canonical form for dedup comparisons. Applies
* provider-specific rules (e.g. Gmail ignores dots in the local part) plus
* generic subaddressing removal.
*/
clean(email: string): string {
let [local, domain] = email.split('@');
@@ -233,9 +240,9 @@ export class EmailClient extends PuterClient {
}
/**
* Check whether an email is allowed to be used. Checks domain
* blocklist plus any registered validators (services can call
* `addValidator()` to register custom policy hooks).
* Check whether an email is allowed to be used. Checks domain blocklist
* plus any registered validators (services can call `addValidator()` to
* register custom policy hooks).
*/
async validate(email: string): Promise<boolean> {
if (this.config.env === 'dev') return true;
@@ -258,9 +265,8 @@ export class EmailClient extends PuterClient {
}
/**
* Register a custom validation hook. Services can call this
* during their startup to veto specific emails (e.g. a
* disposable-email service).
* Register a custom validation hook. Services can call this during their
* startup to veto specific emails (e.g. a disposable-email service).
*/
addValidator(fn: EmailValidator): void {
this.validators.push(fn);
@@ -285,10 +291,30 @@ export class EmailClient extends PuterClient {
}
private compileTemplates(): void {
for (const [name, template] of Object.entries(EMAIL_TEMPLATES)) {
// Widened to the interface: the literal map keeps a distinct type per
// template, and only some of them carry a `text` part.
const templates: Record<EmailTemplateName, EmailTemplate> =
EMAIL_TEMPLATES;
for (const [name, template] of Object.entries(templates)) {
this.compiledTemplates[name as EmailTemplateName] = {
subject: handlebars.compile(template.subject),
// Subjects are plain-text headers: HTML-escaping would put
// literal entities in front of the recipient (&amp; etc.).
// Header safety is handled elsewhere — the transport encodes
// newlines, and free-form values (e.g. app_title) collapse
// whitespace upstream.
subject: handlebars.compile(template.subject, {
noEscape: true,
}),
html: handlebars.compile(dedent(template.html)),
// Same reasoning as the subject: a text part is not HTML, so
// escaping would show entities to the reader.
...(template.text
? {
text: handlebars.compile(dedent(template.text), {
noEscape: true,
}),
}
: {}),
};
}
}
+278 -30
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -18,19 +18,195 @@
*/
/**
* Email template definitions. Keys are the template names; values are
* the Handlebars-compilable `subject` and `html` strings.
* Email template definitions. Keys are the template names; values are the
* Handlebars-compilable `subject` and `html` strings.
*
* Rendered values are supplied by callers of `EmailClient.send()`.
* Variables use standard Handlebars syntax: `{{var}}`, `{{#if cond}}…{{/if}}`,
* and the custom helper `{{{nl2br text}}}` for HTML-safe newline conversion.
* Rendered values are supplied by callers of `EmailClient.send()`. Variables
* use standard Handlebars syntax: `{{var}}`, `{{#if cond}}…{{/if}}`, and the
* custom helper `{{{nl2br text}}}` for HTML-safe newline conversion.
*/
export interface EmailTemplate {
subject: string;
html: string;
/**
* Optional plain-text alternative. Where a template has one it goes out
* beside the HTML as multipart/alternative, which is what plain-text
* clients, screen readers and spam scoring all prefer to a machine
* down-conversion of the markup.
*/
text?: string;
}
// -- Shared layout ----------------------------------------------------
/**
* Colors, in one place so the two share templates can't drift apart. Every one
* of them is also written inline further down: clients that drop `<style>`
* (Gmail reading a non-Gmail account, Outlook.com) would otherwise render an
* unstyled page, so the stylesheet only carries what inline CSS can't express —
* the small-screen and dark-mode overrides.
*
* `ACCENT` is the GUI's primary blue darkened until white text on it clears
* 4.5:1, since a button label is small text however bold it is.
*/
const INK = '#101828';
const INK_SOFT = '#5b6472';
const INK_FAINT = '#667085';
const PAGE_BG = '#f2f4f7';
const CARD_BG = '#ffffff';
const CARD_BORDER = '#e4e7ec';
const RULE = '#e6e9ee';
const PANEL_BG = '#f8f9fb';
const PANEL_BORDER = '#eceff3';
const ACCENT = '#0a76cc';
const FONT =
"-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif";
/** Pads the preview line so body text can't leak into it. */
const PREHEADER_FILL = '&#847;&zwnj;&nbsp;'.repeat(60);
/**
* The document both share notifications render into: one 600px column that goes
* full width on a phone, laid out with tables and `bgcolor` because Outlook
* renders through Word and ignores anything more modern.
*
* `preheader` is the line the inbox shows beside the subject — it should add to
* the subject, not repeat it. `content` is the card's rows; `footer` sits below
* the card, where the reason-for-receiving and unsubscribe belong.
*/
const shareEmailLayout = (parts: {
preheader: string;
content: string;
footer: string;
}): string => `
<!DOCTYPE html>
<html lang="en" dir="ltr" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="x-apple-disable-message-reformatting" />
<meta name="color-scheme" content="light dark" />
<meta name="supported-color-schemes" content="light dark" />
<title>{{subject_line}}</title>
<!--[if mso]>
<noscript><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript>
<![endif]-->
<style>
body { margin: 0; padding: 0; width: 100% !important; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
table { border-spacing: 0; mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
td { mso-line-height-rule: exactly; }
a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; font-size: inherit !important; font-family: inherit !important; font-weight: inherit !important; line-height: inherit !important; }
@media only screen and (max-width: 600px) {
.col { width: 100% !important; }
.pad { padding-left: 24px !important; padding-right: 24px !important; }
.pad-y { padding-top: 28px !important; padding-bottom: 28px !important; }
.h1 { font-size: 22px !important; line-height: 30px !important; }
.btn { width: 100% !important; }
}
@media (prefers-color-scheme: dark) {
.page { background-color: #0e1116 !important; }
.card { background-color: #171b22 !important; border-color: #272d38 !important; }
.ink { color: #e9ebef !important; }
.ink-soft { color: #9aa3b2 !important; }
.ink-soft a { color: #9aa3b2 !important; }
.rule { border-color: #272d38 !important; }
.panel { background-color: #1d222a !important; border-color: #2b323d !important; }
.mark { color: #4da3f2 !important; }
}
</style>
</head>
<body class="page" style="margin: 0; padding: 0; width: 100%; background-color: ${PAGE_BG};">
<div style="display: none; font-size: 1px; line-height: 1px; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all;">${parts.preheader}${PREHEADER_FILL}</div>
<div role="article" aria-roledescription="email" lang="en">
<table role="presentation" class="page" width="100%" cellpadding="0" cellspacing="0" border="0" style="width: 100%; background-color: ${PAGE_BG};">
<tr>
<td align="center" style="padding: 32px 12px;">
<!--[if mso]><table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
<table role="presentation" class="col" width="600" cellpadding="0" cellspacing="0" border="0" style="width: 100%; max-width: 600px; text-align: left;">
<tr>
<td class="pad mark" style="padding: 0 4px 14px; font-family: ${FONT}; font-size: 15px; line-height: 20px; font-weight: 700; letter-spacing: 0.01em; color: ${ACCENT};">Puter</td>
</tr>
<tr>
<td class="card" style="background-color: ${CARD_BG}; border: 1px solid ${CARD_BORDER}; border-radius: 14px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="width: 100%;">
<tr>
<td class="pad pad-y" style="padding: 36px 36px 34px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="width: 100%;">${parts.content}
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="pad ink-soft" style="padding: 20px 4px 0; font-family: ${FONT}; font-size: 13px; line-height: 20px; color: ${INK_FAINT};">${parts.footer}
</td>
</tr>
</table>
<!--[if mso]></td></tr></table><![endif]-->
</td>
</tr>
</table>
</div>
</body>
</html>
`;
/** The greeting line above the heading. */
const greetingRow = (text: string): string => `
<tr>
<td class="ink-soft" style="padding: 0 0 6px; font-family: ${FONT}; font-size: 15px; line-height: 22px; color: ${INK_SOFT};">${text}</td>
</tr>`;
const headingRow = (text: string): string => `
<tr>
<td class="ink h1" style="padding: 0 0 18px; font-family: ${FONT}; font-size: 24px; line-height: 32px; font-weight: 700; letter-spacing: -0.01em; color: ${INK};">${text}</td>
</tr>`;
/**
* One row per sender, hairline-separated. The wording comes pre-composed from
* the digest (`digestLines`), so the list stays a list however many senders and
* items fold into it.
*/
const SHARE_LIST_ROW = `
<tr>
<td class="panel" style="padding: 6px 18px; background-color: ${PANEL_BG}; border: 1px solid ${PANEL_BORDER}; border-radius: 10px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="width: 100%;">
{{#each shares}}
<tr>
<td class="ink rule" style="padding: 12px 0;{{#unless @first}} border-top: 1px solid ${RULE};{{/unless}} font-family: ${FONT}; font-size: 16px; line-height: 24px; color: ${INK};"><strong style="font-weight: 600;">{{this.sender}}</strong> shared {{this.what}}</td>
</tr>
{{/each}}
</table>
</td>
</tr>`;
/** A body paragraph. `padding` lets a caller tune the rhythm around it. */
const textRow = (text: string, padding = '18px 0 0'): string => `
<tr>
<td class="ink-soft" style="padding: ${padding}; font-family: ${FONT}; font-size: 15px; line-height: 23px; color: ${INK_SOFT};">${text}</td>
</tr>`;
/**
* The call to action. Padding sits on the cell and the color on `bgcolor` so
* Outlook still draws a real button (square-cornered, which is fine); the table
* goes full width under 600px so the tap target spans the card.
*/
const buttonRow = (label: string): string => `
<tr>
<td style="padding: 26px 0 0;">
<table role="presentation" class="btn" cellpadding="0" cellspacing="0" border="0" style="border-collapse: separate;">
<tr>
<td align="center" bgcolor="${ACCENT}" style="background-color: ${ACCENT}; border-radius: 10px; padding: 14px 26px;">
<a href="{{link}}" style="display: inline-block; font-family: ${FONT}; font-size: 16px; line-height: 20px; font-weight: 600; color: #ffffff; text-decoration: none;">${label}</a>
</td>
</tr>
</table>
</td>
</tr>`;
export const EMAIL_TEMPLATES = {
'approved-for-listing': {
subject: '🎉 Your app has been approved for listing!',
@@ -75,6 +251,25 @@ Please update <a href="https://puter.com/app/{{app_name}}">{{app_title}}</a>.
<blockquote>{{nl2br message}}</blockquote>
<p>Best,<br />
The Puter Team
</p>
`,
},
'app-user-feedback': {
subject: 'New user feedback for {{app_title}}',
html: `
<p>Hi{{#if owner_username}} {{owner_username}}{{/if}},</p>
<p>
<strong>{{sender_username}}</strong>{{#if sender_email}} (<a href="mailto:{{sender_email}}">{{sender_email}}</a>){{/if}} sent feedback about <a href="{{app_link}}">{{app_title}}</a>:
</p>
<blockquote>{{{nl2br message}}}</blockquote>
{{#if sender_email}}<p>Just reply to this email to respond to them directly.</p>{{/if}}
<p>
You're receiving this because feedback is enabled for
<a href="{{app_link}}">{{app_title}}</a> — manage it in the
<a href="{{dev_center_link}}">Dev Center</a> under your app's settings.
</p>
<p>Best,<br />
The Puter Team
</p>
`,
},
@@ -164,32 +359,85 @@ immediately</p>
<p>Puter</p>
`,
},
share_by_username: {
subject: 'Puter share from {{susername}}',
html: `
<p>Hi there {{rusername}},</p>
<p>You've received a share from {{susername}} on Puter.</p>
<p>Go to puter.com to check it out.</p>
{{#if message}}
<p>The following message was included:</p>
<blockquote>{{message}}</blockquote>
{{/if}}
<p>Sincerely,</p>
<p>Puter</p>
/**
* A digest: shares to one recipient are held briefly and merged, so
* `shares` may carry several senders. The subject is composed by the
* service (see `digestSubject`), which owns the grouped wording.
*/
file_shared_with_you: {
subject: '{{subject_line}}',
html: shareEmailLayout({
preheader: 'Waiting for you under Shared with me.',
content:
greetingRow('Hi{{#if recipient}} {{recipient}}{{/if}},') +
headingRow('Shared with you') +
SHARE_LIST_ROW +
buttonRow('Open Puter') +
textRow(
'Shared items live under <span style="font-weight: 600;">Shared</span> in your files.',
'24px 0 0',
),
footer: `You're receiving this because someone shared with your Puter account.{{#if unsubscribe_uuid}}
<br /><a href="{{link}}/unsubscribe?user_uuid={{unsubscribe_uuid}}" style="color: inherit; text-decoration: underline;">Unsubscribe from notification emails</a>{{/if}}`,
}),
text: `
Hi{{#if recipient}} {{recipient}}{{/if}},
Shared with you on Puter:
{{#each shares}}
- {{this.sender}} shared {{this.what}}
{{/each}}
Open Puter: {{link}}
Shared items live under "Shared" in your files.
--
You're receiving this because someone shared with your Puter account.
{{#if unsubscribe_uuid}}Unsubscribe from notification emails:
{{link}}/unsubscribe?user_uuid={{unsubscribe_uuid}}{{/if}}
`,
},
share_by_email: {
subject: 'share by email',
html: `
<p>Hi there,</p>
<p>You've received a share from {{sender_name}} on Puter:</p>
<p><a href="{{link}}">{{link}}</a></p>
{{#if message}}
<p>The following message was included:</p>
<blockquote>{{message}}</blockquote>
{{/if}}
<p>Sincerely,</p>
<p>Puter</p>
// The only way to reach someone with no account. Same digest shape.
file_shared_invite: {
subject: '{{subject_line}}',
html: shareEmailLayout({
preheader: 'Claim it with a free Puter account.',
content:
greetingRow('Hi there,') +
headingRow('Shared with you on Puter') +
SHARE_LIST_ROW +
textRow(
'There\'s no Puter account for <span style="font-weight: 600;">{{email}}</span> yet. Create one with this address, confirm it, and everything above will be waiting for you. It\'s free and takes about a minute.',
) +
buttonRow('Create your free account') +
textRow(
'Already on Puter? Add {{email}} to your account and confirm it to get the same access.',
'24px 0 0',
),
footer: `You're receiving this because someone shared with {{email}}. Nothing is shared until the address is confirmed, so you can ignore this email and nothing happens.`,
}),
text: `
Hi there,
Shared with you on Puter:
{{#each shares}}
- {{this.sender}} shared {{this.what}}
{{/each}}
There's no Puter account for {{email}} yet. Create one with this
address, confirm it, and everything above will be waiting for you.
It's free and takes about a minute.
Create your free account: {{link}}
Already on Puter? Add {{email}} to your account and confirm it to get
the same access.
--
You're receiving this because someone shared with {{email}}. Nothing is
shared until the address is confirmed, so you can ignore this email
and nothing happens.
`,
},
} satisfies Record<string, EmailTemplate>;
+103 -2
View File
@@ -1,5 +1,6 @@
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
@@ -7,6 +8,7 @@ import {
it,
vi,
} from 'vitest';
import { extensionStore } from '../../extensions.ts';
import { PuterServer } from '../../server.ts';
import { setupTestServer } from '../../testUtil.ts';
import type { EventClient } from './EventClient.js';
@@ -25,8 +27,7 @@ describe('EventClient', () => {
});
// Each test gets a fresh key so listeners registered by earlier tests
// never collide with later ones (the client has no public way to
// unsubscribe).
// never collide with later ones.
let key: string;
beforeEach(() => {
key = `test.${Math.random().toString(36).slice(2)}`;
@@ -184,6 +185,106 @@ describe('EventClient', () => {
});
});
describe('off', () => {
it('stops delivering to a removed listener', () => {
const kept = vi.fn();
const removed = vi.fn();
target.on(key, kept);
target.on(key, removed);
target.off(key, removed);
target.emit(key, {}, {});
expect(kept).toHaveBeenCalledTimes(1);
expect(removed).not.toHaveBeenCalled();
});
it('ignores a key nobody ever subscribed to', () => {
expect(() => target.off(key, vi.fn())).not.toThrow();
});
it('leaves the list alone when the listener was never registered', () => {
const listener = vi.fn();
target.on(key, listener);
target.off(key, vi.fn());
target.emit(key, {}, {});
expect(listener).toHaveBeenCalledTimes(1);
});
});
describe('hasListeners', () => {
it('is false for a key nobody subscribed to', () => {
expect(target.hasListeners(key)).toBe(false);
});
it('is true for an exact subscriber', () => {
target.on(key, vi.fn());
expect(target.hasListeners(key)).toBe(true);
});
it('is true when only a wildcard prefix matches', () => {
target.on(`${key}.*`, vi.fn());
expect(target.hasListeners(`${key}.child.deep`)).toBe(true);
});
it('is true for an extension-registered listener', () => {
extensionStore.events[key] = [vi.fn()];
try {
expect(target.hasListeners(key)).toBe(true);
} finally {
delete extensionStore.events[key];
}
});
it('goes back to false once the last listener is removed', () => {
const listener = vi.fn();
target.on(key, listener);
target.off(key, listener);
expect(target.hasListeners(key)).toBe(false);
});
});
describe('extension-registered listeners', () => {
afterEach(() => {
delete extensionStore.events[key];
});
it('fires alongside listeners registered on the client', () => {
const fromExtension = vi.fn();
const fromClient = vi.fn();
extensionStore.events[key] = [fromExtension];
target.on(key, fromClient);
target.emit(key, { n: 1 }, { source: 'test' });
expect(fromExtension).toHaveBeenCalledWith(
key,
{ n: 1 },
{ source: 'test' },
);
expect(fromClient).toHaveBeenCalledTimes(1);
});
it('is awaited by emitAndWait', async () => {
const order: string[] = [];
extensionStore.events[key] = [
async () => {
await new Promise((resolve) => setTimeout(resolve, 5));
order.push('extension');
},
];
target.on(key, () => {
order.push('client');
});
await target.emitAndWait(key, {}, {});
expect(order).toEqual(['client', 'extension']);
});
});
describe('lifecycle hooks', () => {
it('onServerStart emits a serverStart event', () => {
const listener = vi.fn();
+46 -28
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -44,20 +44,19 @@ export class EventClient extends PuterClient {
/**
* Dispatch an event to every matching subscriber.
*
* Match semantics: emit walks every dot-separated prefix of `key`,
* looking up `<prefix>.*` listeners for prefixes shorter than the full
* key, and exact-key listeners on the final iteration. So emitting
* Match semantics: emit walks every dot-separated prefix of `key`, looking
* up `<prefix>.*` listeners for prefixes shorter than the full key, and
* exact-key listeners on the final iteration. So emitting
* `outer.gui.item.removed` fires subscribers on:
*
* - `outer.*`
* - `outer.gui.*`
* - `outer.gui.item.*`
* - `outer.gui.item.removed`
*
* Subscribers are still keyed in a single map — wildcards just live
* under their literal `<prefix>.*` string. No regex, no per-emit
* scan of every listener.
* - `outer.*`
* - `outer.gui.*`
* - `outer.gui.item.*`
* - `outer.gui.item.removed`
*
* Subscribers are still keyed in a single map — wildcards just live under
* their literal `<prefix>.*` string. No regex, no per-emit scan of every
* listener.
*/
emit<T extends keyof EventMap>(
key: T,
@@ -85,15 +84,15 @@ export class EventClient extends PuterClient {
/**
* Like `emit`, but awaits every matched listener before resolving.
*
* Use this when the emitter needs to act on mutations the handlers made
* to `data` — e.g. validation hooks where a listener can set
* `data.allow = false` to reject, or pre-commit pipelines where every
* stage must complete before the next step runs. Regular `emit` is
* fire-and-forget and can't observe handler state changes.
* Use this when the emitter needs to act on mutations the handlers made to
* `data` — e.g. validation hooks where a listener can set `data.allow =
* false` to reject, or pre-commit pipelines where every stage must complete
* before the next step runs. Regular `emit` is fire-and-forget and can't
* observe handler state changes.
*
* Listeners run sequentially in the order they're registered so an
* earlier handler's mutation is visible to later ones. A listener that
* throws is logged (same as `emit`) and the chain continues.
* Listeners run sequentially in the order they're registered so an earlier
* handler's mutation is visible to later ones. A listener that throws is
* logged (same as `emit`) and the chain continues.
*/
async emitAndWait<T extends keyof EventMap>(
key: T,
@@ -130,18 +129,37 @@ export class EventClient extends PuterClient {
});
}
/**
* Whether anything would run if `key` were emitted, wildcards included.
*
* For emitters whose work is only worth doing when someone is listening —
* gathering the payload costs a round trip, say. Emitting into the void is
* otherwise perfectly cheap and doesn't need this.
*/
hasListeners<T extends keyof EventMap>(key: T): boolean {
const parts = key.split('.');
for (let i = 0; i < parts.length; i++) {
const matchKey = (
i === parts.length - 1
? key
: `${parts.slice(0, i + 1).join('.')}.*`
) as ListenKey;
if (this.#eventListeners[matchKey]?.length) return true;
if (extensionStore.events[matchKey]?.length) return true;
}
return false;
}
/**
* Subscribe to an event by exact key OR a wildcard prefix.
*
* Wildcards: a key ending in `.*` matches every event whose name
* starts with the prefix. `outer.*` matches `outer.gui.item.removed`,
* `outer.fs.write-hash`, and any other dot-extended descendant.
* Exact keys still match exactly. See `emit()` for the dispatch order.
*
* Callback receives the full `(key, data, meta)` tuple as passed
* to `emit()` — wildcard subscribers can branch on the triggering
* event name.
* Wildcards: a key ending in `.*` matches every event whose name starts
* with the prefix. `outer.*` matches `outer.gui.item.removed`,
* `outer.fs.write-hash`, and any other dot-extended descendant. Exact keys
* still match exactly. See `emit()` for the dispatch order.
*
* Callback receives the full `(key, data, meta)` tuple as passed to
* `emit()` — wildcard subscribers can branch on the triggering event name.
*/
on<P extends ListenKey>(
key: P,
+137 -8
View File
@@ -20,6 +20,7 @@ import type {
Response as ExpressResponse,
} from 'express';
import { Actor } from '../../core';
import type { UsageInput } from '../../services/metering/types';
import { FSEntry } from '../../stores/fs/FSEntry';
// GUI write events spread an entry plus per-event metadata into `response`.
@@ -31,6 +32,24 @@ type GuiEvent<R = Record<string, unknown>> = {
response: R;
};
/**
* Extension-augmentable half of {@link EventMap}. Extensions that emit their own
* events declare the payload here by declaration merging, so both the emitter
* and every listener are typed against the same shape:
*
* declare module '@heyputer/backend/clients/event/types' {
* interface IExtensionEventMap {
* 'my.thing.happened': { thingId: string };
* }
* }
*
* Deliberately member-less and index-signature-free: an index signature here
* would widen `keyof EventMap` to `string` and silently disable key checking on
* every `emit` in the tree.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface IExtensionEventMap {}
export type EventMap = {
// ---- Server lifecycle ----
serverStart: Record<string, never>;
@@ -141,6 +160,19 @@ export type EventMap = {
'puter.signup.validate': {
allow: boolean;
email?: string;
/**
* The address in the same canonical form the `email.validate` hook was
* given (`cleanEmail`), so a handler can correlate the two hooks on one
* key. Aliases (`[email protected]`, `[email protected]`) differ from
* `email` here.
*/
clean_email?: string;
/**
* True for a temp (frictionless, no-password) signup. Those carry a
* synthetic `<username>@gmail.com` and never reach email validation, so
* a handler must not draw conclusions from `email`.
*/
is_temp?: boolean;
ip?: string | null;
source?: 'oidc';
req?: unknown;
@@ -289,7 +321,17 @@ export type EventMap = {
sourceObjectKey: string;
copyObjectKey: string;
};
'fs.move.node': { node: FSEntry; fromPath: string; toPath: string };
/**
* `fromUserId` is the owner the node had before the move. A move into
* someone else's tree re-owns the row, and `node` already carries the new
* owner — listeners that care about the hand-over need the old one.
*/
'fs.move.node': {
node: FSEntry;
fromPath: string;
toPath: string;
fromUserId?: number;
};
'fs.remove.node': { node: FSEntry; entry: FSEntry; target: FSEntry };
'fs.write.file': { node: FSEntry; entry: FSEntry; target: FSEntry };
'fs.storage.upload-progress': {
@@ -305,13 +347,81 @@ export type EventMap = {
};
'storage.quota.bonus': { userId: number; extra: number };
// ---- Metering ----
// Recurring charges are pure mechanism here: the metering service knows
// when to ask (once per user per month, the first time that month's usage
// record is touched) and how to record the answer, and an extension
// decides what the account owes. Listeners push onto `charges`; the
// service applies them as ordinary usage once every listener has run.
// Nothing listening → no charges and no claim is ever taken.
//
// Emitted after the claim is settled, so a listener that calls back into
// metering can't re-trigger it.
'metering.monthly.charges': {
/**
* User-scoped, with no app on it: the account is what recurs, and the
* app that happened to trigger the month's first call has nothing to do
* with what is owed. Price against what the user owns.
*/
actor: Actor;
/** The month being charged for, `YYYY-MM` in UTC. */
month: string;
/**
* Push what the user owes here. Every listener's charges are merged
* into one amount map and recorded as a single increment.
*/
charges: UsageInput[];
};
// ---- Workers ----
// Only a genuinely new worker. Redeploying an existing name updates its
// row instead, and never reaches here — so a listener that prices this
// is pricing workers that came into existence, not deploys.
'worker.create': { actor: Actor; workerName: string };
// The same announcement for worker code that lives inside a hosted site
// and is deployed on demand rather than by an explicit call. Such a worker
// has no row of ours to key on, so what stands in for "genuinely new" is
// the absence of any prior record that it ran — which is why it is
// announced separately, and identified by where its source lives rather
// than by a worker name.
'worker.dynamic.create': {
actor: Actor;
subdomain: string;
worker: string;
};
// ---- Outer / GUI broadcast ----
'outer.cacheUpdate': {
cacheKey: string[];
data?: unknown;
ttlSeconds?: number;
};
/**
* Permission cache generations were bumped, so peer regions must bump their
* own — the counter is per-cluster, so a local bump says nothing to them.
* Carries the actors, not the values: the numbers only have to change.
*/
'outer.permission.generationBumped': { actorUids: string[] };
/**
* Flat permission entries were deleted. Grant-path flat entries carry no
* expiry, so without this a revoke never lands in a peer region whose KV
* table isn't replicated. Revoke-only: a grant that fails to replicate just
* denies there, which is the safe direction.
*/
'outer.permission.flatInvalidated': {
entries: Array<{ holderUserId: number; permission: string }>;
};
'outer.fs.write-hash': { hash: string; uuid: string };
/**
* Cache keys the KV read cache must stop serving, because the entries
* behind them were just written somewhere else.
*
* `outer.*` rather than `outer.pubsub.*` on purpose: the cache lives in the
* Redis a cluster shares, so one node applying the invalidation covers the
* whole cluster — fanning it out to siblings would just repeat the write.
*/
'outer.kv.cacheInvalidated': { cacheKeys: string[] };
'outer.gui.item.added': GuiEvent;
'outer.gui.item.updated': GuiEvent;
'outer.gui.item.moved': GuiEvent;
@@ -325,8 +435,10 @@ export type EventMap = {
}>;
// ---- Subdomains ----
'subdomain.delete': { subdomain: string };
'subdomain.update': { subdomain: string };
// `uid` is the row uuid — for `delete` it is the only surviving handle a
// listener can use to find state keyed to the row after it is gone.
'subdomain.delete': { subdomain: string; uid?: string };
'subdomain.update': { subdomain: string; uid?: string };
'site.htmlServed': {
subdomain: string;
entry: unknown;
@@ -402,7 +514,23 @@ export type EventMap = {
[K in `route.${string}`]: RouteLifecycleEvent;
} & {
[K in `pubsub.login.${string}`]: { authtoken: string };
};
} & {
/**
* A user's subscription now resolves to a different policy. Carried on the
* `outer.pubsub.*` channel so it reaches sibling nodes and peer clusters,
* not just the one that handled the change — every node caches the resolved
* policy, so a purchase is only live once they have all dropped theirs.
*/
'outer.pubsub.metering.subscription-changed': { userUuid: string };
/**
* A user's purchased credit balance changed. Separate from a policy change
* because it moves the other half of the same budget, and carried on the
* `outer.pubsub.*` channel for the same reason: every node caches whether
* an account has budget left, so a top-up only lifts enforcement once they
* have all dropped that answer.
*/
'outer.pubsub.metering.credits-changed': { userUuid: string };
} & IExtensionEventMap;
/**
* Phase of a request/method lifecycle. `reject` is emitted when a `before`
@@ -482,10 +610,11 @@ 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>;
+1 -1
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -30,7 +30,7 @@ describe('PreludeClient', () => {
expect(makeClient().isConfigured()).toBe(false);
});
describe('isCountrySupported (€0.07 cap)', () => {
describe('isCountrySupported (€0.20 cap)', () => {
const client = makeClient('sk_test');
it('allows revenue markets up to the cap (incl. the priciest)', () => {
@@ -40,6 +40,17 @@ describe('PreludeClient', () => {
expect(client.isCountrySupported('us')).toBe(true); // case-insensitive
});
it('allows the markets the old €0.07 cap excluded', () => {
// Raising the cap to €0.20 brought ~89 countries into the phone
// gate. These pin the new range so a future change to the default
// has to say so out loud.
expect(client.isCountrySupported('UA')).toBe(true); // €0.0940
expect(client.isCountrySupported('PH')).toBe(true); // €0.1237
expect(client.isCountrySupported('EG')).toBe(true); // €0.1561
expect(client.isCountrySupported('NG')).toBe(true); // €0.1980
expect(client.isCountrySupported('WS')).toBe(true); // €0.2000, at the cap
});
it('rejects countries above the cap, with no SMS, or unknown', () => {
expect(client.isCountrySupported('PK')).toBe(false); // €0.3548
expect(client.isCountrySupported('ID')).toBe(false); // €0.2430
@@ -63,9 +74,7 @@ describe('PreludeClient', () => {
});
it('createVerification POSTs the phone target + ip signal with bearer auth', async () => {
fetchMock.mockResolvedValue(
okJson({ id: 'vrf_1', status: 'success' }),
);
fetchMock.mockResolvedValue(okJson({ id: 'vrf_1', status: 'success' }));
const client = makeClient('sk_test');
const res = await client.createVerification('+14155550123', {
@@ -81,7 +90,11 @@ describe('PreludeClient', () => {
target: { type: 'phone_number', value: '+14155550123' },
// Defaults to RCS (cheaper); Prelude falls back to SMS. locale is
// hardcoded to en-US so the message text is always English.
options: { code_size: 6, preferred_channel: 'rcs', locale: 'en-US' },
options: {
code_size: 6,
preferred_channel: 'rcs',
locale: 'en-US',
},
signals: { ip: '203.0.113.7' },
});
});
@@ -196,9 +209,9 @@ describe('PreludeClient', () => {
it('throws (does not call fetch) when not configured', async () => {
const client = makeClient();
await expect(
client.createVerification('+14155550123'),
).rejects.toThrow(/not configured/i);
await expect(client.createVerification('+14155550123')).rejects.toThrow(
/not configured/i,
);
expect(fetchMock).not.toHaveBeenCalled();
});
+20 -13
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -50,12 +50,15 @@ export type PreludeChannel =
export type PreludeDeliveryChannel = PreludeChannel | 'silent' | 'voice';
/**
* Default per-SMS cost ceiling (EUR). Countries whose Prelude SMS rate exceeds
* this — or that have no SMS channel — are not offered phone verification. The
* cap covers every realistic revenue market (priciest are Germany €0.0598 and
* Saudi Arabia €0.0638) while excluding the expensive, high-fraud long tail.
* Override per-deployment with `config.prelude.maxSmsCostEur`.
* this — or that have no SMS channel — are not offered phone verification.
* Raised from €0.07 to €0.20: the old cap sat only marginally above the
* priciest revenue markets (Germany €0.0598, Saudi Arabia €0.0638), so any rate
* drift silently withdrew the phone gate from a real market — and the abuse
* harness now routes far more legitimate signups into the SMS band, where an
* unavailable gate is a dead end rather than a mild inconvenience. Override
* per-deployment with `config.prelude.maxSmsCostEur`.
*/
const DEFAULT_MAX_SMS_COST_EUR = 0.07;
const DEFAULT_MAX_SMS_COST_EUR = 0.2;
/** Status returned by Prelude when creating/retrying a verification. */
export type PreludeCreateStatus =
@@ -74,11 +77,11 @@ export type PreludeCheckStatus =
| 'transaction_mismatch';
/**
* Prelude Verify v2 client (https://docs.prelude.so/verify/v2). Sends and checks
* SMS one-time codes — Prelude generates, delivers, and validates the code, so
* we never store one ourselves. No-ops with a warning when no API key is
* configured (so dev environments don't crash); `isConfigured()` lets callers
* surface a clean "phone verification unavailable" error instead.
* Prelude Verify v2 client (https://docs.prelude.so/verify/v2). Sends and
* checks SMS one-time codes — Prelude generates, delivers, and validates the
* code, so we never store one ourselves. No-ops with a warning when no API key
* is configured (so dev environments don't crash); `isConfigured()` lets
* callers surface a clean "phone verification unavailable" error instead.
*/
export class PreludeClient extends PuterClient {
private apiKey: string | null = null;
@@ -113,7 +116,9 @@ export class PreludeClient extends PuterClient {
/**
* Whether SMS verification should be offered for a country. False when the
* country is unknown, has no SMS channel, or its rate exceeds the cost cap.
* country is unknown, has no SMS channel, or its rate exceeds the cost
* cap.
*
* @param iso ISO-3166 alpha-2 (e.g. 'US') — from the parsed phone number.
*/
isCountrySupported(iso: string | undefined): boolean {
@@ -174,7 +179,9 @@ export class PreludeClient extends PuterClient {
}
/**
* Check a code the user entered against the active verification for `target`.
* Check a code the user entered against the active verification for
* `target`.
*
* @returns `{ status }` — `'success'` means verified.
*/
async checkVerification(
+5 -3
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -17,11 +17,13 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/** Per-country Prelude SMS pricing, hardcoded from the Prelude global price
/**
* Per-country Prelude SMS pricing, hardcoded from the Prelude global price
* sheet. `sms` is the average cost in EUR, or null when SMS is unavailable
* there. Used to cap phone verification to affordable countries (see
* PreludeClient.isCountrySupported). Regenerate from the price sheet when
* Prelude updates rates. */
* Prelude updates rates.
*/
export interface CountryPrice {
name: string;
/** Prelude SMS average in EUR, or null when SMS is not available. */
@@ -0,0 +1,171 @@
/**
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { IConfig } from '../../types';
import { RedisClient } from './RedisClient';
const config = (redis: Record<string, unknown>): IConfig =>
({ port: 0, extensions: [], redis }) as unknown as IConfig;
type ClusterOptions = {
redisOptions?: { tls?: unknown; connectTimeout?: number };
clusterRetryStrategy?: (attempts: number) => number;
};
const optionsOf = (client: RedisClient): ClusterOptions =>
(client as unknown as { options: ClusterOptions }).options;
describe('RedisClient — in-process mock', () => {
let client: RedisClient | null = null;
afterEach(async () => {
if (client) await client.onServerShutdown();
client = null;
});
it('falls back to the mock when no startup nodes are configured', async () => {
client = new RedisClient(config({}));
await client.set('greeting', 'hello');
await expect(client.get('greeting')).resolves.toBe('hello');
});
it('honours an explicit mock request even with startup nodes present', async () => {
client = new RedisClient(
config({
useMock: true,
startupNodes: [{ host: 'redis.internal', port: 6379 }],
}),
);
await client.set('k', 'v');
await expect(client.get('k')).resolves.toBe('v');
});
it('exposes the shutdown hook directly on the cluster instance', () => {
client = new RedisClient(config({}));
expect(typeof client.onServerShutdown).toBe('function');
});
it('disconnects when a clean quit fails', async () => {
const instance = new RedisClient(config({}));
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(instance, 'quit').mockRejectedValue(new Error('quit refused'));
const disconnect = vi.spyOn(instance, 'disconnect');
await instance.onServerShutdown();
expect(disconnect).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
'[redis] failed to quit redis client cleanly',
expect.any(Error),
);
warn.mockRestore();
});
});
describe('RedisClient — real cluster wiring', () => {
let client: RedisClient | null = null;
afterEach(() => {
client?.disconnect();
client = null;
});
const startupNodes = [{ host: '127.0.0.1', port: 7001 }];
it('enables TLS by default and bounds the connect timeout', () => {
client = new RedisClient(config({ startupNodes }));
expect(optionsOf(client).redisOptions?.tls).toEqual({});
expect(optionsOf(client).redisOptions?.connectTimeout).toBe(10000);
});
it('lets a plain-TCP deployment opt out of TLS', () => {
client = new RedisClient(config({ startupNodes, tls: false }));
expect(optionsOf(client).redisOptions?.tls).toBeUndefined();
});
it('backs off on cluster retries up to a ceiling', () => {
client = new RedisClient(config({ startupNodes, tls: false }));
const retry = optionsOf(client).clusterRetryStrategy!;
expect(retry(0)).toBe(100);
expect(retry(5)).toBe(600);
expect(retry(100)).toBe(2000);
});
it('treats startup churn as a warning and everything else as an error', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
client = new RedisClient(config({ startupNodes, tls: false }));
client.emit('error', new Error('None of startup nodes is available'));
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('startup issue while connecting'),
);
const fatal = new Error('WRONGPASS invalid credentials');
client.emit('error', fatal);
expect(error).toHaveBeenCalledWith('[redis] cluster error', fatal);
warn.mockRestore();
error.mockRestore();
});
it('applies the same triage to per-node errors', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
client = new RedisClient(config({ startupNodes, tls: false }));
const transient = new Error('boom');
transient.name = 'ClusterAllFailedError';
client.emit('node error', transient, '127.0.0.1:7001');
expect(warn).toHaveBeenCalledWith(
expect.stringContaining(
'startup issue for cluster node 127.0.0.1:7001',
),
);
const fatal = new Error('node exploded');
client.emit('node error', fatal, '127.0.0.1:7002');
expect(error).toHaveBeenCalledWith(
'[redis] cluster node error (127.0.0.1:7002)',
fatal,
);
// Non-Error payloads are stringified rather than crashing the handler.
client.emit('node error', 'None of startup nodes is available', 'n3');
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('startup issue for cluster node n3'),
);
warn.mockRestore();
error.mockRestore();
});
it('logs the transport lifecycle once each', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
client = new RedisClient(config({ startupNodes, tls: false }));
client.emit('connect');
client.emit('ready');
expect(log).toHaveBeenCalledWith('[redis] cluster transport connected');
expect(log).toHaveBeenCalledWith('[redis] cluster ready');
log.mockRestore();
});
});
+7 -7
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -108,13 +108,13 @@ const buildCluster = (config: IConfig): Cluster => {
/**
* `RedisClient` IS the ioredis `Cluster` instance — consumers call
* `this.clients.redis.get(...)` / `.set(...)` directly rather than
* going through an inner `.client` field. Lifecycle methods
* (`onServerShutdown`) are attached onto the cluster instance itself.
* `this.clients.redis.get(...)` / `.set(...)` directly rather than going
* through an inner `.client` field. Lifecycle methods (`onServerShutdown`) are
* attached onto the cluster instance itself.
*
* Type-wise, `RedisClient` is `Cluster & WithLifecycle`; the registry-
* facing value below is a constructor that returns that shape. Mirrors
* the `DatabaseClientFactory` pattern.
* Type-wise, `RedisClient` is `Cluster & WithLifecycle`; the registry- facing
* value below is a constructor that returns that shape. Mirrors the
* `DatabaseClientFactory` pattern.
*/
export type RedisClient = Cluster & WithLifecycle;
+489
View File
@@ -0,0 +1,489 @@
/**
* 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 { GetObjectCommand } from '@aws-sdk/client-s3';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { IConfig } from '../../types';
import { S3Client } from './S3Client';
const LOCAL_BUCKET = 'puter-local';
/**
* The multipart helper takes its command sender as a parameter, so the failure
* paths can be driven without a live endpoint.
*/
type S3Internals = {
awsConfig: { endpoint?: string };
migrateLegacyStorage(opts?: {
bucket?: string;
legacyPath?: string;
}): Promise<{ migratedFileCount: number; scannedEntryCount: number }>;
uploadMultipart(args: {
bucket: string;
client: { send: (command: unknown) => Promise<unknown> };
filePath: string;
fileSize: number;
key: string;
}): Promise<void>;
};
const internals = (client: S3Client) => client as unknown as S3Internals;
const localConfig = (): IConfig =>
({
port: 0,
extensions: [],
s3: { localConfig: { inMemory: true } },
}) as unknown as IConfig;
const startLocal = async (): Promise<S3Client> => {
const client = new S3Client(localConfig());
await client.onServerStart();
return client;
};
const objectBody = async (
client: S3Client,
key: string,
): Promise<string | undefined> => {
const result = await client
.get()
.send(new GetObjectCommand({ Bucket: LOCAL_BUCKET, Key: key }));
return result.Body?.transformToString();
};
describe('S3Client — local development endpoint', () => {
let client: S3Client;
beforeEach(async () => {
client = await startLocal();
});
afterEach(async () => {
await client.onServerShutdown();
});
it('points clients at the in-process object store', async () => {
await client
.get()
.send(
new GetObjectCommand({
Bucket: LOCAL_BUCKET,
Key: 'definitely-absent',
}),
)
.then(
() => {
throw new Error('expected a missing-key failure');
},
(error: { name?: string }) => {
expect(error.name).toBe('NoSuchKey');
},
);
});
it('reuses one client per region and mints a new one per region', () => {
const first = client.get('us-west-2');
expect(client.get('us-west-2')).toBe(first);
expect(client.get('eu-central-1')).not.toBe(first);
});
it('serves presigning from the same client when no public endpoint is set', () => {
expect(client.getForPresign('us-west-2')).toBe(client.get('us-west-2'));
});
it('keeps modest upload thresholds so the local store is not overwhelmed', () => {
expect(client.maxSingleUploadSize).toBe(10 * 1024 * 1024);
expect(client.partSize).toBe(5 * 1024 * 1024);
});
});
describe('S3Client — remote endpoint configuration', () => {
let local: S3Client;
let remote: S3Client | null = null;
beforeEach(async () => {
local = await startLocal();
});
afterEach(async () => {
if (remote) await remote.onServerShutdown();
remote = null;
await local.onServerShutdown();
});
const remoteConfig = (extra: Record<string, unknown>): IConfig =>
({
port: 0,
extensions: [],
s3: {
s3Config: {
endpoint: internals(local).awsConfig.endpoint,
accessKeyId: 'fakeAccessKeyId',
secretAccessKey: 'fakeSecretAccessKey',
region: 'us-west-2',
forcePathStyle: true,
...extra,
},
},
}) as unknown as IConfig;
it('talks to a configured S3-compatible endpoint', async () => {
remote = new S3Client(remoteConfig({}));
await remote.onServerStart();
await remote
.get()
.send(new GetObjectCommand({ Bucket: LOCAL_BUCKET, Key: 'nope' }))
.then(
() => {
throw new Error('expected a missing-key failure');
},
(error: { name?: string }) => {
expect(error.name).toBe('NoSuchKey');
},
);
});
it('signs browser-facing URLs against the public endpoint', async () => {
remote = new S3Client(
remoteConfig({ publicEndpoint: 'https://cdn.example.test' }),
);
await remote.onServerStart();
const presign = remote.getForPresign('us-west-2');
expect(presign).not.toBe(remote.get('us-west-2'));
// Cached per region like the regular client map.
expect(remote.getForPresign('us-west-2')).toBe(presign);
expect(remote.getForPresign('eu-central-1')).not.toBe(presign);
});
it('shares one client when the public endpoint matches the private one', async () => {
const endpoint = internals(local).awsConfig.endpoint;
remote = new S3Client(remoteConfig({ publicEndpoint: endpoint }));
await remote.onServerStart();
expect(remote.getForPresign('us-west-2')).toBe(remote.get('us-west-2'));
});
it('raises the upload thresholds when using the ambient credential chain', async () => {
remote = new S3Client({
port: 0,
extensions: [],
s3: { s3Config: { useCredentialChain: true } },
} as unknown as IConfig);
await remote.onServerStart();
expect(remote.partSize).toBe(64 * 1024 * 1024);
expect(remote.maxSingleUploadSize).toBe(128 * 1024 * 1024);
});
});
describe('S3Client — legacy storage migration', () => {
let client: S3Client;
let dir: string;
beforeEach(async () => {
client = await startLocal();
dir = mkdtempSync(join(tmpdir(), 'puter-s3-legacy-'));
});
afterEach(async () => {
rmSync(dir, { recursive: true, force: true });
await client.onServerShutdown();
});
it('does nothing when there is no legacy directory', async () => {
await expect(
internals(client).migrateLegacyStorage({
legacyPath: join(dir, 'absent'),
}),
).resolves.toEqual({ migratedFileCount: 0, scannedEntryCount: 0 });
});
it('uploads each legacy file, skips directories, then removes the tree', async () => {
const small = 'small-file-contents';
writeFileSync(join(dir, 'small.txt'), small);
writeFileSync(join(dir, 'other.txt'), 'other');
mkdirSync(join(dir, 'a-subdirectory'));
await expect(
internals(client).migrateLegacyStorage({ legacyPath: dir }),
).resolves.toEqual({ migratedFileCount: 2, scannedEntryCount: 3 });
await expect(objectBody(client, 'small.txt')).resolves.toBe(small);
await expect(objectBody(client, 'other.txt')).resolves.toBe('other');
expect(existsSync(dir)).toBe(false);
});
it('switches to a multipart upload for a file over the single-put limit', async () => {
// S3 requires every part but the last to be at least 5 MiB, so the
// fixture has to straddle that for real.
client.maxSingleUploadSize = 1024 * 1024;
client.partSize = 5 * 1024 * 1024;
const body = 'X'.repeat(6 * 1024 * 1024);
writeFileSync(join(dir, 'large.bin'), body);
await expect(
internals(client).migrateLegacyStorage({ legacyPath: dir }),
).resolves.toEqual({ migratedFileCount: 1, scannedEntryCount: 1 });
await expect(objectBody(client, 'large.bin')).resolves.toBe(body);
});
});
describe('S3Client — multipart failure handling', () => {
let client: S3Client;
let dir: string;
let filePath: string;
beforeEach(async () => {
client = await startLocal();
dir = mkdtempSync(join(tmpdir(), 'puter-s3-multipart-'));
filePath = join(dir, 'part-source.bin');
writeFileSync(filePath, 'Y'.repeat(30));
client.partSize = 10;
});
afterEach(async () => {
rmSync(dir, { recursive: true, force: true });
await client.onServerShutdown();
});
const commandName = (command: unknown) =>
(command as { constructor: { name: string } }).constructor.name;
it('fails when the store will not open a multipart upload', async () => {
const send = vi.fn(async () => ({}));
await expect(
internals(client).uploadMultipart({
bucket: LOCAL_BUCKET,
client: { send },
filePath,
fileSize: 30,
key: 'no-upload-id',
}),
).rejects.toThrow('Failed to start multipart upload');
});
it('aborts the upload when a part comes back without an ETag', async () => {
const sent: string[] = [];
const send = vi.fn(async (command: unknown) => {
const name = commandName(command);
sent.push(name);
if (name === 'CreateMultipartUploadCommand') {
return { UploadId: 'upload-1' };
}
if (name === 'UploadPartCommand') return {};
return {};
});
await expect(
internals(client).uploadMultipart({
bucket: LOCAL_BUCKET,
client: { send },
filePath,
fileSize: 30,
key: 'etag-less',
}),
).rejects.toMatchObject({ statusCode: 400, legacyCode: 'bad_request' });
expect(sent).toEqual([
'CreateMultipartUploadCommand',
'UploadPartCommand',
'AbortMultipartUploadCommand',
]);
});
it('sends one part per chunk and completes with every ETag', async () => {
const parts: { PartNumber: number; ContentLength: number }[] = [];
let completed: { ETag: string; PartNumber: number }[] | undefined;
const send = vi.fn(async (command: unknown) => {
const name = commandName(command);
const input = (command as { input: Record<string, unknown> }).input;
if (name === 'CreateMultipartUploadCommand') {
return { UploadId: 'upload-1' };
}
if (name === 'UploadPartCommand') {
parts.push({
PartNumber: input.PartNumber as number,
ContentLength: input.ContentLength as number,
});
return { ETag: `etag-${input.PartNumber}` };
}
if (name === 'CompleteMultipartUploadCommand') {
completed = (
input.MultipartUpload as {
Parts: { ETag: string; PartNumber: number }[];
}
).Parts;
}
return {};
});
client.partSize = 12;
await internals(client).uploadMultipart({
bucket: LOCAL_BUCKET,
client: { send },
filePath,
fileSize: 30,
key: 'chunked',
});
expect(parts).toEqual([
{ PartNumber: 1, ContentLength: 12 },
{ PartNumber: 2, ContentLength: 12 },
{ PartNumber: 3, ContentLength: 6 },
]);
expect(completed).toEqual([
{ ETag: 'etag-1', PartNumber: 1 },
{ ETag: 'etag-2', PartNumber: 2 },
{ ETag: 'etag-3', PartNumber: 3 },
]);
});
it('aborts and rethrows when completing the upload fails', async () => {
const sent: string[] = [];
const send = vi.fn(async (command: unknown) => {
const name = commandName(command);
sent.push(name);
if (name === 'CreateMultipartUploadCommand') {
return { UploadId: 'upload-1' };
}
if (name === 'UploadPartCommand') return { ETag: 'etag' };
if (name === 'CompleteMultipartUploadCommand') {
throw new Error('complete rejected');
}
return {};
});
await expect(
internals(client).uploadMultipart({
bucket: LOCAL_BUCKET,
client: { send },
filePath,
fileSize: 30,
key: 'incomplete',
}),
).rejects.toThrow('complete rejected');
expect(sent.at(-1)).toBe('AbortMultipartUploadCommand');
});
});
describe('S3Client — disk-backed local store', () => {
let cwd: string;
let dir: string;
let client: S3Client | null = null;
beforeEach(() => {
cwd = process.cwd();
dir = mkdtempSync(join(tmpdir(), 'puter-s3-disk-'));
});
afterEach(async () => {
if (client) await client.onServerShutdown();
client = null;
process.chdir(cwd);
rmSync(dir, { recursive: true, force: true });
});
it('persists to the configured directories and drains legacy storage', async () => {
// The legacy sweep resolves `storage/` against the working
// directory, so the whole fixture lives in a throwaway cwd.
process.chdir(dir);
mkdirSync(join(dir, 'storage'));
writeFileSync(join(dir, 'storage', 'legacy.txt'), 'from-disk');
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
client = new S3Client({
port: 0,
extensions: [],
s3: {
localConfig: {
host: '127.0.0.1',
port: 0,
dataDir: join(dir, 'fauxqs-data'),
s3StorageDir: join(dir, 'fauxqs-s3'),
},
},
} as unknown as IConfig);
await client.onServerStart();
expect(log).toHaveBeenCalledWith(
'[s3] migrated 1 file(s) from legacy storage',
);
await expect(objectBody(client, 'legacy.txt')).resolves.toBe(
'from-disk',
);
expect(existsSync(join(dir, 'storage'))).toBe(false);
log.mockRestore();
});
});
describe('S3Client — short reads during multipart', () => {
let client: S3Client;
let dir: string;
beforeEach(async () => {
client = await startLocal();
dir = mkdtempSync(join(tmpdir(), 'puter-s3-short-'));
});
afterEach(async () => {
rmSync(dir, { recursive: true, force: true });
await client.onServerShutdown();
});
it('stops uploading parts once the file runs out early', async () => {
const filePath = join(dir, 'truncated.bin');
writeFileSync(filePath, 'Z'.repeat(20));
client.partSize = 10;
const parts: number[] = [];
const send = vi.fn(async (command: unknown) => {
const name = (command as { constructor: { name: string } })
.constructor.name;
const input = (command as { input: Record<string, unknown> }).input;
if (name === 'CreateMultipartUploadCommand') {
return { UploadId: 'upload-1' };
}
if (name === 'UploadPartCommand') {
parts.push(input.ContentLength as number);
return { ETag: `etag-${input.PartNumber}` };
}
return {};
});
// The caller's size is stale — the file is shorter than advertised.
await internals(client).uploadMultipart({
bucket: LOCAL_BUCKET,
client: { send },
filePath,
fileSize: 50,
key: 'truncated',
});
expect(parts).toEqual([10, 10]);
});
});
+21 -7
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -21,6 +21,7 @@ import {
AbortMultipartUploadCommand,
CompleteMultipartUploadCommand,
CreateMultipartUploadCommand,
HeadBucketCommand,
PutObjectCommand,
S3Client as AwsS3Client,
type S3ClientConfig,
@@ -184,8 +185,8 @@ export class S3Client extends PuterClient {
// ------------------------------------------------------------------
/**
* Get (or create) an S3Client for the given region.
* Clients are cached per-region for connection reuse.
* Get (or create) an S3Client for the given region. Clients are cached
* per-region for connection reuse.
*/
get(
region = this.config.s3_region || this.config.region || 'us-west-2',
@@ -213,10 +214,10 @@ export class S3Client extends PuterClient {
/**
* Client used to generate browser-facing presigned URLs. When
* `s3Config.publicEndpoint` is set, this returns a client bound to
* that endpoint — its signatures resolve against the public host
* the browser will actually hit. When unset, falls back to the
* regular client (prod behavior: one public endpoint everywhere).
* `s3Config.publicEndpoint` is set, this returns a client bound to that
* endpoint — its signatures resolve against the public host the browser
* will actually hit. When unset, falls back to the regular client (prod
* behavior: one public endpoint everywhere).
*/
getForPresign(
region = this.config.s3_region || this.config.region || 'us-west-2',
@@ -244,6 +245,19 @@ export class S3Client extends PuterClient {
return client;
}
/**
* Cheapest round-trip that proves the object store answers for a bucket: no
* object data, no listing, just a HEAD. Throws on any failure (missing
* bucket, bad credentials, unreachable endpoint) so callers can treat it as
* a liveness probe. Reuses the pooled per-region client.
*/
async headBucket(
bucket = this.config.s3_bucket || LEGACY_STORAGE_BUCKET,
region?: string,
): Promise<void> {
await this.get(region).send(new HeadBucketCommand({ Bucket: bucket }));
}
// ------------------------------------------------------------------
// Legacy storage migration
// ------------------------------------------------------------------
+3 -3
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -45,8 +45,8 @@ export interface IExtensionClientInstances {
/**
* Optional ClickHouse analytics client. Absent by default — a production
* deployment registers it via an extension to speed up the app-stats path
* at scale (see {@link ClickhouseClient}). Always branch on its presence
* and fall back to SQL.
* at scale (see {@link ClickhouseClient}). Always branch on its presence and
* fall back to SQL.
*/
clickhouse?: ClickhouseClient;
}
+136 -39
View File
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -31,15 +31,99 @@ import DEFAULT_APP_ICON from './default-app-icon.js';
/**
* REST endpoints for app management.
*
* Delegates to AppDriver for the actual CRUD + permission logic —
* these routes are just thin shape adapters that translate REST
* conventions into driver calls.
* Delegates to AppDriver for the actual CRUD + permission logic — these routes
* are just thin shape adapters that translate REST conventions into driver
* calls.
*/
/**
* Desktop boot reads the app list and individual app records repeatedly, so the
* ceiling is set well above normal boot traffic and exists to catch a runaway
* client rather than to pace one.
*
* "Repeatedly" is the operative word: an app record is read on launch, on
* permission checks, and again by anything resolving an app by name, so these
* accumulate against whatever else a session is doing rather than arriving on
* their own. Sized for a session working hard, not for a person clicking.
*/
const APP_READ_LIMIT = {
scope: 'app-read',
limit: 1_800,
window: 60_000,
key: 'user',
};
/**
* Unauthenticated icon serving; no actor to key on, so the bucket is the
* address — and an address is a NAT, a campus or a carrier gateway that can
* hold hundreds of desktops. Each desktop boot pulls the taskbar's icons at
* once, so a single burst from one network is already thousands of requests.
* Responses are publicly cacheable and usually a redirect, so the ceiling is
* not protecting bandwidth; it is there so a client looping on a broken icon
* can't spin unbounded.
*/
const APP_ICON_LIMIT = {
scope: 'app-icon',
limit: 12_000,
window: 60_000,
key: 'ip',
};
export class AppController extends PuterController {
get appStore() {
return this.stores.app;
}
// In-flight background app-open writes. Tracked only so tests and
// shutdown can wait for them — the request path never does.
#pendingOpenWrites = new Set();
/**
* Record an app open. `app_opens` is analytics: it backs the recent-apps
* list and the open counters, and no response field is derived from it. The
* client posts this without awaiting and updates its own recent list
* optimistically, so holding a response open for a primary write only added
* latency to the launch that write is measuring.
*
* Failures are logged, never surfaced — a dropped stat must not turn into a
* failed app open.
*
* @param {string} appUid
* @param {number} userId
* @returns {Promise<void>} Settles when the write and event emit finish
*/
#recordAppOpen(appUid, userId) {
const ts = Math.floor(Date.now() / 1000);
const work = (async () => {
try {
await this.clients.db.write(
'INSERT INTO `app_opens` (`app_uid`, `user_id`, `ts`) VALUES (?, ?, ?)',
[appUid, userId, ts],
);
} catch (e) {
console.warn('[rao] insert failed:', e);
}
try {
this.clients.event?.emitAndWait(
'app.opened',
{ app_uid: appUid, user_id: userId, ts },
{},
);
} catch {
// event emission best-effort
}
})();
this.#pendingOpenWrites.add(work);
work.finally(() => this.#pendingOpenWrites.delete(work));
return work;
}
/** Await every in-flight app-open write. */
async drainPendingAppOpens() {
await Promise.allSettled([...this.#pendingOpenWrites]);
}
get appDriver() {
// Drivers are wired into the shared driversContainers export by
// PuterServer at boot. Controllers get them lazily via this getter
@@ -49,7 +133,9 @@ export class AppController extends PuterController {
return d;
}
registerRoutes(router) {
registerRoutes(
/** @type {import('../../core/http/PuterRouter').PuterRouter} */ router,
) {
// GET /apps — list apps owned by the current user
router.get(
'/apps',
@@ -57,6 +143,7 @@ export class AppController extends PuterController {
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const apps = await this.appDriver.select({
@@ -71,8 +158,16 @@ export class AppController extends PuterController {
'/apps/nameAvailable',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
requireAuth: true,
// Answers "does this name exist?" for any name, so it is a
// name-enumeration oracle however cheap it is to serve.
// Mirrors the `isNameAvailable` budget on AppDriver.
rateLimit: {
scope: 'app-name-available',
limit: 60,
window: 60_000,
key: 'user',
},
},
async (req, res) => {
const name = req.query?.name;
@@ -107,6 +202,7 @@ export class AppController extends PuterController {
{
subdomain: 'api',
requireAuth: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const actor = req.actor;
@@ -148,33 +244,10 @@ export class AppController extends PuterController {
legacyCode: 'not_found',
});
// Persist open record
try {
await this.clients.db.write(
'INSERT INTO `app_opens` (`app_uid`, `user_id`, `ts`) VALUES (?, ?, ?)',
[
app_uid,
req.actor.user.id,
Math.floor(Date.now() / 1000),
],
);
} catch (e) {
console.warn('[rao] insert failed:', e);
}
try {
this.clients.event?.emitAndWait(
'app.opened',
{
app_uid,
user_id: req.actor.user.id,
ts: Math.floor(Date.now() / 1000),
},
{},
);
} catch {
// event emission best-effort
}
// Validation and authorization are settled by this point, so
// the caller learns the outcome now and the stats write lands
// on its own. See `#recordAppOpen`.
this.#recordAppOpen(app_uid, req.actor.user.id);
res.json({});
},
@@ -188,6 +261,7 @@ export class AppController extends PuterController {
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const raw = req.params.name;
@@ -214,7 +288,13 @@ export class AppController extends PuterController {
source: 'appsRoute',
args: req.query ?? {},
});
return { ...shaped, privateAccess };
return {
...shaped,
privateAccess:
shaped.privateAccess?.hasAccess === false
? shaped.privateAccess
: privateAccess,
};
}),
);
@@ -255,6 +335,7 @@ export class AppController extends PuterController {
{
subdomain: 'api',
requireAuth: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const appList = Array.isArray(req.body) ? req.body : [];
@@ -437,7 +518,11 @@ export class AppController extends PuterController {
}
setIconSecurityHeaders(res);
res.set('Content-Type', mime);
res.set('Cache-Control', 'public, max-age=60');
// Same freshness as the redirect path above — this is the
// same resource, just served inline because no CDN file
// exists yet. A 60s TTL made every app launch re-fetch the
// icon over a connection the launch itself is competing for.
res.set('Cache-Control', 'public, max-age=900');
res.send(Buffer.from(icon.slice(commaIdx + 1), 'base64'));
// Trigger background generation so next request hits the CDN
@@ -459,15 +544,27 @@ export class AppController extends PuterController {
// Icons are <img src> targets from the GUI (root) AND resolved via
// api_base_url in taskbar payloads. Register on both so either origin
// works without a cross-subdomain redirect.
router.get('/app-icon/:app_uid', { subdomain: ['api', ''] }, serveIcon);
router.get(
'/app-icon/:app_uid',
{ subdomain: ['api', ''], rateLimit: APP_ICON_LIMIT },
serveIcon,
);
router.get(
'/app-icon/:app_uid/:size',
{ subdomain: ['api', ''] },
{ subdomain: ['api', ''], rateLimit: APP_ICON_LIMIT },
serveIcon,
);
}
onServerStart() {}
onServerPrepareShutdown() {}
/**
* Let outstanding stats writes finish before the process goes away —
* otherwise a deploy silently drops every open recorded in the seconds
* before it.
*/
async onServerPrepareShutdown() {
await this.drainPendingAppOpens();
}
onServerShutdown() {}
}
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
@@ -91,6 +91,11 @@ const uniqueName = (prefix: string) =>
const uniqueIndexUrl = () =>
`https://example-${Math.random().toString(36).slice(2, 10)}.test/`;
// 1x1 transparent PNG. The `icon` write path validates the decoded payload,
// not just the declared MIME, so icon fixtures must be real images.
const MINIMAL_PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
const createApp = async (
actor: Actor,
overrides: Record<string, unknown> = {},
@@ -285,12 +290,7 @@ describe('AppController POST /rao', () => {
const { res } = makeRes();
await expect(
withActor(actor, () =>
callRoute(
'post',
'/rao',
makeReq({ body: {}, actor }),
res,
),
callRoute('post', '/rao', makeReq({ body: {}, actor }), res),
),
).rejects.toMatchObject({ statusCode: 400 });
});
@@ -328,6 +328,9 @@ describe('AppController POST /rao', () => {
);
expect(captured.body).toEqual({});
// The stats write is deliberately not awaited by the request.
await server.controllers.apps.drainPendingAppOpens();
const rows = (await server.clients.db.read(
'SELECT `app_uid`, `user_id` FROM `app_opens` WHERE `app_uid` = ? AND `user_id` = ?',
[app.uid, owner.userId],
@@ -335,6 +338,74 @@ describe('AppController POST /rao', () => {
expect(rows).toHaveLength(1);
});
// `app_opens` is analytics: the response carries nothing derived from it
// and the client never awaits the post. Holding the response open for a
// primary write put that write's latency inside the app launch it was
// measuring, on a connection the launch was competing for.
it('responds without waiting for the stats write', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
let releaseWrite = () => {};
const writeSpy = vi
.spyOn(server.clients.db, 'write')
.mockImplementation(
() =>
new Promise((resolve) => {
releaseWrite = () => resolve(undefined as never);
}),
);
try {
const { res, captured } = makeRes();
await withActor(owner.actor, () =>
callRoute(
'post',
'/rao',
makeReq({ body: { app_uid: app.uid }, actor: owner.actor }),
res,
),
);
// The handler returned while the INSERT is still outstanding.
expect(captured.body).toEqual({});
expect(writeSpy).toHaveBeenCalled();
} finally {
releaseWrite();
await server.controllers.apps.drainPendingAppOpens();
writeSpy.mockRestore();
}
});
// A stats failure must never turn into a failed app open — and since the
// write is now unawaited, it must not surface as an unhandled rejection.
it('swallows a failing stats write without rejecting the request', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
const writeSpy = vi
.spyOn(server.clients.db, 'write')
.mockRejectedValue(new Error('primary is down'));
try {
const { res, captured } = makeRes();
await withActor(owner.actor, () =>
callRoute(
'post',
'/rao',
makeReq({ body: { app_uid: app.uid }, actor: owner.actor }),
res,
),
);
expect(captured.body).toEqual({});
await expect(
server.controllers.apps.drainPendingAppOpens(),
).resolves.toBeUndefined();
} finally {
writeSpy.mockRestore();
}
});
it('falls back to actor.app.uid when the body omits app_uid', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
@@ -354,6 +425,8 @@ describe('AppController POST /rao', () => {
);
expect(captured.body).toEqual({});
await server.controllers.apps.drainPendingAppOpens();
const rows = (await server.clients.db.read(
'SELECT `app_uid` FROM `app_opens` WHERE `app_uid` = ? AND `user_id` = ?',
[app.uid, owner.userId],
@@ -427,6 +500,73 @@ describe('AppController GET /apps/:name', () => {
expect((arr[0] as Record<string, unknown>).uid).toBe(app.uid);
expect(arr[1]).toBeNull();
});
// The driver is the authoritative producer of launch metadata: it runs
// the hosted-subdomain guard, which this route knows nothing about. The
// route's own entitlement re-check must never turn that denial into an
// affirmative verdict — the GUI launcher appends `puter.auth.token` to
// whatever `index_url` it is handed.
it('preserves the hosted-backing denial for the app owner', async () => {
const owner = await makeUser();
const sub = uniqueName('gone');
const row = await server.stores.subdomain.create({
userId: owner.userId,
subdomain: sub,
});
const app = await createApp(owner.actor, {
index_url: `https://${sub}.site.puter.localhost/`,
});
await server.stores.subdomain.deleteByUuid(
String((row as { uuid: string }).uuid),
{ userId: owner.userId },
);
const { res, captured } = makeRes();
await withActor(owner.actor, () =>
callRoute(
'get',
'/apps/:name',
makeReq({ params: { name: app.name }, actor: owner.actor }),
res,
),
);
const body = captured.body as Record<string, unknown>;
expect(body.privateAccess).toMatchObject({
hasAccess: false,
reason: 'hosted_backing_unavailable',
});
});
it('omits the stale index_url for a non-owner', async () => {
const owner = await makeUser();
const stranger = await makeUser();
const sub = uniqueName('gone');
const row = await server.stores.subdomain.create({
userId: owner.userId,
subdomain: sub,
});
const app = await createApp(owner.actor, {
index_url: `https://${sub}.site.puter.localhost/`,
});
await server.stores.subdomain.deleteByUuid(
String((row as { uuid: string }).uuid),
{ userId: owner.userId },
);
const { res, captured } = makeRes();
await withActor(stranger.actor, () =>
callRoute(
'get',
'/apps/:name',
makeReq({ params: { name: app.name }, actor: stranger.actor }),
res,
),
);
const body = captured.body as Record<string, unknown>;
expect(body.index_url).toBeUndefined();
expect(body.privateAccess).toMatchObject({ hasAccess: false });
});
});
// ── POST /query/app ─────────────────────────────────────────────────
@@ -649,7 +789,9 @@ describe('AppController GET /app-icon/:app_uid', () => {
it('decodes a data URL icon and serves the declared MIME', async () => {
const owner = await makeUser();
const png = Buffer.from('mock-png-bytes');
// Real PNG bytes: the write path sniffs the decoded payload and
// rejects anything that isn't the image type it claims to be.
const png = Buffer.from(MINIMAL_PNG_BASE64, 'base64');
const dataUrl = `data:image/png;base64,${png.toString('base64')}`;
const app = await createApp(owner.actor, { icon: dataUrl });
@@ -666,6 +808,25 @@ describe('AppController GET /app-icon/:app_uid', () => {
expect((captured.body as Buffer).equals(png)).toBe(true);
});
// Icons are fetched on every app launch, over a connection the launch is
// already competing for. The inline path must not be cached more briefly
// than the redirect path that serves the same resource.
it('caches an inline data-URL icon as long as the redirect path', async () => {
const owner = await makeUser();
const dataUrl = `data:image/png;base64,${MINIMAL_PNG_BASE64}`;
const app = await createApp(owner.actor, { icon: dataUrl });
const { res, captured } = makeRes();
await callRoute(
'get',
'/app-icon/:app_uid',
makeReq({ params: { app_uid: app.uid } }),
res,
);
expect(captured.headers['cache-control']).toBe('public, max-age=900');
});
it('falls back to the default icon when the data-URL MIME is not allowlisted', async () => {
const owner = await makeUser();
// text/html is NOT in the icon allowlist — must NOT be echoed back.
@@ -707,3 +868,175 @@ describe('AppController GET /app-icon/:app_uid', () => {
expect(captured.statusCode).toBe(200);
});
});
// ── /rao actor gating ───────────────────────────────────────────────
describe('AppController POST /rao actor gating', () => {
it('refuses to record an open for a scoped access token', async () => {
const { actor } = await makeUser();
const app = await createApp(actor);
// Shared / scoped credentials must not drive analytics counters.
const tokenActor = {
...actor,
accessToken: { uuid: uuidv4(), permissions: [] },
} as unknown as Actor;
const { res } = makeRes();
await expect(
withActor(tokenActor, () =>
callRoute(
'post',
'/rao',
makeReq({
body: { app_uid: app.uid },
actor: tokenActor,
}),
res,
),
),
).rejects.toMatchObject({ statusCode: 403, legacyCode: 'forbidden' });
});
it("refuses to let an app actor record another app's open", async () => {
const { actor } = await makeUser();
const own = await createApp(actor);
const other = await createApp(actor);
const appActor = {
...actor,
app: { uid: own.uid as string },
} as unknown as Actor;
const { res } = makeRes();
await expect(
withActor(appActor, () =>
callRoute(
'post',
'/rao',
makeReq({
body: { app_uid: other.uid },
actor: appActor,
}),
res,
),
),
).rejects.toMatchObject({ statusCode: 403, legacyCode: 'forbidden' });
});
});
// ── app-icon redirect + fallback paths ──────────────────────────────
describe('AppController GET /app-icon remote icons', () => {
// AppDriver.create validates the `icon` column, so these fixtures write
// it straight to the row. AppStore caches by uid — drop that entry or the
// handler reads the pre-update app back.
const setIcon = async (uid: string, icon: string) => {
await server.clients.db.write(
'UPDATE `apps` SET `icon` = ? WHERE `uid` = ?',
[icon, uid],
);
await server.stores.app.invalidateByUid(uid);
};
it('redirects to an icon hosted on a trusted host', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
const { static_hosting_domain: hostingDomain } = (
server.controllers.apps as unknown as {
config: { static_hosting_domain: string };
}
).config;
const trusted = `https://puter-app-icons.${hostingDomain}/${app.uid}-128.png`;
await setIcon(String(app.uid), trusted);
const { res, captured } = makeRes();
await callRoute(
'get',
'/app-icon/:app_uid',
makeReq({ params: { app_uid: app.uid } }),
res,
);
expect(captured.redirectStatus).toBe(302);
expect(captured.redirectUrl).toBe(trusted);
expect(captured.headers['cache-control']).toBe('public, max-age=900');
});
it('never redirects to an icon URL on an untrusted host', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
// An open redirect here would let an app row point browsers anywhere.
await setIcon(String(app.uid), 'https://evil.example.com/icon.png');
const { res, captured } = makeRes();
await callRoute(
'get',
'/app-icon/:app_uid',
makeReq({ params: { app_uid: app.uid } }),
res,
);
expect(captured.redirectUrl).toBeUndefined();
expect(captured.headers['content-type']).toContain('image/svg+xml');
});
it('serves the default icon for a malformed data URL with no comma', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
await setIcon(String(app.uid), 'data:image/png;base64');
const { res, captured } = makeRes();
await callRoute(
'get',
'/app-icon/:app_uid',
makeReq({ params: { app_uid: app.uid } }),
res,
);
expect(captured.headers['content-type']).toContain('image/svg+xml');
});
it('serves the default icon for an unknown app uid', async () => {
const { res, captured } = makeRes();
await callRoute(
'get',
'/app-icon/:app_uid',
makeReq({ params: { app_uid: `app-${uuidv4()}` } }),
res,
);
expect(captured.headers['content-type']).toContain('image/svg+xml');
});
it('serves the default icon for a bare (non-URL, non-data) icon value', async () => {
const owner = await makeUser();
const app = await createApp(owner.actor);
await setIcon(String(app.uid), 'legacy-icon-name.png');
const { res, captured } = makeRes();
await callRoute(
'get',
'/app-icon/:app_uid/:size',
makeReq({ params: { app_uid: app.uid, size: '64' } }),
res,
);
expect(captured.headers['content-type']).toContain('image/svg+xml');
});
});
// ── app-icon rate limit ─────────────────────────────────────────────
describe('AppController app-icon rate limit', () => {
it('sizes the icon bucket for a whole network rather than one desktop', () => {
// Icons are unauthenticated `<img src>` targets, so the only key is
// the address — which one NAT shares across every desktop behind it,
// and each boot pulls the taskbar's icons in a burst.
for (const path of ['/app-icon/:app_uid', '/app-icon/:app_uid/:size']) {
const route = router.routes.find(
(r) => r.method === 'get' && r.path === path,
);
if (!route) throw new Error(`No GET ${path} route`);
expect(route.options.rateLimit).toEqual({
scope: 'app-icon',
limit: 12_000,
window: 60_000,
key: 'ip',
});
}
});
});
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,103 @@
/*
* 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/>.
*/
/**
* Wiring test for `guiOriginOnly`.
*
* `originGate.test.ts` covers what the gate decides. This covers that the
* routes which hand a session credential back to the caller actually opt into
* it — a correct gate wired to nothing protects nothing, and the failure is
* invisible (the route keeps working, just for everybody).
*/
import { describe, expect, it } from 'vitest';
import { AuthController } from './AuthController.js';
import {
ROUTES_METADATA_KEY,
type CollectedRoute,
} from '../../core/http/types.js';
// The decorators register on the prototype via `addInitializer`, which only
// runs once an instance exists. We never start this one — constructing it is
// enough to populate the route metadata.
const collectRoutes = (): CollectedRoute[] => {
const proto = AuthController.prototype as unknown as Record<
string,
CollectedRoute[] | undefined
>;
if (!proto[ROUTES_METADATA_KEY]) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (AuthController as any)({}, {}, {}, {}, {});
}
return proto[ROUTES_METADATA_KEY] ?? [];
};
/**
* Every route that answers with a usable session credential. Adding one here
* without `guiOriginOnly` is the mistake this test exists to catch: reflected
* CORS would let any page read the credential out of the response.
*/
const CREDENTIAL_ROUTES: Array<[method: string, path: string]> = [
['post', '/login'],
['post', '/login/otp'],
['post', '/login/recovery-code'],
['post', '/signup'],
['get', '/session/sync-cookie'],
];
describe('guiOriginOnly wiring on AuthController', () => {
const routes = collectRoutes();
it('registers the routes under test at all (guards against a rename)', () => {
for (const [method, path] of CREDENTIAL_ROUTES) {
const found = routes.find(
(r) => r.method === method && r.path === path,
);
expect(found, `${method.toUpperCase()} ${path} not registered`)
.toBeDefined();
}
});
it.each(CREDENTIAL_ROUTES)(
'gates %s %s to the GUI origin',
(method, path) => {
const route = routes.find(
(r) => r.method === method && r.path === path,
);
expect(route?.options.guiOriginOnly).toBe(true);
},
);
// The popup relay is the third-party sign-in path: `puter.auth.signIn()`
// polls `/login/wait` from whatever origin the app is served from, and
// `/login/set` is posted by the popup. Gating either to our own origin
// would break every third-party app, and neither needs it — the token
// they move is app-scoped, not a session.
it.each([
['post', '/login/wait'],
['post', '/login/set'],
])('leaves %s %s open cross-origin', (method, path) => {
const route = routes.find(
(r) => r.method === method && r.path === path,
);
expect(route, `${method.toUpperCase()} ${path} not registered`)
.toBeDefined();
expect(route?.options.guiOriginOnly).toBeUndefined();
});
});
@@ -1,4 +1,4 @@
/**
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
Loaded 100 of 1073 files, more files were not shown because too many files have changed in this diff. Show more