mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5918e3f4e2 | ||
|
|
2c9e818e5f | ||
|
|
8826a9fc51 | ||
|
|
8307e8c9f0 | ||
|
|
732786a029 | ||
|
|
f0cd251626 | ||
|
|
943adae622 | ||
|
|
65572dcf23 | ||
|
|
b3923f86da | ||
|
|
729114bd09 | ||
|
|
da1c85d3c5 | ||
|
|
66410d7f1f | ||
|
|
76bd05f228 | ||
|
|
fef1337b2b | ||
|
|
58794f4f76 | ||
|
|
9809e428b5 | ||
|
|
eaddd1d44e | ||
|
|
53b792c52c | ||
|
|
2dd7073034 | ||
|
|
a552ce0b87 | ||
|
|
c04827fd3f | ||
|
|
9debdffc5d | ||
|
|
57b4cbab66 | ||
|
|
5e1645d40e | ||
|
|
b795b219a8 | ||
|
|
401b6066b3 | ||
|
|
ec3c33fea6 | ||
|
|
95d797b047 | ||
|
|
bd06e88185 | ||
|
|
cabedc30b0 | ||
|
|
f81b76c1d1 | ||
|
|
9604cc3f23 | ||
|
|
2c852bf6b3 | ||
|
|
fc861da89f | ||
|
|
facb844747 | ||
|
|
3b791bb334 | ||
|
|
a64a444a17 | ||
|
|
d3c9828207 | ||
|
|
87180b1081 | ||
|
|
d22b656df8 | ||
|
|
19cd5f4476 | ||
|
|
fc56075115 | ||
|
|
e1998e39ab | ||
|
|
fb7968a1c7 | ||
|
|
c88eeb3868 | ||
|
|
9e25ce1401 | ||
|
|
f15d835eeb | ||
|
|
27c4506e02 | ||
|
|
6a7c09f54e | ||
|
|
6254714484 | ||
|
|
efa2cb4441 | ||
|
|
4bc969b99e | ||
|
|
65f6d38432 | ||
|
|
d641f6f7a1 | ||
|
|
00828b9998 | ||
|
|
126ec09556 | ||
|
|
25a5799088 | ||
|
|
ea2f9967a6 | ||
|
|
ba9b885a5a | ||
|
|
6cc241ac31 | ||
|
|
7f8e24f06d | ||
|
|
9b6627b1ea | ||
|
|
7576e0b03a | ||
|
|
d980a9f590 | ||
|
|
d18ea1adb5 | ||
|
|
08f075d774 | ||
|
|
664de0016b | ||
|
|
e273431f14 | ||
|
|
8ed8feed4b | ||
|
|
22f5bf5429 | ||
|
|
198184f986 | ||
|
|
026ae46530 | ||
|
|
0615c3aa3c | ||
|
|
748461aabb | ||
|
|
78cfe0c0f6 | ||
|
|
81f9f00fc0 | ||
|
|
556380cf16 | ||
|
|
908ec23eda | ||
|
|
d5ae5a0049 | ||
|
|
419d0aaa89 | ||
|
|
c3a0c28705 | ||
|
|
7ceb2090b7 |
No files matched your search
@@ -52,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).
|
||||
|
||||
---
|
||||
|
||||
|
||||
+39
-35
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||

|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
+41
-2
@@ -251,6 +251,28 @@
|
||||
}
|
||||
},
|
||||
|
||||
// ── 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`:
|
||||
@@ -324,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": "" },
|
||||
@@ -341,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
|
||||
@@ -448,8 +484,11 @@
|
||||
// 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.
|
||||
// "meteringEnforcement": { "enabled": true, "workers": false },
|
||||
// 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
|
||||
|
||||
+9
-1
@@ -44,7 +44,15 @@ pass one explicitly unless you really mean "page someone".
|
||||
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.
|
||||
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 —
|
||||
|
||||
@@ -53,7 +53,9 @@ 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
|
||||
|
||||
@@ -122,6 +122,10 @@ cat > puter/config/config.json <<EOF
|
||||
"ollama": { "enabled": false }
|
||||
},
|
||||
|
||||
"meteringEnforcement": {
|
||||
"subscriptions": false
|
||||
},
|
||||
|
||||
"trust_proxy": 1
|
||||
}
|
||||
EOF
|
||||
@@ -136,6 +140,7 @@ Why these knobs:
|
||||
- `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. 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.
|
||||
@@ -295,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
|
||||
|
||||
+107
-3
@@ -6,6 +6,10 @@ import {
|
||||
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');
|
||||
@@ -50,6 +54,42 @@ function collectAllCosts(): Record<string, unknown>[] {
|
||||
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,
|
||||
@@ -61,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 (
|
||||
@@ -92,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 (
|
||||
@@ -109,7 +197,23 @@ 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 });
|
||||
};
|
||||
|
||||
@@ -206,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({
|
||||
|
||||
+80
-3
@@ -33,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,
|
||||
@@ -74,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,
|
||||
@@ -84,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,
|
||||
@@ -92,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(
|
||||
@@ -172,6 +244,8 @@ export const handleWhoami = async (
|
||||
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) {
|
||||
@@ -196,6 +270,9 @@ export const handleWhoami = async (
|
||||
delete subscription.offering.price_id;
|
||||
}
|
||||
|
||||
// Last word on what ships, after every listener has had its say.
|
||||
scrubSensitive(details);
|
||||
|
||||
res.json(details);
|
||||
};
|
||||
|
||||
|
||||
@@ -131,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
|
||||
{
|
||||
@@ -191,6 +196,10 @@ EOF
|
||||
"ollama": { "enabled": false }
|
||||
},
|
||||
|
||||
"meteringEnforcement": {
|
||||
"subscriptions": false
|
||||
},
|
||||
|
||||
"trust_proxy": $PUTER_TRUST_PROXY
|
||||
}
|
||||
EOF
|
||||
|
||||
Generated
+2102
-3710
File diff suppressed because it is too large.
Load diff
+14
-25
@@ -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,25 +25,19 @@
|
||||
"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 && npm run build:workerLib && vitest run --config src/backend/vitest.config.ts ",
|
||||
@@ -73,9 +62,7 @@
|
||||
"setupExtensions": "node ./tools/extensionSetup.mjs"
|
||||
},
|
||||
"workspaces": [
|
||||
"src/*",
|
||||
"tools/*",
|
||||
"experiments/js-parse-and-output"
|
||||
"src/*"
|
||||
],
|
||||
"nodemonConfig": {
|
||||
"ext": "js, json, mjs, jsx, svg, css",
|
||||
@@ -85,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",
|
||||
@@ -101,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"
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
||||
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';
|
||||
@@ -27,7 +27,15 @@ import { DatabaseClientFactory } from './index.js';
|
||||
import { SqliteDatabaseClient } from './SqliteDatabaseClient.js';
|
||||
|
||||
/** Highest schema version the migration table can reach. */
|
||||
const CURRENT_SCHEMA_VERSION = 60;
|
||||
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 = (
|
||||
@@ -52,7 +60,7 @@ const userVersionOf = async (client: SqliteDatabaseClient): Promise<number> => {
|
||||
return row.user_version as number;
|
||||
};
|
||||
|
||||
describe('SqliteDatabaseClient — boot and migrations', () => {
|
||||
describe('SqliteDatabaseClient — boot and migrations', { timeout: DISK_MIGRATION_TIMEOUT_MS }, () => {
|
||||
let client: SqliteDatabaseClient;
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -83,6 +91,105 @@ describe('SqliteDatabaseClient — boot and migrations', () => {
|
||||
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');
|
||||
@@ -137,7 +244,10 @@ describe('SqliteDatabaseClient — boot and migrations', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('SqliteDatabaseClient — legacy version inference', () => {
|
||||
describe(
|
||||
'SqliteDatabaseClient — legacy version inference',
|
||||
{ timeout: DISK_MIGRATION_TIMEOUT_MS },
|
||||
() => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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`);
|
||||
@@ -3,18 +3,19 @@
|
||||
*
|
||||
* 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/>.
|
||||
* along with this program. If not, see
|
||||
* [https://www.gnu.org/licenses/](https://www.gnu.org/licenses/).
|
||||
*/
|
||||
|
||||
import { createServer, type Server } from 'node:http';
|
||||
@@ -302,6 +303,35 @@ describe('DDBClient — batch writes', () => {
|
||||
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', () => {
|
||||
|
||||
@@ -45,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>>();
|
||||
@@ -114,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;
|
||||
@@ -171,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[]) => ({
|
||||
@@ -222,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: [] };
|
||||
@@ -258,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;
|
||||
},
|
||||
@@ -278,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
|
||||
@@ -328,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();
|
||||
@@ -423,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(
|
||||
@@ -538,6 +638,9 @@ export class DDBClient extends PuterClient {
|
||||
marshallOptions: {
|
||||
removeUndefinedValues: true,
|
||||
},
|
||||
unmarshallOptions: {
|
||||
wrapNumbers: clampStoredNumber,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -565,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);
|
||||
};
|
||||
@@ -54,14 +54,22 @@ const sentMessage = (info: unknown) =>
|
||||
};
|
||||
|
||||
describe('EmailClient — transport lifecycle', () => {
|
||||
it('reports as configured once a transport is wired up', () => {
|
||||
it('stops sending once the transport is shut down', async () => {
|
||||
const client = startClient();
|
||||
expect(client.isConfigured).toBe(true);
|
||||
expect(
|
||||
await client.sendRaw({ to: '[email protected]', subject: 'up', text: 'x' }),
|
||||
).not.toBeNull();
|
||||
|
||||
client.onServerShutdown();
|
||||
expect(client.isConfigured).toBe(false);
|
||||
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
expect(
|
||||
await client.sendRaw({ to: '[email protected]', subject: 'down', text: 'x' }),
|
||||
).toBeNull();
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('warns and stays unconfigured when no transport is set', () => {
|
||||
it('warns at boot when no transport is set', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const client = new EmailClient({
|
||||
port: 0,
|
||||
@@ -69,7 +77,6 @@ describe('EmailClient — transport lifecycle', () => {
|
||||
} as unknown as IConfig);
|
||||
client.onServerStart();
|
||||
|
||||
expect(client.isConfigured).toBe(false);
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('no email transport configured'),
|
||||
);
|
||||
@@ -179,6 +186,29 @@ describe('EmailClient — template rendering', () => {
|
||||
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 = '';
|
||||
@@ -215,6 +245,139 @@ describe('EmailClient — template rendering', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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&d "notes".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);
|
||||
|
||||
|
||||
@@ -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 ------------------------------------------------
|
||||
@@ -152,11 +157,16 @@ 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) {
|
||||
@@ -168,6 +178,8 @@ 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 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -177,7 +189,8 @@ export class EmailClient extends PuterClient {
|
||||
*
|
||||
* 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).
|
||||
* silently drop mail should check `config.email` before composing, or the
|
||||
* `null` return after).
|
||||
*/
|
||||
async sendRaw(options: SendMailOptions) {
|
||||
if (!this.transport) {
|
||||
@@ -193,11 +206,6 @@ 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 ---------------------------------
|
||||
|
||||
/**
|
||||
@@ -283,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 (& 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,
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,8 +29,184 @@
|
||||
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 = '͏‌ '.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>;
|
||||
|
||||
@@ -32,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>;
|
||||
@@ -142,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;
|
||||
@@ -290,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': {
|
||||
@@ -338,12 +379,39 @@ export type EventMap = {
|
||||
// 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
|
||||
@@ -367,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;
|
||||
@@ -460,7 +530,7 @@ export type EventMap = {
|
||||
* 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`
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -38,7 +38,11 @@ import type { Actor } from '../../core/actor.js';
|
||||
import { Context, runWithContext } from '../../core/context.js';
|
||||
import { HttpError } from '../../core/http/HttpError.js';
|
||||
import { requireUserActorGate } from '../../core/http/middleware/gates.js';
|
||||
import type { TokenSource } from '../../core/http/types.js';
|
||||
import {
|
||||
ROUTES_METADATA_KEY,
|
||||
type CollectedRoute,
|
||||
type TokenSource,
|
||||
} from '../../core/http/types.js';
|
||||
import { PuterServer } from '../../server.js';
|
||||
import { FULL_API_ACCESS } from '../../services/permission/consts.js';
|
||||
import { setupTestServer } from '../../testUtil.js';
|
||||
@@ -346,6 +350,188 @@ describe('puter.signup.validate event', () => {
|
||||
|
||||
// ── Signup flow ─────────────────────────────────────────────────────
|
||||
|
||||
// ── Concurrent claims on one address ────────────────────────────────
|
||||
//
|
||||
// The duplicate checks these flows run are not atomic with the writes that
|
||||
// follow them — the validate hook and bcrypt sit in between, and both are slow
|
||||
// enough for a second request to pass the same check. These tests fire the
|
||||
// requests together and assert the address still ends up on exactly one row.
|
||||
|
||||
describe('concurrent claims on one email address', () => {
|
||||
const uniq = () => Math.random().toString(36).slice(2, 10);
|
||||
|
||||
const countOwners = async (email: string): Promise<number> => {
|
||||
// `email_confirmed` is TINYINT on MySQL and BOOLEAN on Postgres, so the
|
||||
// literal has to come from the client rather than be hardcoded.
|
||||
const isTrue = server.clients.db.booleanLiteral(true);
|
||||
const rows = (await server.clients.db.read(
|
||||
`SELECT COUNT(*) AS n FROM \`user\` WHERE \`email\` = ? AND (\`email_confirmed\` = ${isTrue} OR \`password\` IS NOT NULL)`,
|
||||
[email],
|
||||
)) as Array<{ n: number }>;
|
||||
return Number(rows[0]?.n ?? 0);
|
||||
};
|
||||
|
||||
it('lets only one of two simultaneous signups take the address', async () => {
|
||||
const email = `race-${uniq()}@test.local`;
|
||||
const signup = (username: string) =>
|
||||
controller.handleSignup(
|
||||
makeReq({ username, email, password: 'correct-horse-battery' }),
|
||||
makeRes(),
|
||||
);
|
||||
|
||||
// Distinct usernames on purpose: the UNIQUE on `username` would
|
||||
// otherwise be what rejects the second request, and the email race
|
||||
// would go untested.
|
||||
const results = await Promise.allSettled([
|
||||
signup(`r_a_${uniq()}`),
|
||||
signup(`r_b_${uniq()}`),
|
||||
]);
|
||||
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(await countOwners(email)).toBe(1);
|
||||
|
||||
const rejected = results.find((r) => r.status === 'rejected') as
|
||||
| PromiseRejectedResult
|
||||
| undefined;
|
||||
expect(rejected?.reason).toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('lets only one of many simultaneous signups take the address', async () => {
|
||||
const email = `race-many-${uniq()}@test.local`;
|
||||
const results = await Promise.allSettled(
|
||||
Array.from({ length: 5 }, () =>
|
||||
controller.handleSignup(
|
||||
makeReq({
|
||||
username: `r_m_${uniq()}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(await countOwners(email)).toBe(1);
|
||||
});
|
||||
|
||||
it('rejects a signup racing an admin-provisioned placeholder claim', async () => {
|
||||
const email = `race-pseudo-${uniq()}@test.local`;
|
||||
// The placeholder shape signup is allowed to convert: unconfirmed,
|
||||
// no password. Two signups both see it as claimable.
|
||||
await server.stores.user.create({
|
||||
username: `r_p_${uniq()}`,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email,
|
||||
clean_email: email,
|
||||
});
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
controller.handleSignup(
|
||||
makeReq({
|
||||
username: `r_p_a_${uniq()}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
),
|
||||
controller.handleSignup(
|
||||
makeReq({
|
||||
username: `r_p_b_${uniq()}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
),
|
||||
]);
|
||||
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(await countOwners(email)).toBe(1);
|
||||
});
|
||||
|
||||
it('reports a duplicate address as a 400, not a constraint error', async () => {
|
||||
const email = `dupe-${uniq()}@test.local`;
|
||||
await controller.handleSignup(
|
||||
makeReq({
|
||||
username: `d_a_${uniq()}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
);
|
||||
|
||||
// The message has to be the one the pre-check produces — a user who
|
||||
// loses the race should not be able to tell.
|
||||
await expect(
|
||||
controller.handleSignup(
|
||||
makeReq({
|
||||
username: `d_b_${uniq()}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
message:
|
||||
'This email already exists in our database. Please use another one.',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses to give a placeholder row a password for a taken address', async () => {
|
||||
const email = `recover-${uniq()}@test.local`;
|
||||
await controller.handleSignup(
|
||||
makeReq({
|
||||
username: `rec_own_${uniq()}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
);
|
||||
|
||||
// An unconfirmed, password-less row is allowed to sit on the same
|
||||
// address — but password recovery accepts a username, so it can be
|
||||
// driven for this row rather than for the account that owns the
|
||||
// address. Setting a password here would make it a second account able
|
||||
// to recover that inbox.
|
||||
const placeholderName = `rec_ph_${uniq()}`;
|
||||
const placeholder = await server.stores.user.create({
|
||||
username: placeholderName,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email,
|
||||
clean_email: email,
|
||||
});
|
||||
const token = uuidv4();
|
||||
await server.stores.user.update(placeholder.id, {
|
||||
pass_recovery_token: token,
|
||||
});
|
||||
|
||||
const jwt = server.services.token.sign(
|
||||
'otp',
|
||||
{
|
||||
token,
|
||||
user_uid: placeholder.uuid,
|
||||
email,
|
||||
purpose: 'pass-recovery',
|
||||
},
|
||||
{ expiresIn: '1h' },
|
||||
);
|
||||
|
||||
await expect(
|
||||
controller.handleSetPassUsingToken(
|
||||
makeReq({ token: jwt, password: 'another-strong-password' }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
message:
|
||||
'This email is already in use. Recover the account that uses it instead.',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthController.handleSignup', () => {
|
||||
const uniq = () => Math.random().toString(36).slice(2, 10);
|
||||
|
||||
@@ -1499,59 +1685,6 @@ describe('AuthController grant flows', () => {
|
||||
} as Actor;
|
||||
});
|
||||
|
||||
it('grant-user-user: rejects missing target_username/permission with 400', async () => {
|
||||
await expect(
|
||||
controller.handleGrantUserUser(
|
||||
makeReq({ permission: 'fs:read' }, { actor: issuerActor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('grant-user-user: persists the permission and PermissionService.check sees it', async () => {
|
||||
const permission = `service:test-grant-${uuidv4()}:ii:read`;
|
||||
// The controller calls PermissionService.grantUserUserPermission,
|
||||
// which gates on `manage:<permission>` for non-system actors. Pre-
|
||||
// bootstrap the manage flag directly through the permission store
|
||||
// (the system actor would skip this gate, but its in-memory shape
|
||||
// has no user.id, so it can't issue grants). Then the controller
|
||||
// call exercises persist + check end-to-end.
|
||||
await server.stores.permission.setFlatUserPerm(
|
||||
issuer.id,
|
||||
`manage:${permission}`,
|
||||
{
|
||||
permission: `manage:${permission}`,
|
||||
deleted: false,
|
||||
issuer_user_id: issuer.id,
|
||||
} as never,
|
||||
);
|
||||
|
||||
const res = makeRes();
|
||||
await inCtx(issuerActor, () =>
|
||||
controller.handleGrantUserUser(
|
||||
makeReq(
|
||||
{
|
||||
target_username: target.username,
|
||||
permission,
|
||||
extra: { reason: 'unit-test' },
|
||||
},
|
||||
{ actor: issuerActor },
|
||||
),
|
||||
res,
|
||||
),
|
||||
);
|
||||
expect(res.body).toEqual({});
|
||||
|
||||
// The target now sees the permission via the user-to-user grant.
|
||||
const targetActor = {
|
||||
user: { ...target, email_confirmed: true },
|
||||
} as Actor;
|
||||
const granted = await server.services.permission
|
||||
.check(targetActor, permission)
|
||||
.catch(() => false);
|
||||
expect(granted).toBeTruthy();
|
||||
});
|
||||
|
||||
it('grant-user-app: persists a user→app permission grant', async () => {
|
||||
// Create an app row owned by the issuer so the grant has somewhere
|
||||
// to land.
|
||||
@@ -2039,20 +2172,6 @@ describe('AuthController grant flows', () => {
|
||||
expect(await storedPermissions()).not.toContain(NOTHING);
|
||||
});
|
||||
|
||||
it('grant-user-group: 404 when the group does not exist', async () => {
|
||||
await expect(
|
||||
controller.handleGrantUserGroup(
|
||||
makeReq(
|
||||
{
|
||||
group_uid: `does-not-exist-${uuidv4()}`,
|
||||
permission: 'service:foo:ii:read',
|
||||
},
|
||||
{ actor: issuerActor },
|
||||
),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── Token grants: get-user-app-token / check-app ───────────────────
|
||||
@@ -3235,8 +3354,10 @@ describe('AuthController.handleConfirmPhone', () => {
|
||||
});
|
||||
|
||||
describe('AuthController.handleCardVerificationSetup', () => {
|
||||
it('short-circuits to verified when the gate is not set', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
it('short-circuits to verified for an account with a card on file', async () => {
|
||||
const { actor } = await makeUserAndActor({
|
||||
card_fingerprint: 'fp_existing',
|
||||
});
|
||||
const res = makeRes();
|
||||
await controller.handleCardVerificationSetup(
|
||||
makeReq({}, { actor }),
|
||||
@@ -3245,6 +3366,21 @@ describe('AuthController.handleCardVerificationSetup', () => {
|
||||
expect(res.body).toMatchObject({ card_verified: true });
|
||||
});
|
||||
|
||||
it('starts the flow for an account that was never asked and never verified', async () => {
|
||||
// A route requiring a verified card (`requireCardVerified`) sends a
|
||||
// user here with the gate clear and no card on file. Answering
|
||||
// "already verified" on the flag alone would bounce them between a
|
||||
// dialog reporting success and a route that keeps refusing; reaching
|
||||
// the extension (absent here, hence 503) is the flow actually running.
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleCardVerificationSetup(
|
||||
makeReq({}, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 503 });
|
||||
});
|
||||
|
||||
it('throws 403 when the account is suspended', async () => {
|
||||
const { actor } = await makeUserAndActor({
|
||||
requires_card_verification: 1,
|
||||
@@ -3345,8 +3481,10 @@ describe('AuthController.handleCardVerificationConfirm', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('short-circuits to verified when the gate is not set', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
it('short-circuits to verified for an account with a card on file', async () => {
|
||||
const { actor } = await makeUserAndActor({
|
||||
card_fingerprint: 'fp_existing',
|
||||
});
|
||||
const res = makeRes();
|
||||
await controller.handleCardVerificationConfirm(
|
||||
makeReq({ setup_intent_id: 'seti_1' }, { actor }),
|
||||
@@ -3355,6 +3493,18 @@ describe('AuthController.handleCardVerificationConfirm', () => {
|
||||
expect(res.body).toMatchObject({ card_verified: true });
|
||||
});
|
||||
|
||||
it('runs the confirm for an account that was never asked and never verified', async () => {
|
||||
// Same reason as setup: the pending flag says nobody asked, not that
|
||||
// a card was checked, so a voluntary verification has to go through.
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleCardVerificationConfirm(
|
||||
makeReq({ setup_intent_id: 'seti_1' }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 503 });
|
||||
});
|
||||
|
||||
it('throws 409 when phone verification must be completed first', async () => {
|
||||
const { actor } = await makeUserAndActor({
|
||||
requires_card_verification: 1,
|
||||
@@ -3847,6 +3997,151 @@ describe('AuthController.handleConfirmEmail', () => {
|
||||
});
|
||||
expect(after!.email_confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('strips a rival placeholder before confirming, not after', async () => {
|
||||
const { user, actor } = await makeUserAndActor();
|
||||
const email = user.email as string;
|
||||
|
||||
// A placeholder sitting on the same address. Confirming first and
|
||||
// demoting second would momentarily leave two rows owning it, which
|
||||
// the unique index rejects — turning a legitimate confirmation into a
|
||||
// 500.
|
||||
const rival = await server.stores.user.create({
|
||||
username: `rival_${Math.random().toString(36).slice(2, 10)}`,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email,
|
||||
clean_email: email,
|
||||
});
|
||||
|
||||
const refreshed = await server.stores.user.getById(user.id, {
|
||||
force: true,
|
||||
});
|
||||
const res = makeRes();
|
||||
await controller.handleConfirmEmail(
|
||||
makeReq({ code: refreshed!.email_confirm_code! }, { actor }),
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.body).toMatchObject({ email_confirmed: true });
|
||||
const confirmed = await server.stores.user.getById(user.id, {
|
||||
force: true,
|
||||
});
|
||||
expect(confirmed!.email_confirmed).toBe(true);
|
||||
const strippedRival = await server.stores.user.getById(rival.id, {
|
||||
force: true,
|
||||
});
|
||||
expect(strippedRival!.email).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses when another account already confirmed the address', async () => {
|
||||
const email = `owned-${uniq()}@test.local`;
|
||||
|
||||
// Confirmed with no password is the shape an identity provider
|
||||
// creates, and it is what the old rival check (which also demanded a
|
||||
// password) let through. Demoting it would take the address off an
|
||||
// account that proved it owns the inbox.
|
||||
const owner = await server.stores.user.create({
|
||||
username: `owner_${uniq()}`,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email,
|
||||
clean_email: email,
|
||||
email_confirmed: true,
|
||||
});
|
||||
|
||||
// A second, unconfirmed row on the same address holding a confirm
|
||||
// code — the legacy duplicate this path used to resolve in its favour.
|
||||
const claimant = await server.stores.user.create({
|
||||
username: `claim_${uniq()}`,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email,
|
||||
clean_email: email,
|
||||
email_confirm_code: '123456',
|
||||
});
|
||||
const actor = {
|
||||
user: {
|
||||
id: claimant.id,
|
||||
uuid: claimant.uuid,
|
||||
username: claimant.username,
|
||||
email,
|
||||
email_confirmed: false,
|
||||
},
|
||||
} as Actor;
|
||||
|
||||
await expect(
|
||||
controller.handleConfirmEmail(
|
||||
makeReq({ code: '123456' }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
|
||||
const untouched = await server.stores.user.getById(owner.id, {
|
||||
force: true,
|
||||
});
|
||||
expect(untouched!.email).toBe(email);
|
||||
expect(untouched!.email_confirmed).toBe(true);
|
||||
const stillUnconfirmed = await server.stores.user.getById(claimant.id, {
|
||||
force: true,
|
||||
});
|
||||
expect(stillUnconfirmed!.email_confirmed).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthController.handleSaveAccount address conflicts', () => {
|
||||
it('refuses to promote a temp account onto a taken address', async () => {
|
||||
const email = `save-${Math.random().toString(36).slice(2, 10)}@test.local`;
|
||||
await controller.handleSignup(
|
||||
makeReq({
|
||||
username: `save_own_${Math.random().toString(36).slice(2, 10)}`,
|
||||
email,
|
||||
password: 'correct-horse-battery',
|
||||
}),
|
||||
makeRes(),
|
||||
);
|
||||
|
||||
const tempRes = makeRes();
|
||||
await controller.handleSignup(makeReq({ is_temp: true }), tempRes);
|
||||
const tempUser = (
|
||||
tempRes.body as { user: { username: string; uuid: string } }
|
||||
).user;
|
||||
const tempRow = await server.stores.user.getByUuid(tempUser.uuid);
|
||||
const actor = {
|
||||
user: {
|
||||
id: tempRow!.id,
|
||||
uuid: tempRow!.uuid,
|
||||
username: tempRow!.username,
|
||||
email: null,
|
||||
email_confirmed: false,
|
||||
},
|
||||
} as Actor;
|
||||
|
||||
await expect(
|
||||
controller.handleSaveAccount(
|
||||
makeReq(
|
||||
{
|
||||
username: `save_new_${Math.random().toString(36).slice(2, 10)}`,
|
||||
email,
|
||||
password: 'another-strong-password',
|
||||
},
|
||||
{ actor },
|
||||
),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
legacyCode: 'email_already_in_use',
|
||||
});
|
||||
|
||||
// The temp row must be left alone — a failed promotion that already
|
||||
// wrote the username would strand the account half-converted.
|
||||
const untouched = await server.stores.user.getById(tempRow!.id, {
|
||||
force: true,
|
||||
});
|
||||
expect(untouched!.email).toBeNull();
|
||||
expect(untouched!.password).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Password recovery flow ──────────────────────────────────────────
|
||||
@@ -4453,16 +4748,24 @@ describe('AuthController permission revokes', () => {
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('revoke-user-group: 400 on missing group_uid/permission', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleRevokeUserGroup(
|
||||
makeReq({ permission: 'fs:read' }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
// No in-tree caller, so a later cleanup would read it as dead: pin the gate.
|
||||
it('revoke-user-user: stays registered as a user-actor route', () => {
|
||||
const proto = Object.getPrototypeOf(controller) as Record<
|
||||
string,
|
||||
CollectedRoute[] | undefined
|
||||
>;
|
||||
const route = (proto[ROUTES_METADATA_KEY] ?? []).find(
|
||||
(r) => r.path === '/auth/revoke-user-user',
|
||||
);
|
||||
expect(route, '/auth/revoke-user-user is not registered').toBeDefined();
|
||||
expect(route!.method).toBe('post');
|
||||
expect(route!.options).toMatchObject({
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
});
|
||||
});
|
||||
|
||||
// Why the deprecated route exists: older grants stay withdrawable.
|
||||
it('revoke-user-user: round-trips a grant + revoke without throwing', async () => {
|
||||
const { actor: issuerActor, user: issuer } = await makeUserAndActor();
|
||||
const { user: target } = await makeUserAndActor();
|
||||
@@ -4476,24 +4779,17 @@ describe('AuthController permission revokes', () => {
|
||||
issuer_user_id: issuer.id,
|
||||
} as never,
|
||||
);
|
||||
// Grant first.
|
||||
// Through the service: the grant route is retired, the revoke is not.
|
||||
await inCtx(issuerActor, () =>
|
||||
controller.handleGrantUserUser(
|
||||
makeReq(
|
||||
{ target_username: target.username, permission },
|
||||
{ actor: issuerActor },
|
||||
),
|
||||
makeRes(),
|
||||
server.services.permission.grantUserUserPermission(
|
||||
issuerActor,
|
||||
target.username,
|
||||
permission,
|
||||
),
|
||||
);
|
||||
|
||||
// Now revoke — must complete without throwing and return {}.
|
||||
// We don't re-assert the post-revoke `check()` answer here: the
|
||||
// Redis-mock scan cache is process-wide, and intervening grants
|
||||
// from other tests have repeatedly been observed to leave the
|
||||
// cached `true` answer in place even after a successful revoke.
|
||||
// Verifying the controller path rather than the cache eviction
|
||||
// semantics keeps this test focused.
|
||||
// Asserts the controller path only: the process-wide Redis-mock scan
|
||||
// cache makes a post-revoke `check()` unreliable across tests.
|
||||
const res = makeRes();
|
||||
await inCtx(issuerActor, () =>
|
||||
controller.handleRevokeUserUser(
|
||||
@@ -4569,9 +4865,10 @@ describe('AuthController.handleCheckPermissions + handleListPermissions', () =>
|
||||
);
|
||||
|
||||
// A user→user grant must show up under `myself_to_user` for the
|
||||
// issuer and `user_to_myself` for the holder. Grants gate on
|
||||
// `manage:<permission>`, so bootstrap that flag first (mirrors the
|
||||
// grant-user-user persistence test).
|
||||
// issuer and `user_to_myself` for the holder. Seeded through the
|
||||
// service: the grant route is retired, but the listing still has to
|
||||
// report grants made before that, and the ones sharing writes.
|
||||
// Grants gate on `manage:<permission>`, so bootstrap that flag first.
|
||||
const { user: holder, actor: holderActor } = await makeUserAndActor();
|
||||
const userPermission = 'service:tl-user:ii:read';
|
||||
await server.stores.permission.setFlatUserPerm(
|
||||
@@ -4584,16 +4881,11 @@ describe('AuthController.handleCheckPermissions + handleListPermissions', () =>
|
||||
} as never,
|
||||
);
|
||||
await inCtx(actor, () =>
|
||||
controller.handleGrantUserUser(
|
||||
makeReq(
|
||||
{
|
||||
target_username: holder.username,
|
||||
permission: userPermission,
|
||||
extra: {},
|
||||
},
|
||||
{ actor },
|
||||
),
|
||||
makeRes(),
|
||||
server.services.permission.grantUserUserPermission(
|
||||
actor,
|
||||
holder.username,
|
||||
userPermission,
|
||||
{},
|
||||
),
|
||||
);
|
||||
|
||||
@@ -5022,6 +5314,33 @@ describe('AuthController 2FA flows', () => {
|
||||
).toHaveLength(10);
|
||||
});
|
||||
|
||||
it('a recovery code minted by configure-2fa setup satisfies /login/recovery-code', async () => {
|
||||
const { user, actor } = await makeUserAndActor({ email_confirmed: 1 });
|
||||
const setupRes = makeRes();
|
||||
await controller.handleConfigure2fa(
|
||||
makeReq({}, { actor, params: { action: 'setup' } }),
|
||||
setupRes,
|
||||
);
|
||||
const { codes } = setupRes.body as { codes: string[] };
|
||||
|
||||
await controller.handleConfigure2fa(
|
||||
makeReq({}, { actor, params: { action: 'enable' } }),
|
||||
makeRes(),
|
||||
);
|
||||
|
||||
const otpJwt = server.services.token.sign(
|
||||
'otp',
|
||||
{ user_uid: user.uuid, purpose: 'otp-login' },
|
||||
{ expiresIn: '5m' },
|
||||
);
|
||||
const res = makeRes();
|
||||
await controller.handleLoginRecoveryCode(
|
||||
makeReq({ token: otpJwt, code: codes[0] }),
|
||||
res,
|
||||
);
|
||||
expect(isCompleteLoginResponse(res.body)).toBe(true);
|
||||
});
|
||||
|
||||
it('configure-2fa setup: 409 when 2FA is already enabled', async () => {
|
||||
const { actor } = await makeUserAndActor({ otp_enabled: 1 });
|
||||
await expect(
|
||||
@@ -5116,130 +5435,6 @@ describe('AuthController.handleGetDevProfile', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── Group endpoints ────────────────────────────────────────────────
|
||||
|
||||
describe('AuthController group endpoints', () => {
|
||||
it('group/create: rejects non-object extra/metadata with 400', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGroupCreate(
|
||||
makeReq({ extra: ['x'] }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
await expect(
|
||||
controller.handleGroupCreate(
|
||||
makeReq({ metadata: ['x'] }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('group/create + add-users + remove-users: full owner-driven lifecycle', async () => {
|
||||
const { actor: owner } = await makeUserAndActor();
|
||||
const { user: target } = await makeUserAndActor();
|
||||
|
||||
// Create.
|
||||
const createRes = makeRes();
|
||||
await controller.handleGroupCreate(
|
||||
makeReq({ metadata: { name: 'g' } }, { actor: owner }),
|
||||
createRes,
|
||||
);
|
||||
const { uid } = createRes.body as { uid: string };
|
||||
expect(typeof uid).toBe('string');
|
||||
|
||||
// Add.
|
||||
const addRes = makeRes();
|
||||
await controller.handleGroupAddUsers(
|
||||
makeReq({ uid, users: [target.username] }, { actor: owner }),
|
||||
addRes,
|
||||
);
|
||||
expect(addRes.body).toEqual({});
|
||||
|
||||
// Remove.
|
||||
const remRes = makeRes();
|
||||
await controller.handleGroupRemoveUsers(
|
||||
makeReq({ uid, users: [target.username] }, { actor: owner }),
|
||||
remRes,
|
||||
);
|
||||
expect(remRes.body).toEqual({});
|
||||
});
|
||||
|
||||
it('group/add-users: 400 on missing uid or non-array users', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGroupAddUsers(
|
||||
makeReq({ users: ['x'] }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
await expect(
|
||||
controller.handleGroupAddUsers(
|
||||
makeReq({ uid: 'g-1' }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('group/add-users: 404 on unknown uid; 403 when caller doesn’t own the group', async () => {
|
||||
const { actor: a1 } = await makeUserAndActor();
|
||||
const { actor: a2 } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGroupAddUsers(
|
||||
makeReq(
|
||||
{ uid: `does-not-exist-${uuidv4()}`, users: [] },
|
||||
{ actor: a1 },
|
||||
),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 404 });
|
||||
|
||||
// Group owned by a1; a2 tries to add → 403.
|
||||
const createRes = makeRes();
|
||||
await controller.handleGroupCreate(
|
||||
makeReq({}, { actor: a1 }),
|
||||
createRes,
|
||||
);
|
||||
const { uid } = createRes.body as { uid: string };
|
||||
await expect(
|
||||
controller.handleGroupAddUsers(
|
||||
makeReq({ uid, users: [] }, { actor: a2 }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 403 });
|
||||
});
|
||||
|
||||
it('group/list: forwards to GroupStore listByOwner/listByMember (or surfaces the source-side method-name mismatch)', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
const res = makeRes();
|
||||
try {
|
||||
await controller.handleGroupList(makeReq({}, { actor }), res);
|
||||
const body = res.body as {
|
||||
owned_groups: unknown[];
|
||||
in_groups: unknown[];
|
||||
};
|
||||
expect(Array.isArray(body.owned_groups)).toBe(true);
|
||||
expect(Array.isArray(body.in_groups)).toBe(true);
|
||||
} catch (e) {
|
||||
// The handler calls `stores.group.listByOwner(...)`, but the
|
||||
// GroupStore implementation may expose a differently-named
|
||||
// method. Surface the mismatch so a future GroupStore rename
|
||||
// re-enables the assertion above.
|
||||
expect((e as Error).message).toMatch(
|
||||
/listByOwner|listByMember|is not a function/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('group/public-groups: returns {user, temp} from config', async () => {
|
||||
const res = makeRes();
|
||||
await controller.handleGroupPublicGroups(makeReq({}), res);
|
||||
const body = res.body as { user: string | null; temp: string | null };
|
||||
expect(body).toHaveProperty('user');
|
||||
expect(body).toHaveProperty('temp');
|
||||
});
|
||||
});
|
||||
|
||||
// ── GUI token + session sync cookie ────────────────────────────────
|
||||
|
||||
describe('AuthController.handleGetGuiToken + handleSessionSyncCookie', () => {
|
||||
@@ -6125,16 +6320,6 @@ describe('AuthController grant/revoke additional branches', () => {
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('grant-user-group: 400 on missing group_uid', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGrantUserGroup(
|
||||
makeReq({ permission: 'fs:read' }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('revoke-user-app: 400 when permission is "*" but app_uid is missing', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
@@ -6252,58 +6437,6 @@ describe('AuthController.handleGetDevProfile additional branches', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthController group endpoints: additional branches', () => {
|
||||
it('group/remove-users: 400 on missing uid', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGroupRemoveUsers(
|
||||
makeReq({ users: ['x'] }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('group/remove-users: 400 on non-array users', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGroupRemoveUsers(
|
||||
makeReq({ uid: 'g-1' }, { actor }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('group/remove-users: 404 on unknown uid', async () => {
|
||||
const { actor } = await makeUserAndActor();
|
||||
await expect(
|
||||
controller.handleGroupRemoveUsers(
|
||||
makeReq(
|
||||
{ uid: `does-not-exist-${uuidv4()}`, users: [] },
|
||||
{ actor },
|
||||
),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 404 });
|
||||
});
|
||||
|
||||
it('group/remove-users: 403 when caller does not own the group', async () => {
|
||||
const { actor: a1 } = await makeUserAndActor();
|
||||
const { actor: a2 } = await makeUserAndActor();
|
||||
const createRes = makeRes();
|
||||
await controller.handleGroupCreate(
|
||||
makeReq({}, { actor: a1 }),
|
||||
createRes,
|
||||
);
|
||||
const { uid } = createRes.body as { uid: string };
|
||||
await expect(
|
||||
controller.handleGroupRemoveUsers(
|
||||
makeReq({ uid, users: [] }, { actor: a2 }),
|
||||
makeRes(),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 403 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('AuthController.handleGetGuiToken / handleSessionSyncCookie additional branches', () => {
|
||||
it('get-gui-token: 404 when actor has a session but the user row is gone', async () => {
|
||||
const { user, actor } = await makeUserAndActor();
|
||||
|
||||
@@ -52,6 +52,8 @@ import {
|
||||
createSecret as otpCreateSecret,
|
||||
verify as verifyOtp,
|
||||
} from '../../services/auth/OTPUtil.js';
|
||||
import type { UserRow } from '../../stores/user/UserStore.js';
|
||||
import { isOwnedEmailConflict } from '../../stores/user/UserStore.js';
|
||||
import { sessionCookieFlags } from '../../util/cookieFlags.js';
|
||||
import { cleanEmail, isBlockedEmail } from '../../util/email.js';
|
||||
import { generate_identifier } from '../../util/identifier.js';
|
||||
@@ -116,7 +118,7 @@ const TWO_FACTOR_LIMIT = {
|
||||
key: 'user',
|
||||
} as const;
|
||||
|
||||
/** Permission and membership writes. Never called in a loop by a client. */
|
||||
/** Permission writes. Never called in a loop by a client. */
|
||||
const GRANT_LIMIT = {
|
||||
scope: 'auth-grant',
|
||||
limit: 60,
|
||||
@@ -156,7 +158,7 @@ const ANTI_CSRF_MINT_LIMIT = {
|
||||
key: 'user',
|
||||
} as const;
|
||||
|
||||
/** Settings-page reads — enumerating sessions, permissions, groups. */
|
||||
/** Settings-page reads — enumerating sessions and permissions. */
|
||||
const AUTH_LIST_LIMIT = {
|
||||
scope: 'auth-list',
|
||||
limit: 120,
|
||||
@@ -177,6 +179,21 @@ const CARD_FALLBACK_OPEN_TTL_SECONDS = 24 * 60 * 60;
|
||||
// How long a failed-SMS-send record stays readable by its error_id — long
|
||||
// enough to cover the typical support round-trip.
|
||||
const SMS_SEND_ERROR_TTL_SECONDS = 7 * 24 * 60 * 60;
|
||||
|
||||
/**
|
||||
* Whether this account has already been through the card flow. Both halves
|
||||
* matter: the pending flag being clear only says nobody asked, while the
|
||||
* fingerprint is the artifact a completed check leaves behind. A route that
|
||||
* requires a verified card (`requireCardVerified`) sends users here with the
|
||||
* flag clear and no card on file, and answering "already verified" on the flag
|
||||
* alone would bounce them between a dialog that reports success and a route
|
||||
* that keeps refusing.
|
||||
*/
|
||||
const cardAlreadyVerified = (user: {
|
||||
card_fingerprint?: string | null;
|
||||
requires_card_verification?: boolean;
|
||||
}): boolean =>
|
||||
Boolean(user.card_fingerprint) && !user.requires_card_verification;
|
||||
const RESERVED_USERNAMES = new Set([
|
||||
'admin',
|
||||
'administrator',
|
||||
@@ -775,11 +792,9 @@ export class AuthController extends PuterController {
|
||||
if (this.config.disable_user_signup) {
|
||||
let claimable = false;
|
||||
if (!is_temp) {
|
||||
const existing =
|
||||
(await this.stores.user.getByEmail(body.email)) ??
|
||||
(await this.stores.user.getByCleanEmail(
|
||||
cleanEmail(body.email),
|
||||
));
|
||||
const existing = await this.stores.user.findEmailOwner(
|
||||
body.email,
|
||||
);
|
||||
claimable = Boolean(
|
||||
existing &&
|
||||
!existing.email_confirmed &&
|
||||
@@ -817,28 +832,18 @@ export class AuthController extends PuterController {
|
||||
// password to an OIDC account, the owner logs in via OIDC and
|
||||
// uses the authenticated change-password flow.
|
||||
//
|
||||
// Match on both raw `email` and canonical `clean_email` so
|
||||
// Matching runs against both raw `email` and canonical `clean_email` so
|
||||
// gmail-style aliases (`[email protected]` vs
|
||||
// `[email protected]`) collapse to the same account.
|
||||
let pseudo_user = null;
|
||||
if (!is_temp) {
|
||||
const canonical = cleanEmail(body.email);
|
||||
const existing =
|
||||
(await this.stores.user.getByEmail(body.email)) ??
|
||||
(await this.stores.user.getByCleanEmail(canonical));
|
||||
if (existing) {
|
||||
// Confirmed account (regardless of credential type) → reject.
|
||||
if (existing.email_confirmed || existing.password !== null) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'This email already exists in our database. Please use another one.',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
// Password-null AND unconfirmed → treat as pseudo.
|
||||
pseudo_user = existing;
|
||||
}
|
||||
}
|
||||
//
|
||||
// This is the cheap early check: it keeps an obvious duplicate from
|
||||
// paying for the validate hook and a bcrypt round. It is NOT the
|
||||
// guarantee — everything between here and the insert widens the window,
|
||||
// so the check runs again against the primary immediately before the
|
||||
// write, and the unique index catches whatever still slips through.
|
||||
let pseudo_user = is_temp
|
||||
? null
|
||||
: await this.#resolveSignupEmailClaim(body.email);
|
||||
|
||||
// Extension-level validation gate. Abuse-prevention extensions
|
||||
// inspect the incoming signup and can:
|
||||
@@ -857,6 +862,15 @@ export class AuthController extends PuterController {
|
||||
req.socket?.remoteAddress ||
|
||||
null) as string | null,
|
||||
email: body.email,
|
||||
// The same canonical form `email.validate` was given, so a check
|
||||
// in the abuse harness can look up the verdict that hook cached
|
||||
// for this address. Without it an alias (`[email protected]`,
|
||||
// `[email protected]`) reaches the two hooks under two different keys.
|
||||
clean_email: cleanEmail(body.email),
|
||||
// Temp signups carry a synthetic `<username>@gmail.com` and skip
|
||||
// #validateEmail entirely, so an email check must know not to
|
||||
// reason about the address at all.
|
||||
is_temp,
|
||||
allow: true,
|
||||
no_temp_user: false,
|
||||
requires_email_confirmation: false,
|
||||
@@ -945,24 +959,54 @@ export class AuthController extends PuterController {
|
||||
.slice(0, 19)
|
||||
.replace('T', ' ');
|
||||
|
||||
// Re-run the claim against the primary now that the slow work is done.
|
||||
// The check above ran before the validate hook (network round-trips to
|
||||
// the abuse listeners) and before bcrypt — hundreds of milliseconds in
|
||||
// which a concurrent signup can take the address, or claim the very
|
||||
// placeholder row we were about to convert.
|
||||
if (!is_temp) {
|
||||
pseudo_user = await this.#resolveSignupEmailClaim(body.email, {
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
|
||||
let user;
|
||||
if (pseudo_user) {
|
||||
// -- Pseudo-user claim (convert the placeholder row) --
|
||||
await this.stores.user.update(pseudo_user.id, {
|
||||
username: body.username,
|
||||
password: password_hash,
|
||||
uuid: user_uuid,
|
||||
email_confirm_code,
|
||||
email_confirm_token,
|
||||
email_confirmed: 0,
|
||||
requires_email_confirmation: 1,
|
||||
last_activity_ts: signupSqlTs,
|
||||
...(validateEvent.reputation != null
|
||||
? { reputation: validateEvent.reputation }
|
||||
: {}),
|
||||
requires_phone_verification: force_phone_verification ? 1 : 0,
|
||||
requires_card_verification: force_card_verification ? 1 : 0,
|
||||
});
|
||||
//
|
||||
// Guarded, not a plain update: the address never changes hands here
|
||||
// (the row already holds it), so the unique index has nothing to
|
||||
// catch. Two signups that both read this row as claimable would
|
||||
// otherwise both "succeed", the second overwriting the first's
|
||||
// username and password on a row the first was already given a
|
||||
// session for.
|
||||
const claimed = await this.stores.user.claimPlaceholder(
|
||||
pseudo_user.id,
|
||||
{
|
||||
username: body.username,
|
||||
password: password_hash,
|
||||
uuid: user_uuid,
|
||||
email_confirm_code,
|
||||
email_confirm_token,
|
||||
email_confirmed: 0,
|
||||
requires_email_confirmation: 1,
|
||||
last_activity_ts: signupSqlTs,
|
||||
...(validateEvent.reputation != null
|
||||
? { reputation: validateEvent.reputation }
|
||||
: {}),
|
||||
requires_phone_verification: force_phone_verification
|
||||
? 1
|
||||
: 0,
|
||||
requires_card_verification: force_card_verification ? 1 : 0,
|
||||
},
|
||||
);
|
||||
if (!claimed) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'This email already exists in our database. Please use another one.',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
|
||||
// Move from temp group to regular user group
|
||||
if (this.config.default_temp_group) {
|
||||
@@ -994,37 +1038,51 @@ export class AuthController extends PuterController {
|
||||
const clientIp = req.ip || req.socket?.remoteAddress || null;
|
||||
const proxyIpChain = req.headers['x-forwarded-for'];
|
||||
|
||||
user = await this.stores.user.create({
|
||||
username: body.username,
|
||||
uuid: user_uuid,
|
||||
password: password_hash,
|
||||
email: is_temp ? null : body.email,
|
||||
clean_email: is_temp ? null : cleanEmail(body.email),
|
||||
free_storage: this.config.storage_capacity ?? null,
|
||||
requires_email_confirmation:
|
||||
!is_temp || force_email_confirmation,
|
||||
email_confirm_code,
|
||||
email_confirm_token,
|
||||
audit_metadata: {
|
||||
ip: clientIp,
|
||||
ip_fwd: proxyIpChain,
|
||||
user_agent: req.headers?.['user-agent'],
|
||||
origin: req.headers?.origin,
|
||||
fingerprint,
|
||||
},
|
||||
signup_ip: clientIp,
|
||||
signup_ip_forwarded: proxyIpChain,
|
||||
signup_user_agent: req.headers?.['user-agent'] ?? null,
|
||||
signup_origin: (req.headers?.origin as string | null) ?? null,
|
||||
signup_server: (this.config as { serverId?: string }).serverId,
|
||||
referrer: req.body.referrer ?? null,
|
||||
last_activity_ts: signupSqlTs,
|
||||
reputation: validateEvent.reputation,
|
||||
// Phone collected later in the verification dialog (null now).
|
||||
phone: null,
|
||||
requires_phone_verification: force_phone_verification,
|
||||
requires_card_verification: force_card_verification,
|
||||
} as never);
|
||||
try {
|
||||
user = await this.stores.user.create({
|
||||
username: body.username,
|
||||
uuid: user_uuid,
|
||||
password: password_hash,
|
||||
email: is_temp ? null : body.email,
|
||||
clean_email: is_temp ? null : cleanEmail(body.email),
|
||||
free_storage: this.config.storage_capacity ?? null,
|
||||
requires_email_confirmation:
|
||||
!is_temp || force_email_confirmation,
|
||||
email_confirm_code,
|
||||
email_confirm_token,
|
||||
audit_metadata: {
|
||||
ip: clientIp,
|
||||
ip_fwd: proxyIpChain,
|
||||
user_agent: req.headers?.['user-agent'],
|
||||
origin: req.headers?.origin,
|
||||
fingerprint,
|
||||
},
|
||||
signup_ip: clientIp,
|
||||
signup_ip_forwarded: proxyIpChain,
|
||||
signup_user_agent: req.headers?.['user-agent'] ?? null,
|
||||
signup_origin:
|
||||
(req.headers?.origin as string | null) ?? null,
|
||||
signup_server: (this.config as { serverId?: string })
|
||||
.serverId,
|
||||
referrer: req.body.referrer ?? null,
|
||||
last_activity_ts: signupSqlTs,
|
||||
reputation: validateEvent.reputation,
|
||||
// Phone collected later in the verification dialog (null now).
|
||||
phone: null,
|
||||
requires_phone_verification: force_phone_verification,
|
||||
requires_card_verification: force_card_verification,
|
||||
} as never);
|
||||
} catch (e) {
|
||||
// Lost the race to another signup between the re-check above and
|
||||
// this insert. The index is the only thing that can see that, so
|
||||
// translate it into the answer the pre-check would have given.
|
||||
if (!isOwnedEmailConflict(e)) throw e;
|
||||
throw new HttpError(
|
||||
400,
|
||||
'This email already exists in our database. Please use another one.',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
|
||||
// Add to default group
|
||||
const defaultGroup = is_temp
|
||||
@@ -1101,8 +1159,7 @@ export class AuthController extends PuterController {
|
||||
is_temp: user!.password === null && user!.email === null,
|
||||
ip:
|
||||
(req?.headers?.['x-forwarded-for'] as
|
||||
| string
|
||||
| undefined) ||
|
||||
string | undefined) ||
|
||||
(
|
||||
req as unknown as {
|
||||
connection?: { remoteAddress?: string };
|
||||
@@ -1275,6 +1332,34 @@ export class AuthController extends PuterController {
|
||||
// after signup but before confirmation.
|
||||
await this.#validateEmail(user.email!);
|
||||
|
||||
// An account that already confirmed this address proved access to the
|
||||
// inbox, and revoking it below would hand the address to whoever
|
||||
// confirmed second. Refuse instead — a duplicate this old is data to
|
||||
// repair, not a race to resolve.
|
||||
const canonical = cleanEmail(user.email!);
|
||||
const confirmedRival = await this.stores.user.findConfirmedOtherByEmail(
|
||||
user.id,
|
||||
user.email!,
|
||||
canonical,
|
||||
);
|
||||
if (confirmedRival) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'This email was confirmed on a different account.',
|
||||
{ legacyCode: 'email_already_in_use' as never },
|
||||
);
|
||||
}
|
||||
|
||||
// Revoke the address from every remaining (unconfirmed) account holding
|
||||
// it, THEN confirm this one. Only one row may own an address, so
|
||||
// confirming first would momentarily create a second owner — which the
|
||||
// unique index rejects, turning a legitimate confirmation into a 500.
|
||||
await this.stores.user.unconfirmOthersByEmail(
|
||||
user.id,
|
||||
user.email!,
|
||||
canonical,
|
||||
);
|
||||
|
||||
await this.stores.user.update(user.id, {
|
||||
email_confirmed: 1,
|
||||
requires_email_confirmation: 0,
|
||||
@@ -1282,16 +1367,6 @@ export class AuthController extends PuterController {
|
||||
email_confirm_token: null,
|
||||
});
|
||||
|
||||
// Revoke confirmation from any other accounts sharing this
|
||||
// email so only the account whose owner just proved inbox
|
||||
// access retains verified status.
|
||||
const canonical = cleanEmail(user.email!);
|
||||
await this.stores.user.unconfirmOthersByEmail(
|
||||
user.id,
|
||||
user.email!,
|
||||
canonical,
|
||||
);
|
||||
|
||||
await promoteToVerifiedGroup(this.stores.group, this.config, user);
|
||||
|
||||
try {
|
||||
@@ -1864,7 +1939,7 @@ export class AuthController extends PuterController {
|
||||
// Phone normally comes first, but the fallback lets a phone-gated user
|
||||
// in once they've exhausted SMS attempts.
|
||||
const fallbackEligible = await this.isCardFallbackEligible(user);
|
||||
if (!user.requires_card_verification && !fallbackEligible) {
|
||||
if (cardAlreadyVerified(user) && !fallbackEligible) {
|
||||
res.json({ card_verified: true });
|
||||
return;
|
||||
}
|
||||
@@ -1984,7 +2059,7 @@ export class AuthController extends PuterController {
|
||||
});
|
||||
// Same fallback exception as setup: card may come before phone.
|
||||
const fallbackEligible = await this.isCardFallbackEligible(user);
|
||||
if (!user.requires_card_verification && !fallbackEligible) {
|
||||
if (cardAlreadyVerified(user) && !fallbackEligible) {
|
||||
res.json({ card_verified: true });
|
||||
return;
|
||||
}
|
||||
@@ -2278,10 +2353,26 @@ export class AuthController extends PuterController {
|
||||
|
||||
// Atomic check: only update if the recovery token still matches
|
||||
const password_hash = await bcrypt.hash(password, 8);
|
||||
const result = await this.clients.db.write(
|
||||
'UPDATE `user` SET `password` = ?, `pass_recovery_token` = NULL, `change_email_confirm_token` = NULL WHERE `id` = ? AND `pass_recovery_token` = ?',
|
||||
[password_hash, user.id, decoded.token],
|
||||
);
|
||||
let result;
|
||||
try {
|
||||
result = await this.clients.db.write(
|
||||
'UPDATE `user` SET `password` = ?, `pass_recovery_token` = NULL, `change_email_confirm_token` = NULL WHERE `id` = ? AND `pass_recovery_token` = ?',
|
||||
[password_hash, user.id, decoded.token],
|
||||
);
|
||||
} catch (e) {
|
||||
if (!isOwnedEmailConflict(e)) throw e;
|
||||
// Recovery can be requested by username, so this row may be an
|
||||
// unconfirmed placeholder that shares its address with a real
|
||||
// account. Giving it a password would make it a second account able
|
||||
// to drive recovery for that inbox, which is the thing the address
|
||||
// constraint exists to stop. The inbox owner has an account
|
||||
// already — they should be recovering that one.
|
||||
throw new HttpError(
|
||||
400,
|
||||
'This email is already in use. Recover the account that uses it instead.',
|
||||
{ legacyCode: 'email_already_in_use' as never },
|
||||
);
|
||||
}
|
||||
const affected =
|
||||
(result as { affectedRows?: number; changes?: number })
|
||||
?.affectedRows ??
|
||||
@@ -2442,10 +2533,7 @@ export class AuthController extends PuterController {
|
||||
// aliases — which is also why the caller has to be excluded: an
|
||||
// alias of your own current address resolves back to you, and
|
||||
// "already in use" about yourself is nonsense.
|
||||
const canonical = cleanEmail(new_email);
|
||||
const existing =
|
||||
(await this.stores.user.getByEmail(new_email)) ??
|
||||
(await this.stores.user.getByCleanEmail(canonical));
|
||||
const existing = await this.stores.user.findEmailOwner(new_email);
|
||||
if (
|
||||
existing &&
|
||||
existing.id !== req.actor!.user.id &&
|
||||
@@ -2546,7 +2634,7 @@ export class AuthController extends PuterController {
|
||||
}
|
||||
|
||||
const rows = (await this.clients.db.read(
|
||||
'SELECT * FROM `user` WHERE `change_email_confirm_token` = ? LIMIT 1',
|
||||
'SELECT * FROM `user` WHERE `change_email_confirm_token` = ? ORDER BY `id` ASC LIMIT 1',
|
||||
[decoded.token],
|
||||
)) as Array<Record<string, unknown>>;
|
||||
const user = rows[0] as
|
||||
@@ -2567,11 +2655,12 @@ export class AuthController extends PuterController {
|
||||
|
||||
// Re-check nobody claimed the new email meanwhile. Match raw +
|
||||
// canonical; block if any real account (confirmed OR
|
||||
// password-holding) already owns it.
|
||||
// password-holding) already owns it. Read the primary — the request
|
||||
// that took the address may have landed moments ago.
|
||||
const canonical = cleanEmail(newEmail);
|
||||
const owner =
|
||||
(await this.stores.user.getByEmail(newEmail)) ??
|
||||
(await this.stores.user.getByCleanEmail(canonical));
|
||||
const owner = await this.stores.user.findEmailOwner(newEmail, {
|
||||
force: true,
|
||||
});
|
||||
if (
|
||||
owner &&
|
||||
owner.id !== user.id &&
|
||||
@@ -2582,15 +2671,30 @@ export class AuthController extends PuterController {
|
||||
});
|
||||
}
|
||||
|
||||
await this.stores.user.update(user.id, {
|
||||
email: newEmail,
|
||||
clean_email: cleanEmail(newEmail),
|
||||
unconfirmed_change_email: null,
|
||||
change_email_confirm_token: null,
|
||||
pass_recovery_token: null,
|
||||
email_confirmed: 1,
|
||||
requires_email_confirmation: 0,
|
||||
});
|
||||
// Strip the address off any unconfirmed placeholder still holding it
|
||||
// before taking it, so this row is the only owner.
|
||||
await this.stores.user.unconfirmOthersByEmail(
|
||||
user.id,
|
||||
newEmail,
|
||||
canonical,
|
||||
);
|
||||
|
||||
try {
|
||||
await this.stores.user.update(user.id, {
|
||||
email: newEmail,
|
||||
clean_email: canonical,
|
||||
unconfirmed_change_email: null,
|
||||
change_email_confirm_token: null,
|
||||
pass_recovery_token: null,
|
||||
email_confirmed: 1,
|
||||
requires_email_confirmation: 0,
|
||||
});
|
||||
} catch (e) {
|
||||
if (!isOwnedEmailConflict(e)) throw e;
|
||||
throw new HttpError(400, 'This email is already in use.', {
|
||||
legacyCode: 'email_already_in_use' as never,
|
||||
});
|
||||
}
|
||||
|
||||
await this.stores.oidc.unlinkAllByUserId(user.id);
|
||||
|
||||
@@ -2693,9 +2797,7 @@ export class AuthController extends PuterController {
|
||||
// reject on ANY confirmed account (OIDC accounts have
|
||||
// password=null but are real) — not just password-holders.
|
||||
const canonical = cleanEmail(email);
|
||||
const existingEmail =
|
||||
(await this.stores.user.getByEmail(email)) ??
|
||||
(await this.stores.user.getByCleanEmail(canonical));
|
||||
const existingEmail = await this.stores.user.findEmailOwner(email);
|
||||
if (
|
||||
existingEmail &&
|
||||
existingEmail.id !== user.id &&
|
||||
@@ -2711,16 +2813,38 @@ export class AuthController extends PuterController {
|
||||
const email_confirm_code = String(crypto.randomInt(100000, 1000000));
|
||||
const email_confirm_token = uuidv4();
|
||||
|
||||
await this.stores.user.update(user.id, {
|
||||
username,
|
||||
email,
|
||||
clean_email: cleanEmail(email),
|
||||
password: password_hash,
|
||||
email_confirm_code,
|
||||
email_confirm_token,
|
||||
email_confirmed: 0,
|
||||
requires_email_confirmation: 1,
|
||||
// bcrypt above is slow enough for someone else to take the address in
|
||||
// the meantime, so re-check against the primary before the write.
|
||||
const raced = await this.stores.user.findEmailOwner(email, {
|
||||
force: true,
|
||||
});
|
||||
if (
|
||||
raced &&
|
||||
raced.id !== user.id &&
|
||||
(raced.email_confirmed || raced.password !== null)
|
||||
) {
|
||||
throw new HttpError(400, 'This email is already in use.', {
|
||||
legacyCode: 'email_already_in_use' as never,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await this.stores.user.update(user.id, {
|
||||
username,
|
||||
email,
|
||||
clean_email: canonical,
|
||||
password: password_hash,
|
||||
email_confirm_code,
|
||||
email_confirm_token,
|
||||
email_confirmed: 0,
|
||||
requires_email_confirmation: 1,
|
||||
});
|
||||
} catch (e) {
|
||||
if (!isOwnedEmailConflict(e)) throw e;
|
||||
throw new HttpError(400, 'This email is already in use.', {
|
||||
legacyCode: 'email_already_in_use' as never,
|
||||
});
|
||||
}
|
||||
|
||||
// Rename the user's FS home so `/<temp>/Desktop` etc.
|
||||
// become `/<new>/Desktop`. Without this cascade, any
|
||||
@@ -2850,30 +2974,6 @@ export class AuthController extends PuterController {
|
||||
|
||||
// -- Permission grants -------------------------------------------
|
||||
|
||||
@Post('/auth/grant-user-user', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
rateLimit: GRANT_LIMIT,
|
||||
})
|
||||
async handleGrantUserUser(req: Request, res: Response): Promise<void> {
|
||||
const { target_username, permission, extra, meta } = req.body;
|
||||
if (!target_username || !permission) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'Missing `target_username` or `permission`',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
await this.services.permission.grantUserUserPermission(
|
||||
req.actor!,
|
||||
target_username,
|
||||
permission,
|
||||
extra,
|
||||
meta,
|
||||
);
|
||||
res.json({});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared input validation for the user-app grant/revoke handlers, which
|
||||
* accept a caller-supplied `origin` as an alternative to `app_uid`. All
|
||||
@@ -3094,35 +3194,13 @@ export class AuthController extends PuterController {
|
||||
res.json({});
|
||||
}
|
||||
|
||||
@Post('/auth/grant-user-group', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
rateLimit: GRANT_LIMIT,
|
||||
})
|
||||
async handleGrantUserGroup(req: Request, res: Response): Promise<void> {
|
||||
const { group_uid, permission, extra, meta } = req.body;
|
||||
if (!group_uid || !permission) {
|
||||
throw new HttpError(400, 'Missing `group_uid` or `permission`', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
}
|
||||
const group = await this.stores.group.getByUid(group_uid);
|
||||
if (!group)
|
||||
throw new HttpError(404, 'Group not found', {
|
||||
legacyCode: 'not_found',
|
||||
});
|
||||
await this.services.permission.grantUserGroupPermission(
|
||||
req.actor!,
|
||||
group,
|
||||
permission,
|
||||
extra,
|
||||
meta,
|
||||
);
|
||||
res.json({});
|
||||
}
|
||||
|
||||
// -- Permission revokes ------------------------------------------
|
||||
|
||||
/**
|
||||
* @deprecated Use `puter.fs.unshare()`, which withdraws the share row and
|
||||
* the grant together. Kept for direct HTTP callers: the grant side is
|
||||
* retired, but access it left behind has to stay withdrawable.
|
||||
*/
|
||||
@Post('/auth/revoke-user-user', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
@@ -3190,27 +3268,6 @@ export class AuthController extends PuterController {
|
||||
res.json({});
|
||||
}
|
||||
|
||||
@Post('/auth/revoke-user-group', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
rateLimit: GRANT_LIMIT,
|
||||
})
|
||||
async handleRevokeUserGroup(req: Request, res: Response): Promise<void> {
|
||||
const { group_uid, permission, meta } = req.body;
|
||||
if (!group_uid || !permission) {
|
||||
throw new HttpError(400, 'Missing `group_uid` or `permission`', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
}
|
||||
await this.services.permission.revokeUserGroupPermission(
|
||||
req.actor!,
|
||||
{ uid: group_uid } as never,
|
||||
permission,
|
||||
meta,
|
||||
);
|
||||
res.json({});
|
||||
}
|
||||
|
||||
// -- Permission checks -------------------------------------------
|
||||
|
||||
@Post('/auth/check-permissions', {
|
||||
@@ -3885,147 +3942,6 @@ export class AuthController extends PuterController {
|
||||
});
|
||||
}
|
||||
|
||||
// -- Group management --------------------------------------------
|
||||
|
||||
@Post('/group/create', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
// Creates a persistent row per call with no quota behind it, so it
|
||||
// sits on the hour-scale budget rather than the grant one.
|
||||
rateLimit: { ...CREDENTIAL_MINT_LIMIT, scope: 'group-create' },
|
||||
})
|
||||
async handleGroupCreate(req: Request, res: Response): Promise<void> {
|
||||
const extra = req.body.extra ?? {};
|
||||
const metadata = req.body.metadata ?? {};
|
||||
if (typeof extra !== 'object' || Array.isArray(extra))
|
||||
throw new HttpError(400, '`extra` must be an object', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
if (typeof metadata !== 'object' || Array.isArray(metadata))
|
||||
throw new HttpError(400, '`metadata` must be an object', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
|
||||
const uid = await this.stores.group.create({
|
||||
ownerUserId: req.actor!.user.id,
|
||||
extra: {},
|
||||
metadata,
|
||||
} as never);
|
||||
res.json({ uid });
|
||||
}
|
||||
|
||||
@Post('/group/add-users', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
rateLimit: GRANT_LIMIT,
|
||||
})
|
||||
async handleGroupAddUsers(req: Request, res: Response): Promise<void> {
|
||||
const { uid, users } = req.body ?? {};
|
||||
if (!uid)
|
||||
throw new HttpError(400, 'Missing `uid`', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
if (!Array.isArray(users))
|
||||
throw new HttpError(400, '`users` must be an array', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
|
||||
const group = await this.stores.group.getByUid(uid);
|
||||
if (!group)
|
||||
throw new HttpError(404, 'Group not found', {
|
||||
legacyCode: 'not_found',
|
||||
});
|
||||
if (
|
||||
(group as { owner_user_id?: number }).owner_user_id !==
|
||||
req.actor!.user.id
|
||||
)
|
||||
throw new HttpError(403, 'Forbidden', {
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
|
||||
await this.stores.group.addUsers(uid, users);
|
||||
// New members inherit the group's permissions immediately, not
|
||||
// after the permission-cache TTL.
|
||||
await this.services.permission.bumpPermissionCacheForUsernames(users);
|
||||
res.json({});
|
||||
}
|
||||
|
||||
@Post('/group/remove-users', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
rateLimit: GRANT_LIMIT,
|
||||
})
|
||||
async handleGroupRemoveUsers(req: Request, res: Response): Promise<void> {
|
||||
const { uid, users } = req.body ?? {};
|
||||
if (!uid)
|
||||
throw new HttpError(400, 'Missing `uid`', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
if (!Array.isArray(users))
|
||||
throw new HttpError(400, '`users` must be an array', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
|
||||
const group = await this.stores.group.getByUid(uid);
|
||||
if (!group)
|
||||
throw new HttpError(404, 'Group not found', {
|
||||
legacyCode: 'not_found',
|
||||
});
|
||||
if (
|
||||
(group as { owner_user_id?: number }).owner_user_id !==
|
||||
req.actor!.user.id
|
||||
)
|
||||
throw new HttpError(403, 'Forbidden', {
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
|
||||
await this.stores.group.removeUsers(uid, users);
|
||||
// Removed members must lose the group's permissions immediately,
|
||||
// not after the permission-cache TTL.
|
||||
await this.services.permission.bumpPermissionCacheForUsernames(users);
|
||||
res.json({});
|
||||
}
|
||||
|
||||
@Get('/group/list', {
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
rateLimit: AUTH_LIST_LIMIT,
|
||||
})
|
||||
async handleGroupList(req: Request, res: Response): Promise<void> {
|
||||
const userId = req.actor!.user.id!;
|
||||
const [owned, member] = await Promise.all([
|
||||
this.stores.group.listGroupsWithOwner(userId),
|
||||
this.stores.group.listGroupsWithMember(userId),
|
||||
]);
|
||||
res.json({
|
||||
owned_groups: owned,
|
||||
in_groups: member,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('/group/public-groups', {
|
||||
subdomain: 'api',
|
||||
// The only unauthenticated route in the group set, so IP is the
|
||||
// only key available — and that makes the bucket an aggregate:
|
||||
// one office, campus or carrier gateway is a single key for
|
||||
// everybody behind it, and each of them reads this once while
|
||||
// bootstrapping. Sized for that population of real people rather
|
||||
// than one browser, and no wider: this sits next to the sign-in
|
||||
// surface, so it stays a real bound on enumeration.
|
||||
rateLimit: {
|
||||
scope: 'public-groups',
|
||||
limit: 1_200,
|
||||
window: 60_000,
|
||||
key: 'ip',
|
||||
},
|
||||
})
|
||||
async handleGroupPublicGroups(_req: Request, res: Response): Promise<void> {
|
||||
res.json({
|
||||
user: this.config.default_user_group ?? null,
|
||||
temp: this.config.default_temp_group ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
// -- Session helpers ---------------------------------------------
|
||||
|
||||
@Get('/get-gui-token', {
|
||||
@@ -4426,57 +4342,7 @@ export class AuthController extends PuterController {
|
||||
// -- Private helpers ----------------------------------------------
|
||||
|
||||
async #cascadeDeleteUser(userId: number): Promise<void> {
|
||||
// Capture the identifiers downstream teardown needs before the row is
|
||||
// gone — the marketplace extension cancels the user's Stripe
|
||||
// subscriptions off `user.delete`, keyed by uuid / customer id.
|
||||
let userUuid: string | undefined;
|
||||
let stripeCustomerId: string | null = null;
|
||||
try {
|
||||
const rows = (await this.clients.db.read(
|
||||
'SELECT `uuid`, `stripe_customer_id` FROM `user` WHERE `id` = ?',
|
||||
[userId],
|
||||
)) as Array<{ uuid?: string; stripe_customer_id?: string | null }>;
|
||||
userUuid = rows[0]?.uuid;
|
||||
stripeCustomerId = rows[0]?.stripe_customer_id ?? null;
|
||||
} catch (e) {
|
||||
console.warn('[cascade-delete-user] identifier lookup failed:', e);
|
||||
}
|
||||
|
||||
try {
|
||||
await this.services.fs.removeAllForUser(userId);
|
||||
} catch (e) {
|
||||
// Proceed with user-row delete anyway — orphaned fsentries are
|
||||
// better than a resurrected account.
|
||||
console.warn('[cascade-delete-user] fs cleanup failed:', e);
|
||||
}
|
||||
|
||||
// Sessions FK is SET NULL, so delete explicitly to avoid dangling rows.
|
||||
await this.clients.db.write(
|
||||
'DELETE FROM `sessions` WHERE `user_id` = ?',
|
||||
[userId],
|
||||
);
|
||||
await this.clients.db.write('DELETE FROM `user` WHERE `id` = ?', [
|
||||
userId,
|
||||
]);
|
||||
await this.stores.user.invalidateById(userId);
|
||||
|
||||
// Fire-and-forget: let listeners purge external state tied to the
|
||||
// account (Stripe subscriptions are cancelled immediately, without
|
||||
// proration). Emitted after the row delete — listeners key off the
|
||||
// payload, not the DB row.
|
||||
try {
|
||||
this.clients.event?.emit(
|
||||
'user.delete',
|
||||
{
|
||||
user_id: userId,
|
||||
user_uuid: userUuid,
|
||||
stripe_customer_id: stripeCustomerId,
|
||||
},
|
||||
{},
|
||||
);
|
||||
} catch {
|
||||
// ignore — event emission shouldn't block deletion
|
||||
}
|
||||
await this.services.userAccount.cascadeDelete(userId);
|
||||
}
|
||||
|
||||
async #generateRandomUsername(): Promise<string> {
|
||||
@@ -4495,6 +4361,34 @@ export class AuthController extends PuterController {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether a signup may take `email`, and hand back the placeholder
|
||||
* row it should convert instead of inserting a new one.
|
||||
*
|
||||
* Throws when a live account already owns the address. Returns the
|
||||
* unconfirmed, password-less pseudo row when one exists (admin
|
||||
* pre-provisioning — signup claims it), or null when the address is free.
|
||||
*
|
||||
* Called twice per signup: once early, to fail fast before the validate
|
||||
* hook and bcrypt, and once against the primary immediately before the
|
||||
* write.
|
||||
*/
|
||||
async #resolveSignupEmailClaim(
|
||||
email: string,
|
||||
opts: { force?: boolean } = {},
|
||||
): Promise<UserRow | null> {
|
||||
const existing = await this.stores.user.findEmailOwner(email, opts);
|
||||
if (!existing) return null;
|
||||
if (existing.email_confirmed || existing.password !== null) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'This email already exists in our database. Please use another one.',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Config-blocklist + extension-driven email validation. Config blocklist
|
||||
* (suffix match on cleaned email) blocks first; then the `email.validate`
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { runWithContext } from '../../core/context.js';
|
||||
import { isHttpError } from '../../core/http/HttpError.js';
|
||||
import { configureRateLimit } from '../../core/http/middleware/rateLimit.js';
|
||||
import { DriverController } from './DriverController.js';
|
||||
|
||||
// The subscription requirement a driver declares per method, exercised
|
||||
// through `#handleCall` the same way the concurrent test does: a synthetic
|
||||
// driver carrying only the field under test, plus a stub metering service
|
||||
// that answers with a fixed plan.
|
||||
|
||||
const captureCallHandler = (controller: DriverController): RequestHandler => {
|
||||
let handler: RequestHandler | undefined;
|
||||
const fakeRouter = {
|
||||
post: (path: string, _opts: unknown, h: RequestHandler) => {
|
||||
if (path === '/call') handler = h;
|
||||
return fakeRouter;
|
||||
},
|
||||
get: () => fakeRouter,
|
||||
use: () => fakeRouter,
|
||||
};
|
||||
controller.registerRoutes(
|
||||
fakeRouter as unknown as Parameters<
|
||||
typeof controller.registerRoutes
|
||||
>[0],
|
||||
);
|
||||
if (!handler) throw new Error('failed to capture POST /call handler');
|
||||
return handler;
|
||||
};
|
||||
|
||||
class StubRes extends EventEmitter {
|
||||
statusCode = 200;
|
||||
body: unknown = undefined;
|
||||
status(code: number) {
|
||||
this.statusCode = code;
|
||||
return this;
|
||||
}
|
||||
json(body: unknown) {
|
||||
this.body = body;
|
||||
return this;
|
||||
}
|
||||
setHeader() {
|
||||
return this;
|
||||
}
|
||||
type() {
|
||||
return this;
|
||||
}
|
||||
send() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
const makeReq = (method: string, tag: string): Request =>
|
||||
({
|
||||
body: { interface: 'test-iface', method },
|
||||
actor: { user: { uuid: `u-${tag}`, username: 'u' } },
|
||||
headers: { 'user-agent': tag },
|
||||
query: {},
|
||||
ip: '127.0.0.1',
|
||||
socket: { remoteAddress: '127.0.0.1' },
|
||||
}) as unknown as Request;
|
||||
|
||||
const syntheticDriver = {
|
||||
driverInterface: 'test-iface',
|
||||
driverName: 'test-driver',
|
||||
isDefault: true,
|
||||
requireSubscription: {
|
||||
methods: { paid: true, premium: ['business', 'pro'] },
|
||||
},
|
||||
onServerStart() {},
|
||||
onServerPrepareShutdown() {},
|
||||
onServerShutdown() {},
|
||||
free: async () => 'free-ok',
|
||||
paid: async () => 'paid-ok',
|
||||
premium: async () => 'premium-ok',
|
||||
};
|
||||
|
||||
const buildController = (plan: string | null) => {
|
||||
const clients = { alarm: { create: () => {} } };
|
||||
const services = plan
|
||||
? {
|
||||
metering: {
|
||||
getActorSubscription: vi.fn().mockResolvedValue({ id: plan }),
|
||||
},
|
||||
}
|
||||
: {};
|
||||
return new DriverController(
|
||||
{} as any,
|
||||
clients as any,
|
||||
{} as any,
|
||||
services as any,
|
||||
{ syntheticDriver } as any,
|
||||
);
|
||||
};
|
||||
|
||||
const call = (plan: string | null, method: string, tag: string) => {
|
||||
const handler = captureCallHandler(buildController(plan));
|
||||
const res = new StubRes();
|
||||
return runWithContext({}, () =>
|
||||
handler(makeReq(method, tag), res as unknown as Response, () => {}),
|
||||
).then(() => res);
|
||||
};
|
||||
|
||||
const expect402 = (promise: Promise<unknown>) =>
|
||||
expect(promise).rejects.toSatisfy(
|
||||
(e) =>
|
||||
isHttpError(e) &&
|
||||
(e as { statusCode: number }).statusCode === 402 &&
|
||||
(e as { legacyCode?: string }).legacyCode ===
|
||||
'subscription_required',
|
||||
);
|
||||
|
||||
describe('DriverController — per-method subscription requirement', () => {
|
||||
beforeEach(() => {
|
||||
configureRateLimit();
|
||||
});
|
||||
|
||||
it('leaves a method that declares nothing open to a free account', async () => {
|
||||
const res = await call('user_free', 'free', 'open');
|
||||
expect(res.body).toMatchObject({ success: true, result: 'free-ok' });
|
||||
});
|
||||
|
||||
it('rejects a free account on a method that requires a subscription', async () => {
|
||||
await expect402(call('user_free', 'paid', 'paid-free'));
|
||||
});
|
||||
|
||||
it('admits a subscriber on that same method', async () => {
|
||||
const res = await call('basic', 'paid', 'paid-sub');
|
||||
expect(res.body).toMatchObject({ success: true, result: 'paid-ok' });
|
||||
});
|
||||
|
||||
it('honours a per-method plan allowlist', async () => {
|
||||
await expect402(call('basic', 'premium', 'premium-basic'));
|
||||
const res = await call('pro', 'premium', 'premium-pro');
|
||||
expect(res.body).toMatchObject({ success: true, result: 'premium-ok' });
|
||||
});
|
||||
|
||||
it('enforces nothing on a deployment with no metering service', async () => {
|
||||
const res = await call(null, 'paid', 'no-metering');
|
||||
expect(res.body).toMatchObject({ success: true, result: 'paid-ok' });
|
||||
});
|
||||
});
|
||||
@@ -212,6 +212,30 @@ const makeRes = (): MockRes => {
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run the call route and return the rejection, or null when it resolves.
|
||||
* Lets a test assert on *which* gate rejected without depending on how far
|
||||
* an admitted call gets afterwards.
|
||||
*/
|
||||
const callForError = async (
|
||||
routes: Captured,
|
||||
req: Request,
|
||||
actor: Actor,
|
||||
): Promise<{ statusCode?: number; legacyCode?: string } | null> => {
|
||||
try {
|
||||
await runWithContext({ actor }, () =>
|
||||
routes['POST /call'](
|
||||
req,
|
||||
makeRes() as unknown as Response,
|
||||
() => {},
|
||||
),
|
||||
);
|
||||
return null;
|
||||
} catch (e) {
|
||||
return e as { statusCode?: number; legacyCode?: string };
|
||||
}
|
||||
};
|
||||
|
||||
const makeReq = (body: Record<string, unknown> = {}, actor?: Actor): Request =>
|
||||
({
|
||||
body,
|
||||
@@ -338,8 +362,7 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
it('admits a bare session ("root" token) actor on the AI drivers', async () => {
|
||||
// Privileged ("godmode") apps call AI with the user's own session
|
||||
// token, so the AI drivers no longer set `noUserSession`: the
|
||||
// session actor reaches the permission scan (403 forbidden — no
|
||||
// perms granted) instead of the credential-shape rejection.
|
||||
// session actor must get past the credential-shape gate.
|
||||
const actor = await makeUserActor();
|
||||
const req = makeReq(
|
||||
{
|
||||
@@ -349,18 +372,8 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
},
|
||||
actor,
|
||||
);
|
||||
await expect(
|
||||
runWithContext({ actor }, () =>
|
||||
routes['POST /call'](
|
||||
req,
|
||||
makeRes() as unknown as Response,
|
||||
() => {},
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
const err = await callForError(routes, req, actor);
|
||||
expect(err?.legacyCode).not.toBe('app_or_api_token_required');
|
||||
});
|
||||
|
||||
it('admits app and access-token actors on the AI drivers (they fail later on permission, not credential shape)', async () => {
|
||||
@@ -385,29 +398,15 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
},
|
||||
actor,
|
||||
);
|
||||
await expect(
|
||||
runWithContext({ actor }, () =>
|
||||
routes['POST /call'](
|
||||
req,
|
||||
makeRes() as unknown as Response,
|
||||
() => {},
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
// Fresh actors hold no service:* perms, so the call still
|
||||
// 403s — but at the permission scan, proving the
|
||||
// credential-shape gate let the delegated actor through.
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
const err = await callForError(routes, req, actor);
|
||||
expect(err?.legacyCode).not.toBe('app_or_api_token_required');
|
||||
}
|
||||
});
|
||||
|
||||
it('admits a user-scoped worker session on the AI drivers', async () => {
|
||||
// Workers deployed without an app binding authenticate as a user
|
||||
// actor whose session row is kind='worker' — they must keep their
|
||||
// AI access (they fail later on permission here, not on
|
||||
// credential shape).
|
||||
// AI access rather than be rejected for their credential shape.
|
||||
const base = await makeUserActor();
|
||||
const actor: Actor = {
|
||||
...base,
|
||||
@@ -421,24 +420,13 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
},
|
||||
actor,
|
||||
);
|
||||
await expect(
|
||||
runWithContext({ actor }, () =>
|
||||
routes['POST /call'](
|
||||
req,
|
||||
makeRes() as unknown as Response,
|
||||
() => {},
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
const err = await callForError(routes, req, actor);
|
||||
expect(err?.legacyCode).not.toBe('app_or_api_token_required');
|
||||
});
|
||||
|
||||
it('still allows bare session actors on drivers without the noUserSession flag', async () => {
|
||||
// puter-kvstore doesn't set the flag; the session actor reaches
|
||||
// the permission scan (403 forbidden — no perms granted) instead
|
||||
// of being rejected for its credential shape.
|
||||
// puter-kvstore doesn't set the flag, so the session actor must get
|
||||
// past the credential-shape gate.
|
||||
const actor = await makeUserActor();
|
||||
const req = makeReq(
|
||||
{
|
||||
@@ -448,24 +436,24 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
},
|
||||
actor,
|
||||
);
|
||||
await expect(
|
||||
runWithContext({ actor }, () =>
|
||||
routes['POST /call'](
|
||||
req,
|
||||
makeRes() as unknown as Response,
|
||||
() => {},
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
legacyCode: 'forbidden',
|
||||
});
|
||||
const err = await callForError(routes, req, actor);
|
||||
expect(err?.legacyCode).not.toBe('app_or_api_token_required');
|
||||
});
|
||||
|
||||
it('rejects with 403 when the actor lacks the service permission', async () => {
|
||||
// A fresh user has no service:* perms → permission.check returns
|
||||
// false → 403.
|
||||
const actor = await makeUserActor();
|
||||
// A scoped access token holds only the permissions written to its
|
||||
// own row, so it is the actor shape that can still be denied — the
|
||||
// `driver`/`service` grants every user inherits are resolved from
|
||||
// the issuer only for full-access tokens.
|
||||
const base = await makeUserActor();
|
||||
const actor: Actor = {
|
||||
...base,
|
||||
accessToken: {
|
||||
uid: `tok-${uuidv4()}`,
|
||||
issuer: base,
|
||||
fullAccess: false,
|
||||
},
|
||||
};
|
||||
const req = makeReq(
|
||||
{
|
||||
interface: 'puter-kvstore',
|
||||
@@ -474,15 +462,8 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
},
|
||||
actor,
|
||||
);
|
||||
await expect(
|
||||
runWithContext({ actor }, () =>
|
||||
routes['POST /call'](
|
||||
req,
|
||||
makeRes() as unknown as Response,
|
||||
() => {},
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 403 });
|
||||
const err = await callForError(routes, req, actor);
|
||||
expect(err).toMatchObject({ statusCode: 403 });
|
||||
});
|
||||
|
||||
it('returns the wrapped {success, result, service} envelope on a successful call', async () => {
|
||||
|
||||
@@ -36,7 +36,9 @@ import {
|
||||
resolveDriverMeta,
|
||||
resolveDriverMethodConcurrent,
|
||||
resolveDriverMethodRateLimit,
|
||||
resolveDriverMethodRequireSubscription,
|
||||
} from '../../drivers/meta.js';
|
||||
import { assertActorHasSubscription } from '../../services/metering/enforcement.js';
|
||||
import type { PermissionService } from '../../services/permission/PermissionService.js';
|
||||
import { PermissionUtil } from '../../services/permission/permissionUtil.js';
|
||||
import type { WithLifecycle } from '../../types';
|
||||
@@ -297,8 +299,7 @@ export class DriverController extends PuterController {
|
||||
|
||||
if (req.actor) {
|
||||
const permService = this.services.permission as unknown as
|
||||
| PermissionService
|
||||
| undefined;
|
||||
PermissionService | undefined;
|
||||
if (permService) {
|
||||
// Build via PermissionUtil.join so any `:` in a driver or
|
||||
// interface name is escaped — raw interpolation would let a
|
||||
@@ -326,6 +327,25 @@ export class DriverController extends PuterController {
|
||||
}
|
||||
}
|
||||
|
||||
// Subscriber-only methods. Declared per-driver
|
||||
// (`@Driver({ requireSubscription })`) because `/drivers/call` is a
|
||||
// single route and a route option would apply to every driver at once.
|
||||
// Checked before the rate limit — the same order the route chain uses
|
||||
// — so a caller whose plan never included the method is told that
|
||||
// rather than spending a bucket on it.
|
||||
const subscriptionRequirement = resolveDriverMethodRequireSubscription(
|
||||
driverMeta?.requireSubscription,
|
||||
method,
|
||||
);
|
||||
if (subscriptionRequirement !== undefined) {
|
||||
await assertActorHasSubscription(
|
||||
this.services.metering,
|
||||
req.actor,
|
||||
subscriptionRequirement,
|
||||
this.config,
|
||||
);
|
||||
}
|
||||
|
||||
// Per-method rate-limit and concurrent specs both live on the
|
||||
// driver's resolved meta (set by `@Driver({ rateLimit, concurrent })`
|
||||
// or imperative fields). Rate-limit is single-shot; concurrent
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
/*
|
||||
* 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 { Request, RequestHandler, Response } from 'express';
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from 'vitest';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { Actor } from '../../core/actor.js';
|
||||
import { PuterRouter } from '../../core/http/PuterRouter.js';
|
||||
import { PuterServer } from '../../server.js';
|
||||
import { AppFeedbackService } from '../../services/feedback/AppFeedbackService.js';
|
||||
import { setupTestServer } from '../../testUtil.js';
|
||||
|
||||
// Boots one real PuterServer (in-memory sqlite + mocked externals) and
|
||||
// registers AppFeedbackController's decorated routes onto a fresh
|
||||
// PuterRouter. Tests drive the captured handlers with stub req/res; the
|
||||
// stores/services underneath are the live wired ones, so rows land in the
|
||||
// real `app_feedback` table.
|
||||
|
||||
let server: PuterServer;
|
||||
let router: PuterRouter;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await setupTestServer();
|
||||
router = new PuterRouter();
|
||||
server.controllers.appFeedback.registerRoutes(router);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.shutdown();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
// Back to the self-hosted no-SMTP baseline the server booted with.
|
||||
delete liveConfig().email;
|
||||
});
|
||||
|
||||
const makeUser = async (): Promise<{ actor: Actor; userId: number }> => {
|
||||
const username = `fdbk-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const created = await server.stores.user.create({
|
||||
username,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email: `${username}@test.local`,
|
||||
free_storage: 100 * 1024 * 1024,
|
||||
requires_email_confirmation: false,
|
||||
});
|
||||
const refreshed = (await server.stores.user.getById(created.id))!;
|
||||
return {
|
||||
userId: refreshed.id,
|
||||
actor: {
|
||||
user: {
|
||||
id: refreshed.id,
|
||||
uuid: refreshed.uuid,
|
||||
username: refreshed.username,
|
||||
email: refreshed.email ?? null,
|
||||
email_confirmed: true,
|
||||
} as Actor['user'],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const makeApp = async (
|
||||
ownerUserId: number,
|
||||
opts: { feedbackEnabled?: boolean; indexUrl?: string; name?: string } = {},
|
||||
) => {
|
||||
const name =
|
||||
opts.name ?? `fdbk-app-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return await server.stores.app.create(
|
||||
{
|
||||
name,
|
||||
title: `Feedback Test ${name}`,
|
||||
index_url: opts.indexUrl ?? `https://${name}.example.com`,
|
||||
...(opts.feedbackEnabled ? { feedback_enabled: 1 } : {}),
|
||||
},
|
||||
{ ownerUserId },
|
||||
);
|
||||
};
|
||||
|
||||
// Feedback is only offered when the deployment can deliver it (email
|
||||
// transport configured); most tests want that baseline without asserting
|
||||
// anything about the mail itself. The service reads `config.email` — the
|
||||
// same live object every layer holds — so the helper writes it there and
|
||||
// the global afterEach clears it.
|
||||
const liveConfig = () =>
|
||||
(server.clients.email as unknown as { config: Record<string, unknown> })
|
||||
.config;
|
||||
const mockEmailConfigured = () => {
|
||||
liveConfig().email = { jsonTransport: true };
|
||||
};
|
||||
|
||||
const confirmOwnerEmail = async (userId: number) => {
|
||||
await server.clients.db.write(
|
||||
'UPDATE `user` SET `email_confirmed` = ? WHERE `id` = ?',
|
||||
[server.clients.db.booleanValue(true), userId],
|
||||
);
|
||||
const user = await server.stores.user.getById(userId);
|
||||
if (user) await server.stores.user.invalidate(user);
|
||||
};
|
||||
|
||||
const makeReq = (init: {
|
||||
body?: unknown;
|
||||
actor?: Actor;
|
||||
query?: Record<string, unknown>;
|
||||
}): Request => {
|
||||
return {
|
||||
body: init.body ?? {},
|
||||
query: init.query ?? {},
|
||||
headers: {},
|
||||
actor: init.actor,
|
||||
} as unknown as Request;
|
||||
};
|
||||
|
||||
const makeRes = () => {
|
||||
const captured: { statusCode: number; body: unknown } = {
|
||||
statusCode: 200,
|
||||
body: undefined,
|
||||
};
|
||||
const res = {
|
||||
json: vi.fn((value: unknown) => {
|
||||
captured.body = value;
|
||||
return res;
|
||||
}),
|
||||
status: vi.fn((code: number) => {
|
||||
captured.statusCode = code;
|
||||
return res;
|
||||
}),
|
||||
};
|
||||
return { res: res as unknown as Response, captured };
|
||||
};
|
||||
|
||||
const findRoute = (method: string, path: string) => {
|
||||
const route = router.routes.find(
|
||||
(r) => r.method === method && r.path === path,
|
||||
);
|
||||
if (!route) throw new Error(`No ${method.toUpperCase()} ${path} route`);
|
||||
return route;
|
||||
};
|
||||
|
||||
const callRoute = async (
|
||||
method: string,
|
||||
path: string,
|
||||
req: Request,
|
||||
res: Response,
|
||||
) => {
|
||||
const handler: RequestHandler = findRoute(method, path).handler;
|
||||
await handler(req, res, () => {
|
||||
throw new Error('handler called next() unexpectedly');
|
||||
});
|
||||
};
|
||||
|
||||
const submit = (actor: Actor, body: unknown) => {
|
||||
const { res, captured } = makeRes();
|
||||
return callRoute('post', '/', makeReq({ body, actor }), res).then(
|
||||
() => captured,
|
||||
);
|
||||
};
|
||||
|
||||
// ── Route gates ─────────────────────────────────────────────────────
|
||||
|
||||
describe('AppFeedbackController route options', () => {
|
||||
it('rejects app actors and cross-origin pages on submit', () => {
|
||||
const { options } = findRoute('post', '/');
|
||||
// requireUserActor is what makes feedback impossible to submit
|
||||
// programmatically with an app token; guiOriginOnly keeps
|
||||
// cross-origin browser pages out even with a leaked user token.
|
||||
expect(options.requireUserActor).toBe(true);
|
||||
expect(options.guiOriginOnly).toBe(true);
|
||||
});
|
||||
|
||||
it('stacks a per-user budget with a per-IP backstop', () => {
|
||||
const { options } = findRoute('post', '/');
|
||||
const limits = options.rateLimit;
|
||||
expect(Array.isArray(limits)).toBe(true);
|
||||
const keys = (limits as Array<{ key?: unknown }>).map((l) => l.key);
|
||||
expect(keys).toContain('user');
|
||||
expect(keys).toContain('ip');
|
||||
});
|
||||
|
||||
it('requires a user actor on the target pre-flight too', () => {
|
||||
const { options } = findRoute('get', '/target');
|
||||
expect(options.requireUserActor).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ── GET /app-feedback/target ────────────────────────────────────────
|
||||
|
||||
describe('AppFeedbackController GET /target', () => {
|
||||
it('throws 400 when neither or both of app/origin are given', async () => {
|
||||
const { actor } = await makeUser();
|
||||
for (const query of [
|
||||
{},
|
||||
{ app: 'x', origin: 'https://x.example.com' },
|
||||
]) {
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute('get', '/target', makeReq({ query, actor }), res),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
}
|
||||
});
|
||||
|
||||
it('reports enabled:false for an unknown app', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({ query: { app: 'no-such-app-xyz' }, actor }),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({ enabled: false, app: null });
|
||||
});
|
||||
|
||||
it('reports enabled:false for an app that has not opted in', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId);
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({ query: { app: app.name }, actor }),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toMatchObject({ enabled: false });
|
||||
});
|
||||
|
||||
it('reports enabled:true with canonical title/name for an opted-in app', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({ query: { app: app.uid }, actor }),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({
|
||||
enabled: true,
|
||||
app: { name: app.name, title: app.title },
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves an opted-in app whose name starts with "app-"', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const name = `app-fdbk-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true, name });
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({ query: { app: name }, actor }),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({
|
||||
enabled: true,
|
||||
app: { name: app.name, title: app.title },
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves an origin to the app whose index_url it matches', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const origin = new URL(app.index_url).origin;
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({ query: { origin }, actor }),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({
|
||||
enabled: true,
|
||||
app: { name: app.name, title: app.title },
|
||||
});
|
||||
});
|
||||
|
||||
it('reports enabled:false when the email transport is unconfigured', async () => {
|
||||
// No mockEmailConfigured(): this is the self-hosted no-SMTP default.
|
||||
// Feedback that can never be delivered must not be solicited.
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({ query: { app: app.name }, actor }),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toMatchObject({ enabled: false });
|
||||
});
|
||||
|
||||
it('reports enabled:false for an origin with no registered app', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'get',
|
||||
'/target',
|
||||
makeReq({
|
||||
query: { origin: 'https://nobody-registered.example.com' },
|
||||
actor,
|
||||
}),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({ enabled: false, app: null });
|
||||
});
|
||||
});
|
||||
|
||||
// ── POST /app-feedback ──────────────────────────────────────────────
|
||||
|
||||
describe('AppFeedbackController POST /', () => {
|
||||
it('throws 400 when message is missing or not a string', async () => {
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const { actor } = await makeUser();
|
||||
for (const message of [undefined, 12345, '']) {
|
||||
await expect(
|
||||
submit(actor, { app: app.name, message }),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
}
|
||||
});
|
||||
|
||||
it('throws 400 when both app and origin are given', async () => {
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
submit(actor, {
|
||||
app: 'x',
|
||||
origin: 'https://x.example.com',
|
||||
message: 'hi',
|
||||
}),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('throws 400 when the origin exceeds the stored column size', async () => {
|
||||
// source_origin is VARCHAR(2048) on MySQL/Postgres; a longer origin
|
||||
// must be rejected up front, not fail (or silently truncate) at the
|
||||
// INSERT after passing every other validation.
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const origin = `${new URL(app.index_url).origin}/${'x'.repeat(2500)}`;
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
submit(actor, { origin, message: 'hi' }),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('throws 403 feedback_not_enabled when the app has not opted in', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId);
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
submit(actor, { app: app.name, message: 'hi there' }),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
legacyCode: 'feedback_not_enabled',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws 403 for an unknown app and an unknown origin alike', async () => {
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
submit(actor, { app: 'no-such-app-xyz', message: 'hi' }),
|
||||
).rejects.toMatchObject({ statusCode: 403 });
|
||||
await expect(
|
||||
submit(actor, {
|
||||
origin: 'https://nobody-registered.example.com',
|
||||
message: 'hi',
|
||||
}),
|
||||
).rejects.toMatchObject({ statusCode: 403 });
|
||||
});
|
||||
|
||||
it('throws 403 feedback_not_enabled when the email transport is unconfigured', async () => {
|
||||
// No mockEmailConfigured(): the opted-in app must still refuse — a
|
||||
// stored row nothing can read, sold to the sender as delivered, is
|
||||
// worse than an honest refusal.
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
submit(actor, { app: app.name, message: 'into the void' }),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
legacyCode: 'feedback_not_enabled',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws 400 when the message exceeds the length limit', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
submit(actor, {
|
||||
app: app.name,
|
||||
message: 'x'.repeat(
|
||||
AppFeedbackService.MESSAGE_MAX_LENGTH + 1,
|
||||
),
|
||||
}),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('stores a normalized row and responds with an empty object', async () => {
|
||||
mockEmailConfigured();
|
||||
const { userId: ownerId } = await makeUser();
|
||||
const app = await makeApp(ownerId, { feedbackEnabled: true });
|
||||
const { actor, userId } = await makeUser();
|
||||
const captured = await submit(actor, {
|
||||
app: app.uid,
|
||||
message: ' Great\r\napp! | ||||