mirror of
https://github.com/storytold/artcraft-services.git
synced 2026-11-19 08:53:03 +01:00
main
100
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f4416f8f7f | Point the Omni API docs at the Cloudflare Worker and drop the Netlify rollback build | ||
|
|
1ce37b5f28 | Serve the API docs on storyteller-docs.artcraft.team from a Cloudflare Worker | ||
|
|
999b402564 |
Stop rebuilding the website during wrangler deploy (#410)
## What the log shows
The Cloudflare build for `artcraft-services` succeeded, then failed
during
deploy:
```
04:52:46 Success: Build command completed
04:52:47 Executing user deploy command: npx wrangler deploy
04:52:56 [custom build] Running: npm run build <-- build runs again
04:53:35 [custom build] Generating static Linux repositories and Flatpak OCI catalog...
04:53:46 [custom build] DOMException [TimeoutError] at fetchHeadPackageSize (linux-repos.ts:274)
[custom build] Error: Command failed: ... generate-static-repos.mjs
✘ [ERROR] Running custom build `npm run build` failed.
```
Two things combine:
1. The root `wrangler.jsonc` declared `"build": { "command": "npm run
build" }`.
Workers Builds already runs the project's build command, so `wrangler
deploy`
rebuilt the entire static export a second time.
2. The second pass re-probed every published package on GitHub (523
package
redirects, 19 OCI repos). `fetchHeadPackageSize` treats one 10s HEAD
timeout
as fatal, so the repeat pass — running ~50s behind the first burst of
identical requests — failed the deploy.
This is not a regression from #408 or #409: neither touches the website
build.
The `build.command` has been in the config since #354, and the failing
probe is
pre-existing.
## Changes
- `wrangler.jsonc`: remove `build.command`, with a comment explaining
why. The
deploy now uploads the `out/` that Workers Builds just produced,
matching how
the webapp and dashboard Workers already behave. A manual `wrangler
deploy`
needs `npm run build:website` first.
- `linux-repos.ts`: `fetchHeadPackageSize` retries three times with a
short
backoff instead of failing the export on a single unanswered HEAD.
## Verification
- `npm ci --ignore-scripts && npm run typecheck` in
`frontend/apps/artcraft-website-next` — exit 0.
- `wrangler deploy --dry-run --config wrangler.jsonc` against a
placeholder
`out/` parses the config and skips straight to bundling: no `[custom
build]`
pass, which is the behavior this PR is after. The dry-run cannot
complete
locally because `worker/index.mjs` imports `generated-catalog.mjs`,
which the
full build generates.
- Not run: the Playwright `test:repos` suite, which needs the deployed
preview.
## Risk
- Deploying the website by hand now needs an explicit build first:
`npm run build:website && npm run deploy:website`. On a clean checkout
`wrangler deploy` fails loudly ("Could not resolve
./generated-catalog.mjs")
because both `out/` and `worker/generated-catalog.mjs` are gitignored
build
artifacts.
- This assumes the Worker keeps a build command configured in Workers
Builds
(the failing log shows `npm run build`). If that field is cleared, the
deploy
step has no artifacts to upload.
|
||
|
|
590ecaf9b1 |
Deploy artcraft-dashboard without the website's signing keys (#409)
## Why
`artcraft-dashboard` was documented (and configured) with the shared
Cloudflare
commands:
| Setting | Value |
|----------------|-----------------------------------|
| Build command | `npm run build` |
| Deploy command | `npm run deploy` |
| Build variable | `ARTCRAFT_APP=artcraft-dashboard` |
Both scripts fall back to `ARTCRAFT_APP=artcraft-website`, so a
dashboard deploy
that was missing the build variable did two wrong things:
- the build ran the website's static export, including
`signLauncherCatalog()`, so the deployment failed without
`LAUNCHER_CATALOG_SIGNING_KEY`;
- the deploy handed Wrangler the **root** config instead of the
dashboard's:
```
✘ [ERROR] The directory specified by the "assets.directory" field in your
configuration file does not exist:
/opt/buildhome/repo/frontend/apps/artcraft-website-next/out
```
## What changed
- The dashboard README now configures the Worker with `npm run
build:dashboard`
and `npm run deploy:dashboard`. Those npm scripts set
`ARTCRAFT_APP=artcraft-dashboard` inline and pass
`frontend/apps/artcraft-dashboard/wrangler.jsonc` to Wrangler, so the
Worker
needs no build variable at all beyond `NODE_VERSION=22`.
- Added a "Build secrets" section stating the dashboard reads neither
`LAUNCHER_CATALOG_SIGNING_KEY` nor `LINUX_SIGNING_KEY`, and that plain
`npm run build` / `npm run deploy` must not be used for this Worker.
- The root README table now lists the per-app build/deploy commands
instead of an
`ARTCRAFT_APP` column, and documents the same trap.
- `cloudflare_app.sh` header comment updated to match.
- Added the missing `deploy:website` script so all three apps have a
symmetric
`build:<app>` / `deploy:<app>` pair.
No build logic changed: `artcraft-dashboard` never referenced the
signing keys
before this PR either. The change removes the misconfiguration path that
made
them appear to be required.
## Verification
- `env -u LAUNCHER_CATALOG_SIGNING_KEY -u LINUX_SIGNING_KEY pnpm install
--frozen-lockfile && pnpm build`
in `frontend/apps/artcraft-dashboard` — exit 0, `dist/` produced without
`_redirects`.
- `wrangler deploy --dry-run --config
frontend/apps/artcraft-dashboard/wrangler.jsonc`
— reads 5 files from `dist/`, binds `env.ASSETS`, clean exit.
- `node -e require('./package.json')` parses; `bash -n` on
`cloudflare_app.sh` and
`build_cloudflare.sh` passes.
## After merge
In the Cloudflare `artcraft-dashboard` Worker, set build command
`npm run build:dashboard`, deploy command `npm run deploy:dashboard`,
and drop
the `ARTCRAFT_APP` build variable. Keep `NODE_VERSION=22`. No signing
secret
needs to be added to this Worker.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Documentation**
* Clarified the app-specific Cloudflare build and deployment commands
for the website, webapp, and dashboard, including that the bare commands
default to the website and require `ARTCRAFT_APP` to select another app.
* Added dashboard Workers Builds guidance, including its Node.js version
requirement and app-specific Wrangler configuration.
* Clarified that only the website build uses signing credentials and its
launcher assets, and warned against deploying the dashboard with the
default Wrangler command.
* **Deployment**
* Added a dedicated command for deploying the website.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
766ead6629 |
Configure artcraft-dashboard for Cloudflare at dashboard.artcraft.team (#408)
## Problem The admin dashboard is deployed only to Netlify (`artcraft-dashboard.netlify.app`), while the rest of the frontends deploy to Cloudflare from this repository. Move it to Cloudflare and serve it at `dashboard.artcraft.team`. ## Change - **`frontend/apps/artcraft-dashboard/wrangler.jsonc`** — `artcraft-dashboard` static-assets Worker: SPA `not_found_handling`, `run_worker_first: ["/api/*"]`, custom domain `dashboard.artcraft.team`. - **`cloudflare_worker/index.ts`** — same-origin `/api/*` proxy to `https://api.storyteller.ai`. The dashboard calls the API with `credentials: "include"`, so its session cookie has to stay first-party; `api.storyteller.ai` is a different site than `dashboard.artcraft.team`, so a direct cross-site call would have the cookie dropped by browsers. This replaces Netlify's `/api/*` rewrite. - **`script/website/cloudflare_app.sh` + root `package.json`** — `ARTCRAFT_APP=artcraft-dashboard`, plus `npm run build:dashboard` / `npm run deploy:dashboard`. - **`_redirects`** moved from `public/` to the app root and copied into `dist/` by `netlify_build.sh`, so the Cloudflare upload never contains the `/* /index.html 200` loop or the external-host proxy that Workers reject. Netlify keeps working unchanged as the rollback target. - **CORS** — `https://dashboard.artcraft.team` allowlisted in `artcraft_admin_dashboard.rs`, the regression table, and the production product-origin test. - **`tsconfig.app.json`** — excludes spec files. `DebugLogCard.spec.ts` imports `vitest`, which only resolved through the parent workspace's `node_modules`; the standalone Cloudflare build never installs those, so `tsc -b` failed. - Docs: dashboard README (deploy, proxy rationale, rollback) and the root README Worker table. ## Cloudflare settings | Setting | Value | |----------------|-----------------------------------| | Build command | `npm run build` | | Deploy command | `npm run deploy` | | Build variable | `ARTCRAFT_APP=artcraft-dashboard` | | Build variable | `NODE_VERSION=22` | `VITE_API_HOST` is deliberately not set: the dashboard keeps calling `/api`, and the Worker proxies it. ## Checklist before cutover - [ ] `artcraft.team` is a zone in the Cloudflare account (Workers custom domains require the zone). - [ ] `artcraft-dashboard` Worker created from this repo with the settings above. - [ ] Domain attached; log in and confirm the session works at `https://dashboard.artcraft.team`. A `*.workers.dev` URL is not CORS-allowlisted, so test through the domain (or add the test host to the CORS config first). - [ ] Netlify site kept for rollback; reverting is pointing the domain back at it. ## Testing - `cargo test -p actix_cors_configs` — 81 passed, including the new `dashboard_domain` case and the allowlist regression table. - `pnpm install --frozen-lockfile && pnpm build` in `frontend/apps/artcraft-dashboard` — succeeds (9014 modules); `dist/` has no `_redirects`. - `wrangler deploy --dry-run --config frontend/apps/artcraft-dashboard/wrangler.jsonc` — clean: 5 assets, `env.ASSETS` binding, no config warnings. - Not run: an actual deploy, since there are no Cloudflare credentials or account access in this environment. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * The ArtCraft Admin Dashboard is now available at `dashboard.artcraft.team`, with dashboard API requests routed through the new deployment. * The dashboard’s production origin is now allowed for cross-origin requests. * **Documentation** * Added deployment and build guidance for the dashboard, including its Cloudflare hosting and API routing details. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
896824e56f |
Build the webapp on Cloudflare without the website's signing keys (#407)
## Problem app.getartcraft.com serves `Hello world`. Its `artcraft-webapp` Worker builds this repository with `npm run build`, which always built **artcraft-website-next** and failed on the website's `LAUNCHER_CATALOG_SIGNING_KEY`. The Worker never got a successful deploy, so it kept its placeholder. ## Change - `npm run build` / `npm run deploy` choose the app from the `ARTCRAFT_APP` build variable via `script/website/cloudflare_app.sh`. The default, `artcraft-website`, is the old behaviour, so the website Worker needs no changes. - `ARTCRAFT_APP=artcraft-webapp` builds only the Nx webapp. It needs **no signing keys**. - `frontend/apps/artcraft-webapp/wrangler.jsonc` is now a static-assets Worker (`artcraft-webapp`). It uses SPA `not_found_handling` and the `app.getartcraft.com` custom domain, replacing the unused Pages `app-new` config. - The Cloudflare `public/_redirects` no longer has the `/* /index.html 200` fallback, since Workers assets reject it as a loop. Netlify's `_redirects` is untouched. - `nx build --skipSync` plus the `nx sync` output for pagedraw/pagescene. Nx refused to build in CI without those references, and that also fails on current `main`. ## Cloudflare settings for the artcraft-webapp Worker | Setting | Value | |----------------|-----------------------------------------| | Build command | `npm run build` | | Deploy command | `npm run deploy` | | Build variable | `ARTCRAFT_APP=artcraft-webapp` | | Build variable | `VITE_GOOGLE_CLIENT_ID` (as on Netlify) | ## Testing - `ARTCRAFT_APP=artcraft-webapp CI=true npm run build` with no signing keys in the environment: succeeds, 239 files, none over 25 MiB. - `wrangler deploy --config frontend/apps/artcraft-webapp/wrangler.jsonc --dry-run`: clean, no `_redirects` warnings. - An unknown `ARTCRAFT_APP` exits 1 with usage. - Not run: the website build path, which is the unchanged command moved into the script. |
||
|
|
bb8ec12a47 | fix: require the internal API key on the GPT image job callback (#287) | ||
|
|
de65625356 | fix: refuse to start production with the public fallback secrets (#300) | ||
|
|
3fce0f73ae | fix: bill and run Veo 3.1 with the same default duration; bound router downloads (#314) | ||
|
|
23e4f021bc | fix: exclude never-paid Stripe statuses from active subscriptions; keep URL options for test DB bootstrap (#327) | ||
|
|
f6a3dd6b9c | fix: cap decompressed size when extracting PMX zip archives (#383) | ||
|
|
499462fe07 | fix: reject mesh generation without a model before resolving media (#386) | ||
|
|
06272d654b | fix: authorize profile edits by user token, not cached username (#388) | ||
|
|
ad03b98ed6 | ci: let Dependabot maintain GitHub Actions dependencies (#393) | ||
|
|
e4be25b4fd | security: drop rustls 0.22 and lettre's rustls 0.21 edge (#405) | ||
|
|
e585d12bfd |
ci: use StepSecurity's maintained actions (#382)
Each third-party action that StepSecurity publishes a secure drop-in replacement for now uses that replacement, pinned to a commit with its version as a comment. Versions follow what we used: the newest StepSecurity release in the same major, or the closest major they publish. dtolnay/rust-toolchain refs that named a toolchain (stable, nightly, 1.76) become the replacement's `toolchain` input. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Chores** * Updated the automation integrations used for pull request creation and container registry sign-in. * Existing workflow settings and registry credentials remain unchanged. Some container build workflow steps remain inactive. * These maintenance updates do not change the app’s features or behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
4c9f1b98f5 |
fix: refuse to show desktop-login approval inside a frame (#266)
## What was wrong The desktop-login consent page (`/login/desktop`, `DesktopLoginApproval`) could be rendered inside a cross-origin frame. The webapp's `netlify.toml` sends no `frame-ancestors` or `X-Frame-Options` for it, and the component did not check for framing. An attacker can start a login challenge for their own desktop, embed the verification URL in a page they control, hide the frame under decoy content, and steer the signed-in victim's click onto "Approve desktop login". The backend then issues the victim's session to the attacker's device-token holder (clickjacking, CWE-1021). ## What changed - `apps/artcraft-webapp/netlify.toml`: `/login/desktop` and `/login/desktop/*` are served with `Content-Security-Policy: frame-ancestors 'none'` and `X-Frame-Options: DENY`. This is scoped to the approval route so other webapp pages are unaffected. - `libs/login/.../desktop-login-approval.tsx`: if `window.self !== window.top` (or that check throws), the component renders "Open this login link directly in your browser to approve it." It does not fetch the review and `decide` is a no-op. This covers deployments that do not send the headers. - New webapp test: a framed render shows no Approve button and makes no API call. ## Blast radius Only the desktop-login approval route. Opening the link top-level (browser, QR code) behaves as before. Any legitimate flow that frames `/login/desktop` would stop working; none exists in this repo. ## Checks run - `NODE_OPTIONS=--no-experimental-webstorage npx vitest run --root apps/artcraft-webapp src/pages/login`: 20/20 pass, including the new framed case. Under Node 26 the flag is needed, or jsdom's `sessionStorage` is shadowed and every test in this file fails, before and after this change. - `npx vitest run --root libs/login`: pass. - `netlify.toml` parses as TOML. ## Checks not run - `tsc -p libs/login/tsconfig.lib.json`: only the pre-existing TS6305 errors for the unbuilt `@storyteller/api` `dist`. - Netlify deploy preview header verification. Addresses CodeRabbit security findings (CWE-1021). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Desktop login approval pages displayed inside a frame now instruct visitors to open the link directly in a browser. The page does not load or submit a login challenge, or offer approval or decline actions. * Browser security headers prevent desktop login pages from being displayed within frames, including when framed pages involve cross-origin access. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
9101e4e9d7 |
fix(webapp): restrict onboarding redirect_to to same-origin paths (#289)
## What was wrong `onboarding.tsx` decoded the `redirect_to` query parameter and passed it straight to `navigate()`. A protocol-relative value such as `//evil.example` (or its encoded form) made the router fall back to a full browser navigation, so an onboarding link could send a freshly signed-up user to an external site (open redirect, CWE-601). ## What changed - `redirect_to` is decoded once (a malformed encoding is kept as-is instead of throwing) and validated with the existing `safeAuthReturnPath` from `lib/login-bridge-context`; anything that is not a same-origin path becomes `/`. - Both navigation paths and the status text use that validated value. ## Blast radius Onboarding page only. Real values (`/checkout/success`, `/checkout/cancel`, `/pricing`, `/`) pass through unchanged. ## Checks run - `tsc -p apps/artcraft-webapp/tsconfig.app.json`: no new errors compared with `main`. ## Checks not run - No new test: the change only calls the existing `safeAuthReturnPath`, which already has coverage in `desktop-login.spec.tsx`. - Manual walk through the onboarding flow. |
||
|
|
f13f35644d |
ci: run Harden-Runner on every job (#381)
Adds step-security/harden-runner (audit, pinned to v2.22.4 like craft-common-actions) as the first step of each job that did not have it, so every workflow in the org's public repos reports its egress to StepSecurity. Audit, not block: block-mode allow lists come from each job's observed traffic. |
||
|
|
3d75db28e3 |
fix: parse Forwarded for= nodes and match disabled endpoints on the routed path (#322)
What was wrong: (1) the Forwarded fallback returned the whole first list element (e.g. `for=1.2.3.4;proto=http`), so exact IP bans never matched. (2) The disabled-endpoint filter compared the raw URI path while actix routes on the percent-decoded path, so an equivalent encoded spelling bypassed it. Change: Forwarded values are parsed per RFC 7239 (first for= node, quotes/brackets/port stripped); X-Forwarded-For is unchanged. The filter now checks request.match_info().as_str(), the path actix routes with. Blast radius: crates/lib/actix_helpers (ban filter and disabled-endpoint middleware). Behavior changes: requests using a Forwarded header now yield a bare IP; encoded spellings of a disabled path are now blocked. Checks run: cargo test -p actix_helpers (new Forwarded test). Checks not run: clippy -D warnings (91 pre-existing errors in this crate on main); no integration test of the middleware against an encoded URI. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Forwarded IP addresses are now read from the first `for` parameter, including quoted values and IPv6 addresses. Other supported IP headers retain their existing parsing behavior. * Disabled-endpoint checks now use the matched route rather than the raw request path, improving checks for requests handled through routed endpoints. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
094a662fba |
fix: hide job result locations the caller may not read (#277)
## What was wrong
`GET /v1/jobs/job/{token}` is public and joined the job's result media
by token alone. A known job token kept disclosing the result's media
token, bucket path and CDN links after the creator made the result
private or it was soft-deleted.
## What changed
For `media_file` results the handler now resolves the session and
re-reads the media through `get_media_file` (moderators see deleted
rows, others do not). `maybe_result_details` is dropped from the
response unless the media is readable by the caller: not private, or the
caller is the creator (user token or anonymous visitor token), or a
moderator. Status, progress and failure fields are unchanged, so polling
keeps working for everyone.
## Blast radius
One handler; one extra media lookup per status poll of a completed
media-file job. Legacy TTS / voice-conversion result types are not
affected.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0).
- Not run: the job status tests need a live MySQL.
|
||
|
|
ffc4c469ad |
fix: require read access to the source image before background removal (#276)
## What was wrong `POST /v1/generate/image/remove_background` looked up the caller-supplied `media_file_token` and submitted its CDN URL to Fal without checking the media's visibility. Anyone who knew another user's **private** image token could run background removal on it and collect the derivative through the job the handler created for them. ## What changed After the media lookup, the handler now requires that the source is readable by the requester: not `Private`, or the requester is its creator (session user token, or the anonymous visitor token for anonymous uploads), or a moderator (`can_delete_other_users_tts_results`, the convention the media read handlers use). Otherwise it returns `NotFound`, so a private token's existence is not confirmed. ## Blast radius One handler. Public and hidden sources behave as before; only private sources belonging to someone else are now rejected. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: the handler tests need a live MySQL. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Background removal requests now check access to the source image before processing. Non-private images remain accessible. Private images are available to moderators and their creator, or to a visitor presenting the matching anonymous visitor credential when no creator credential is present. Requests without the required access receive a not-found response. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
b72e0e26cb |
fix: check cover image access when setting and serving covers (#267)
## What was wrong
`POST /v1/media_files/cover_image/{token}` (and the model weight
equivalent) accepted any image token as a cover after checking only that
it was an image. Listings then joined the cover by token alone and
returned its bucket path and CDN links. A user could attach another
user's **private** image as the cover of their own media and read its
storage location from any listing of that media. Covers that were later
deleted or made private also kept being served.
## What changed
- New helper `media_files/helpers/may_use_as_cover_image.rs`: a private
image may be used as a cover only by the user who created it. Public and
hidden images behave as before. Both cover setters
(`set_media_file_cover_image_handler`,
`set_model_weight_cover_image_handler`) use it and answer `NotFound` on
refusal, the same as a missing token.
- Every media-file cover join in `mysql_queries` (get, batch get, list,
featured, for-user, session, project, batch-generated, source job, tags,
files-without-folder, Elasticsearch backfill) now joins the cover only
when it is live and either not private or owned by the same creator as
the media file it decorates. Existing bad associations stop leaking
without a data migration.
- `.sqlx` entries for the 16 changed `query!` macros were regenerated
against a local schema built from `_database/sql/migrations`. Column
metadata was kept from the existing MySQL entries; only the query text,
hash and parameters changed.
## Blast radius
- Public and hidden covers, and a creator's own private covers on their
own media, render as before.
- A cover that is deleted, or private and owned by someone other than
the media's creator, now comes back as no cover.
- Not changed: the `batch_get_media_files_by_tokens` and folder-listing
cover joins (those files are touched by #227/#229 and the folder PR, so
they are left to avoid conflicts), and the model-weight cover joins in
the weights list queries. The setters now block new associations there;
read-time checks for those queries are a follow-up.
## Checks run
- `SQLX_OFFLINE=true cargo test -p mysql_queries --lib --no-run`:
compiles against the updated `.sqlx` cache
- `SQLX_OFFLINE=true cargo test -p storyteller-web --features
skip_database_tests --bin storyteller-web -- may_use_as_cover_image`:
builds the full crate, 2 new tests pass
- Every changed query was described successfully by sqlx against a local
MariaDB 11.8 loaded with all migrations
## Checks not run
- `cargo sqlx prepare` against production-equivalent MySQL (sqlx-cli is
not installed and only MariaDB was available. Please re-run it if the
cache flags differ.)
- Endpoint integration tests against MySQL
Addresses CodeRabbit security findings (CWE-863).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Deleted cover images are no longer displayed.
* Private images are used as covers only when they belong to the same
creator as the media file; public and hidden images remain eligible.
* Cover-image selection in media and model-weight workflows now respects
private-image access rules.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
a083615cd3 |
fix: keep other users' private media out of folders (#254)
## What was wrong
Folder bulk-add and bulk-move only checked that each media token existed
and wasn't deleted. A user who knew another user's private media token
could put it in their own folder, and the folder list (`GET
/v1/folders/media_files/{folder}`) and folder thumbnails
(`last_media_thumbnails`) then returned that file's CDN URLs and
metadata.
## What changed
- `filter_existing_media_file_tokens` takes `viewer_user_token` and only
keeps private files created by that user. Bulk add and bulk move pass
the session user.
- `batch_get_media_file_thumbnails_by_tokens` takes an optional
`maybe_restrict_private_to_creator`. Folder thumbnails pass the session
user, so memberships that already exist (or files made private later)
stop showing. The Elasticsearch thumbnail-version lookup passes `None`;
it returns no URLs.
- `list_folder_media_files_handler` re-checks private rows on each page
and drops the ones the viewer didn't create. The pagination cursor is
still taken from the unfiltered page.
All new SQL uses `QueryBuilder` with bound parameters, so no `.sqlx`
metadata changes.
## Blast radius
Folders are owner-only. Behaviour changes: another user's private file
can no longer be added to a folder (it is silently skipped, as missing
tokens already are), and such files already in a folder no longer appear
in its listing or thumbnails. A page of the folder list can be shorter
than the limit when rows are hidden.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup
--tests`.
- Not run: endpoint/query tests; they need a live MySQL.
Addresses CodeRabbit security findings (CWE-862).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Folder listings now hide private media files that the viewer cannot
access, while preserving access to their own private files and eligible
non-private files.
* Folder thumbnails no longer reveal private media belonging to another
user.
* Adding or moving media into folders silently skips private files the
viewer cannot access.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
75361b0560 |
fix: hide unreadable context media on prompt reads (#231)
> Stacked on **#228** → **#229** (merge in that order). This PR needs
`MediaReadScope` and `media_read_policy` from those branches; it rebases
onto `main` cleanly once they land.
## Summary
`GET /v1/prompts/{token}` lists the prompt's context items (reference
images, style images, uploads) and built a CDN link and media token for
each from `list_prompt_context_items`, which selects storage locations
only. The media's own visibility was never consulted, so reading a
prompt — including a prompt that was shared or public — exposed the
storage URLs and tokens of another user's **private** media.
The handler now resolves the context media through the shared read scope
and drops items the requester may not read. The prompt still renders its
readable context; private media referenced by it stays private and is no
longer linkable through the prompt.
## Notes
- Moderation goes through `can_ban_users`, matching the existing
moderator-fields logic in this handler.
- `maybe_user_session` is now borrowed rather than moved, since the
scope needs it after the moderator check.
- One extra media query per prompt read (only when the prompt has
context items).
## Checks
- `SQLX_OFFLINE=true cargo check -p storyteller-web` — finished clean,
exit 0.
- No tests run: the prompt endpoint tests need a live MySQL.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Prompt responses now include context media only when it is readable
under the current session’s media access policy. Failed media lookups no
longer prevent a response from being returned.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
a6b5f738af |
fix: enforce private media visibility on token batch reads (#228)
## Summary `GET /v1/media_files/batch` takes a list of media tokens and returned every matching record — storage paths, titles, transcripts, original filenames — to any caller. The session was read only to decide whether deleted records were visible; it played no part in authorizing private ones. The handler now keeps only records the requester may read: - private records are returned to their creator and to moderators, - private records are **dropped** for everyone else, rather than the request failing, so a batch of guessed tokens discloses neither content nor which token matched. The rule lives in a new shared helper, `util/lookup/media_read_policy.rs::ensure_may_read_media`, returning `NotFound` for a private record the caller may not read. It matches the check in `get_weight_handler.rs` and is intended for the other media read paths too, so the policy is not re-derived per endpoint. ## Blast radius `batch_get_media_files` has exactly one caller (this handler), so the endpoint is fully covered. Public and hidden media behave as before; response order is preserved for the remaining records, and the `results` array may be shorter than the requested token list. ## Checks - `SQLX_OFFLINE=true cargo check -p storyteller-web` — finished clean. - No tests run: the media endpoint tests need a live MySQL, which this environment does not provide. Worth adding a case for anonymous callers requesting another user's private token before merging. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Batch media requests now omit private media that the viewer is not authorized to access. Private media remains available to its creator and moderators, while other viewers receive no indication that the restricted item exists. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
ec461047a5 |
fix: enforce private media visibility for reads and batch lists (#226)
## Summary Two endpoints returned private media records without comparing `creator_set_visibility` against the requester, so knowing a token was enough to read another user's private media, including its storage locations and transcripts. **Single-file lookup** (`media_files/get/get_media_file_handler.rs`) - The handler now passes the viewer's `user_token` into both lookup branches. - A shared `ensure_may_read_media` helper returns `NotFound` for `Visibility::Private` records unless the viewer is the creator or a moderator. The same policy now applies to the legacy `TR:` TTS emulation branch, which previously had no check at all. - `NotFound` rather than `NotAuthorized` avoids confirming that a private token exists. This mirrors the check in `get_weight_handler.rs`. **Batch listing** (`media_files/list/list_media_files_by_batch_token_handler.rs`) - The endpoint hard-coded `ViewAs::Author` with a "this is wrong, but gotta go fast" TODO, so any caller holding a batch token received every record in the batch regardless of visibility. - Scope now derives from the session: `Moderator` for moderators, `Author` for other logged-in users, `AnotherUser` for anonymous callers. - `maybe_creator_user_token` is selected with the page so private records are dropped for anyone who is neither the creator nor a moderator. ## Notes - Public and hidden media behave as before; only private access changes. - For non-moderators the batch page can be shorter than `page_size`, and `total_page_count` still counts records the caller may not read, because filtering happens after the query. Fixing that properly needs visibility-aware SQL and is left for a follow-up. - Verified with `SQLX_OFFLINE=true cargo check -p storyteller-web` (finished clean). No tests were added or run: the media endpoints are covered by integration tests that need a live MySQL, which is not available here. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Private media files are visible only to their creator or a moderator. Other viewers will not see private files in batch listings, and direct requests return not found. * Access rules apply consistently to standard media files and legacy text-to-speech results. * Viewer identity is recognized from an authenticated session or a viewer token, allowing creators to access their private media without signing in. * Public media remains accessible according to existing permissions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
dc36ccb6ba |
fix: stop generation from reading other users' private media (#229)
> **Stacked on #228**, which adds `util/lookup/media_read_policy.rs`.
Merge that first; this PR then rebases onto `main` cleanly.
## Summary
Every generation endpoint takes media tokens from the request
(`start_frame_media_token`, `reference_image_media_tokens`, inpainting
sources, image-to-3D inputs, …) and resolved them through
`batch_get_media_files_by_tokens`, which only filtered on existence and
soft deletion. Possession of a token therefore authorised use of the
record: another user's private image could be submitted as a generation
input, and several paths (`lookup_image_urls_as_map`,
`lookup_image_urls_as_optional_list`,
`lookup_media_files_as_cdn_url_list_and_map`) handed back a CDN URL for
it too.
## Changes
- `batch_get_media_files_by_tokens` (all three wrappers) takes a
`MediaReadScope { viewer_user_token, is_mod }` and adds, for
non-moderators:
`AND (m.creator_set_visibility <> 'Private' OR
m.maybe_creator_user_token IS NULL OR m.maybe_creator_user_token = ?)`
Records with no creator are system intermediates that generation depends
on; they are not anyone's private data, so they remain readable. Tokens
are still bound, not interpolated.
- The five lookup helpers forward the scope;
`fetch_reference_video_sources` and the query wrappers take it as a
parameter.
- Call sites supply the requester: `scope_for_session` for cookie
sessions (so moderators keep their access), `scope_for_user_token` for
API-key/SSO callers, `MediaReadScope::ANONYMOUS` for the two genuinely
unauthenticated paths (the cost-quote duration probe and the curated
pinned-media list).
- `get_character_handler` previously read no session at all; it now
resolves one so a creator can still see their own private uploads while
anonymous callers cannot.
## Behaviour changes worth reviewing
- A generation request naming someone else's private token now fails as
"media not found" rather than generating from it.
- Private media can no longer be used as a generation input, even by a
logged-in non-owner. That is the point of the fix, but it is a real
behaviour change for any client that reused tokens across accounts.
- Anonymous callers no longer resolve private media for pinned lists or
cost quotes.
## Checks
- `SQLX_OFFLINE=true cargo check -p storyteller-web` — finished clean,
exit 0.
- No tests run: the media query and endpoint tests need a live MySQL,
which this environment does not provide. The 58-file diff is almost
entirely one added argument per call site; a reviewer should spot-check
the two `ANONYMOUS` sites and the `get_character_handler` session
addition.
|
||
|
|
b8b09b5990 |
fix(db-cleanup): include concrete image types in anonymous image cleanup (#253)
## What was wrong `db-cleanup`'s `delete_all_anonymous_user_images` listed only media files with the legacy coarse `Image` type, then re-checked `MediaFileType::Image` before deleting. Anonymous uploads made through `POST /v1/media_files/upload/image` are stored with a MIME-derived type (`Jpg`, `Png`, `Gif`, `Webp`), so the cleanup skipped them and they never got the moderator-deletion marker. ## What changed - The listing filter now includes every type `MediaFileType::is_image()` accepts (`Image`, `Jpg`, `Png`, `Gif`, `Webp`). - The per-record check uses `is_image()`, so the filter and the check agree. - Small unit test that the selected set matches `is_image()`. ## Blast radius Operator CLI only. Running the command now also soft-deletes (as moderator) anonymous images with concrete types, which is what the command says it does. Files with a creator are still skipped. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup --tests` (combined with the other fixes in this batch). - Not run: the command itself against a database. Addresses CodeRabbit security findings (data retention policy gap). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Anonymous-image cleanup now recognizes JPEG, PNG, GIF, and WebP files alongside legacy image files, so these formats are included when cleaning up images without a creator token. * Non-image files are skipped during cleanup. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
d4033df996 |
fix: enforce the bucket request timeout, cap debug sleeps, fix db-cleanup batch paging (#324)
What was wrong: - LegacyBucketClient called Bucket::set_request_timeout, which rust-s3 (tokio backend) ignores: the HTTP client is built in the constructor. A storage peer that stalled a response held a worker forever. - The video-style-transfer, face-fusion and video-style-transfer-workflow jobs slept for a request-header-supplied number of milliseconds with no maximum, parking a worker. - db-cleanup delete_user_files advanced an offset over a listing that shrinks as files are deleted, so it skipped every other batch. Change: when a timeout is configured, the bucket is rebuilt with with_request_timeout (it applies to the whole request, including body). Debug sleeps go through debug_sleep_duration, capped at 60 s. db-cleanup always reads offset 0 (deleted files are excluded from the listing). Blast radius: cloud_storage, inference-job (3 call sites), db-cleanup. Behavior changes: callers that pass Some(timeout) (jobs default to 5 min via BUCKET_TIMEOUT_SECONDS, web 60 s-ish via env) now actually get that limit per request, so very large transfers longer than the configured value will fail instead of running unbounded. Debug sleeps above 60 s are clamped. Checks run: cargo check -p cloud_storage -p db-cleanup -p inference-job; cargo test -p inference-job --bin inference-job debug_sleep. Checks not run: fmt/clippy, db-cleanup against a database, incomplete-download file cleanup on timeout (not changed). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * File cleanup now processes remaining files in batches without relying on page offsets. * Debug delays in face-fusion and video-style-transfer jobs are capped at 60 seconds, preventing excessively long waits. * Cloud storage bucket requests now apply a timeout only when one is configured, with client setup errors propagated. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
3577dda534 |
fix: enforce owner TTS delete permission, case-insensitive reserved usernames, escape log values (#323)
What was wrong:
- delete_tts_model: the owner branch ignored the session's
can_delete_own_tts_models permission, so a role denying owner deletion
could still delete.
- create_account: reserved usernames were checked on the submitted text
before the lowercase/trim applied when the account is stored, so e.g.
"Admin" passed.
- list_media_files_for_user (v1/v2) and upload_url_to_media_file logged
request-supplied username/URL with {} so CR/LF could forge log lines.
Change: owners must have can_delete_own_tts_models (moderators
unaffected); is_reserved_username trims and lowercases itself; the log
arguments use {:?}. User-visible URL error strings are unchanged.
Blast radius: three handlers plus is_reserved_username (only used by
account creation validation).
Behavior changes: owners whose role lacks can_delete_own_tts_models now
get NotAuthorized; mixed-case/space-padded reserved names are now
rejected.
Checks run: cargo check -p storyteller-web (exit 0).
Checks not run: handler/unit tests (need MySQL; a new unit test for
case-insensitive reserved names was added but not executed), fmt/clippy.
|
||
|
|
de764c9d81 |
fix: persist the requested visibility when importing TTS and voice conversion models (#326)
What was wrong: the download job processors (tacotron, VITS, RVC v2,
So-VITS-SVC, SoftVC) hard-coded Visibility::Public ("TODO: All models
default to public") instead of the creator's queued choice, and
insert_tts_model_from_download_job /
insert_voice_conversion_model_from_download_job accepted
creator_set_visibility but never wrote it. A model imported as Private
or Hidden became public.
Change: both INSERTs now write creator_set_visibility, and the
processors pass job.creator_set_visibility (the hifigan vocoder
processors already did). The two changed sqlx::query! statements have
updated .sqlx offline entries (old entries removed; written by hand from
the same describe data, one extra bind parameter, hash = sha256 of the
new text, and verified by an offline compile).
Blast radius: two mysql_queries insert functions, five download-job
processors. The model_weights inserts already persisted the field.
Behavior changes: imports queued as Private/Hidden are now stored that
way instead of Public. Imports queued as Public are unchanged.
Checks run: cargo check -p download-job (SQLX_OFFLINE=true).
Checks not run: DB tests (need MySQL), fmt/clippy, `cargo sqlx prepare
--check` (no database; entries not regenerated by tooling).
|
||
|
|
9cd544adef |
fix: bound decoded downloads, linear tag recount, ban/ownership checks on legacy handlers (#316)
## What was wrong - `http_download_url_to_bytes` enabled gzip and collected the whole decoded body with `bytes()` and no size limit, so a small compressed response from an attacker-chosen media origin could exhaust memory. - `apply_tags` merged previously linked tag tokens into a growing `Vec` with `contains` per token (quadratic CPU on attacker-accumulated history, inside a transaction). ## What changed - The downloader reads chunks and returns a new `DownloadFileToBytesError::TooLarge` once decoded bytes pass 1 GiB (generous headroom over legitimate media). Error-status bodies are bounded the same way. - `apply_tags` uses a `HashSet` for membership; resulting order and contents are identical. ## Behavior changes Downloads larger than 1 GiB now fail. Nothing else for valid input. ## Checks - run: `cargo check -p storyteller-web --tests` - not run: DB-backed tests (need MySQL); clippy -D warnings (fails on unmodified main in `enums`); no test for the 1 GiB cap (would need to serve that much). ## Second part: authorization fixes ### What was wrong - The five legacy text-to-image handlers (flux 1 dev/schnell, flux pro 1.1/ultra, gpt-image-1) accepted any valid session, including banned accounts. - `terminate_inference_job_handler` only compared owners when the caller also had a session; omitting the cookie made an account-owned job fall back to IP equality, so anyone behind the same IP could cancel it. - `change_media_file_engine_category_handler` returned category-specific errors (existence/engine details) before checking the caller may edit the file. ## What changed - Banned sessions get `NotAuthorized` in those five handlers. - Account-owned jobs require the owning session; the IP rule remains only for anonymous jobs. - Creator-or-moderator check moved directly after loading the record. ## Behavior changes Banned users lose access to those routes (intended); a signed-out caller can no longer cancel an account-owned job from the same IP; non-owners now get NotAuthorized instead of validation messages. ## Checks - run: `cargo check -p storyteller-web --tests` - not run: handler tests (need MySQL); clippy -D warnings (fails on unmodified main in `enums`). Findings: 46338003, 44b859e9, 56186c57, 1f1f2f34, 5456374d Not touched: media-lookup/mesh dedup (09045369, 0355e215; files in #229) and the missing wallet deduction on legacy Flux Dev/Hunyuan (owner). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Banned accounts can no longer submit text-to-image generation requests. * Terminating an inference job now requires a matching signed-in session when the job has a creator. IP-based checks remain for jobs without a creator. * Media-file engine category changes now check permissions before validating category selections. * URL downloads follow up to 10 redirects and are limited to 1 GiB; oversized downloads are rejected. Non-success responses continue to report the response details. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
ab32c3aec6 |
fix: bound decompressed bytes when extracting studio-shot frames (#303)
## What was wrong The studio-shot upload extracts frame images from a ZIP into a temp directory with an unbounded `std::io::copy`. The 8,000-file cap limits entry count, not decompressed size, so a small, highly compressible archive could expand to many gigabytes of temp writes and decompression work inside the request. ## What changed Each member is copied through `copy_within_budget`, which reads at most one byte past the limit and fails with a new `ExtractFramesError::TooLarge` when a frame exceeds `MAX_FRAME_BYTES` (64 MiB) or the upload exceeds `MAX_TOTAL_EXTRACTED_BYTES` (4 GiB). The handler maps it to an error response like the other extraction errors. The constants sit next to the existing `TOO_MANY_FILES_COUNT`. ## Checks - Run: `cargo test -p storyteller-web extract_frames_from_zip` (3 passed: a frame exactly at the limit, one byte over, and the running total); `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: the upload endpoint test (needs a live MySQL). - Not done: moving extraction off the request worker (the finding's second suggestion). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * ZIP uploads now reject frames larger than 64 MiB and combined extracted frames exceeding 4 GiB, with a clear error message when archive contents are too large. * Errors while reading or writing extracted frames are reported as extraction failures. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
11242401eb |
fix: reject expired web sessions (#230)
## Summary `get_api_or_web_session_user_by_session_token` is the lookup behind cookie authentication. It joined `user_sessions` and filtered on `deleted_at` and the user's own deletion state, but never compared `expires_at`. The signed cookie payload carries no expiry claim either, so an expired session row kept authenticating every request — a hijacked or long-lived cookie stayed valid until someone deleted the row. The lookup now also requires: ```sql AND (user_sessions.expires_at IS NULL OR user_sessions.expires_at > UTC_TIMESTAMP()) ``` The `IS NULL` arm keeps any legacy row without an expiry non-expiring rather than silently logging everyone out; if `expires_at` is `NOT NULL` in production it is simply dead. ## Note on the `.sqlx` cache `sqlx::query!` is compile-checked against `.sqlx/`, and this environment has no MySQL, so `cargo sqlx prepare` could not run. I generated the replacement cache entry the way `prepare` does (same column metadata, `hash = sha256(query)`), and the crate compiles offline against it. **Please run `cargo sqlx prepare` against a real database before merging** to confirm the entry matches what the tool would produce. ## Checks - `SQLX_OFFLINE=true cargo check -p storyteller-web` — finished clean, exit 0. - No tests run: `mysql_testing` fixtures (including `expire_user_session`) need a live MySQL. A regression test that expires a session and expects a 401 would be worth adding here. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Expired sessions are no longer accepted during session lookup, including sessions that expire at the current time. * Sessions without an expiration time remain eligible for lookup. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
a3f7204180 |
fix: reject passwords longer than bcrypt's 72-byte input (#302)
## What was wrong bcrypt only uses the first 72 bytes of a password. Account creation, password change and password reset accepted longer passwords and hashed them, so everything after byte 72 was silently ignored. A user who changed only the tail of a long password hadn't really changed it, and a long passphrase was weaker than it looked. ## What changed - `password` crate: new `BCRYPT_MAX_PASSWORD_BYTES = 72`. `bcrypt_hash_password` returns a new `PasswordHashError::PasswordTooLong` instead of truncating (with a unit test at 72 and 73 bytes). - `validate_passwords` (account creation, password change) rejects longer passwords with a clear 400 message. - Password reset redemption rejects them with a new `PasswordTooLong` 400 error. Login (`bcrypt_confirm_password`) is unchanged, so existing accounts with longer passwords can still sign in; they just can't set a new one over 72 bytes. ## Checks - Run: `cargo test -p password` (6 passed); `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: endpoint tests (need a live MySQL). |
||
|
|
80440b43fe |
fix: answer password reset requests before doing account-dependent work (#312)
## What was wrong `POST /v1/password_reset/request` returns the same body whether or not the account exists, but not in the same time. For unknown accounts it returned right after the lookup. For real accounts it first created the reset record, inserted the email job, and awaited the external Resend email send. The response time difference (often hundreds of ms) lets anyone enumerate registered emails and usernames. ## What changed After the lookup, the account-dependent work moves unchanged into `issue_password_reset`, which runs on a spawned task (`actix_web::rt::spawn`). The handler returns the success response immediately in both cases. Failures in the background task are logged (`error!`) instead of returned. Callers couldn't act on them anyway, and unknown accounts already got a plain success. ## Blast radius One handler. A reset email that fails to send no longer produces a 500 for the requester; it shows up in logs instead. #217 touches the lookup lines above this change; any rebase is trivial. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: endpoint tests (need a live MySQL and email provider). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Password reset requests now return the same success response whether or not the account exists. * Requests for known accounts are acknowledged immediately while the reset email is processed in the background. Processing failures do not change the response. * When reset processing is at capacity, requests still receive the same success response. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
147f9a7fa7 |
fix: revoke existing sessions when a password reset is redeemed (#310)
## What was wrong
Redeeming a password reset changed the password (and bumped
`password_version`) but left every existing session valid, and session
checks don't look at `password_version`. Someone who already had a
session on the account (the reason for recovering it, often) kept access
after recovery and could even change the password again.
## What changed
`change_password_from_password_reset` now also soft-deletes all of the
user's live `user_sessions` rows inside the same transaction as the
password update, rolling back if that fails. The redeem handler already
creates a fresh session for the person who completed the reset, after
commit.
It's a runtime `sqlx::query` (no new `.sqlx` offline entry needed).
Sessions already cached in Redis expire within the cache TTL
(`REDIS_CACHE_TTL_SECONDS`, 60s by default).
- A password login now creates its session with one conditional insert:
it succeeds only if `password_version` still matches the version the
password was verified against, under a row lock on the user. A login
that races a reset is answered as invalid credentials instead of leaving
a live session behind.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0).
- Not run: the reset flow tests (need a live MySQL).
- Not changed: ordinary password changes (`change_password_handler`)
still keep other sessions.
## Review round (
|
||
|
|
28e7caa573 |
fix: reject other users' private images as Veo 2, Veo 3 Fast and Kling 2.1 Master sources (#319)
## What was wrong The legacy image-to-video handlers for Veo 2, Veo 3 Fast and Kling 2.1 Master loaded the caller-supplied source image by token without checking visibility, so anyone holding another user's private image token could send it to the provider and receive derived output. ## What changed Same check as #283 (Veo 3): a Private source is usable only by its creator or a moderator (`can_delete_other_users_tts_results`); otherwise `NotFound`, so existence is not confirmed. ## Behavior changes Using someone else's private image as a source now returns 404. Public/unlisted and own images unchanged. ## Not covered fcdeb392 also lists Kling 1.6 Pro, Kling 2.1 Pro, Seedance 1.0 lite/pro and the Beeble edit handler; they load media through different code paths (batch lookup / video sources) and are left open for a follow-up. Veo 3 is #283. ## Checks - run: `cargo check -p storyteller-web --tests` - not run: handler tests (need MySQL); clippy -D warnings (fails on unmodified main in `enums`). Finding: fcdeb392 (partial) |
||
|
|
2394ab8070 |
fix: refuse another user's private image as a weight cover (#318)
## What was wrong Both weight cover setters (`set_model_weight_cover_image_handler` and the `cover_image_media_file_token` branch of `update_weight_handler`) authorized the weight but only checked that the chosen media file exists and is an image. A weight owner who knew another user's private image token could make it the cover and publish its storage links. ## What changed A Private image that the caller did not create is rejected with `NotFound` (same rule as the cover-image read paths in #267: not private, or same creator). Own private images and any non-private image still work. ## Behavior changes Setting someone else's private image as a cover now returns 404. ## Checks - run: `cargo check -p storyteller-web --tests` - not run: handler tests (need MySQL); clippy -D warnings (fails on unmodified main in `enums`). Findings: 58119149, 2490367c |
||
|
|
307026f29b |
fix: hide unreadable results on batch and Omni API job status (#309)
## What was wrong
Three job-status reads return a completed job's result media token,
bucket path and CDN links to anyone holding the job token, without
checking the result media's current visibility or deletion:
- `GET /v1/jobs/batch` (public, cookie session optional)
- `GET /v1/omni_api/job_status/{token}` and the Omni API batch route
(API-key authenticated, but the authenticated user was discarded)
So results the creator later made private, or deleted, stayed reachable
through any known job token.
## What changed
New shared helper `util::lookup::hide_unreadable_job_results` takes the
job records, the viewer's user token and moderator flag, loads all media
results in one `batch_get_media_files_by_tokens` query (deleted rows
only for moderators), and clears `maybe_result_details` for results that
are deleted, or private and not the viewer's. Status, progress and
failure fields are untouched.
- Web batch: viewer from the cookie session; moderators via
`can_delete_other_users_tts_results`.
- Omni API single and batch: viewer is the API key's user
(`require_api_key_user` already returned it).
The single web job route (`/v1/jobs/job/{token}`) is handled in #277.
## Notes for review
- #229 adds a read-scope parameter to `batch_get_media_files_by_tokens`.
Whichever merges second needs a one-line update here (passing
`MediaReadScope` or keeping `can_see_deleted`).
- Anonymous (visitor-token) creators of private media aren't matched
here; private results are normally owned by logged-in users.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web`; `cargo test
-p storyteller-web hide_unreadable_job_results` (1 passed, covers
public/hidden/private, creator, other user, moderator, missing creator).
- Not run: endpoint tests (need a live MySQL).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Job status responses now hide media results that the viewer isn’t
permitted to access, while retaining other status information.
* Private media results are shown only to their creator or a moderator.
Public and hidden media results remain visible, and missing media
results are hidden.
* If media lookup fails, result details are hidden rather than exposing
potentially inaccessible results.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
eff0b1e676 |
fix: check access to job inputs before enqueueing legacy media jobs (#271)
## What was wrong The legacy enqueue routes took media tokens from the request and queued them without checking who owned them: - `/v1/conversion/enqueue_fbx_to_gltf` - `/v1/animation/face_animation/create` - `/v1/animation/rerender/create` - the live portrait / face mirror routes - the face fusion route - the studio and VST workflow routes - `/v1/workflow/comfy/create` - the GPT-SoVITS model download (cover image) The workers download those objects with the service's bucket credentials and publish the result under the requester. Anyone holding another user's private media token could therefore get a converted, animated or restyled copy of it. With GPT-SoVITS, they could attach it as a model cover that anyone can read. The live portrait worker also reads deleted inputs. ## What changed - New `util::job_input_access`. It allows an input only when it exists, is not deleted, and is either non-private or created by the requester. Moderators (`can_ban_users`) are allowed. Records with no creator user follow the same rule as the batch media read policy in #229. - Every route listed above now checks each input token before inserting the job. A media-file, media-upload or voice-conversion-result token that fails the check gets a not-found or bad-input response. - New query `media_uploads::get_media_upload_access_info`. Legacy media uploads need their creator token for this check, and existing queries don't return it. It is a runtime query because `maybe_creator_user_token` on that table has no offline cache entry. Swap it for `query_as!` after the next `cargo sqlx prepare`. ## Blast radius Only callers who name media they cannot read are affected. Their jobs are no longer enqueued. Jobs on your own media, public media or hidden media are unchanged. ## Not covered here - The workers do not recheck access before downloading. Any job already in the queue, or any job inserted by another path, is still processed. - The video style transfer worker follows `original source` references. That lookup is not rechecked. - The weight read path still serves the cover links that are already stored on weights. Addresses CodeRabbit security findings (CWE-639). ## Checks run - `SQLX_OFFLINE=true cargo check -p storyteller-web -p mysql_queries` - Unit tests for the visibility rule (`job_input_access`) are included; results to follow in a comment once the shared build host frees up. ## Checks not run - Handler and query tests against a live MySQL. - End-to-end worker runs. They need GPUs and the bucket. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Job submissions now check whether referenced media, uploads, and voice-conversion results are available to the requester before creating a job. * Public and hidden items are usable by any requester. Private items are usable by their creator or a moderator; private items without a creator are also usable by any requester. * Missing, deleted, or inaccessible inputs are rejected as not found. Access-check errors are reported as server errors. * Checks cover animation, workflow, conversion, and model-download submissions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
d1c203236f |
fix: hide private and deleted media from public bookmark lists (#257)
## What was wrong
`GET /v1/user_bookmarks/list/user/{username}` is public. Its query joins
`media_files` for media bookmarks and returned the bucket hash, prefix,
extension and creator for every bookmarked file, regardless of the
file's visibility or deletion state. Anyone could list another user's
bookmarks and get CDN URLs for private (or deleted) media.
## What changed
- `list_user_bookmarks_by_maybe_entity_type` takes
`maybe_viewer_user_token` and `viewer_is_moderator`.
- For non-moderators, rows that join a media file are kept only if the
file is not deleted and is either non-private or created by the viewer.
Non-media bookmarks are unaffected. The count query uses the same
filter, so page counts stay consistent.
- The handler resolves the optional session; moderators
(`can_delete_other_users_tts_results`, as in `get_media_file_handler`)
see the list unfiltered.
- Unit tests on the generated SQL.
## Blast radius
Public bookmark lists lose private/deleted media entries for anonymous
and non-owner viewers. Model-weight bookmarks are not filtered by weight
visibility here.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup
--tests`.
- Not run: the new `mysql_queries` unit tests and endpoint tests (need
MySQL for the latter).
Addresses CodeRabbit security findings (CWE-862).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Bookmarked media now follows visibility and deletion rules: private or
deleted media is hidden from viewers who aren’t allowed to see it.
* Creators can still see their own private bookmarked media, and
moderators can view bookmarks without these filters.
* Bookmark lists and totals reflect the viewer’s access, with anonymous
viewers handled without a signed-in session.
* If session lookup fails, bookmark lists can still be shown without
signed-in access.
* Bookmark responses are marked as private and are not stored in caches.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
357d4705b9 |
fix: don't use a private imageref as the cover of a shared result (#256)
## What was wrong For mesh/splat results with no thumbnail, the FAL webhook attaches the prompt's first image reference as the result's cover (`try_to_attach_prompt_imageref_cover`). It never looked at the reference's visibility, so a private source image could become the cover of a public result, and every response that shows the result's cover then exposed the private image's bucket path and URL. ## What changed Before attaching, the helper loads the imageref and the target media file: - non-private imageref: attach as before; - private imageref: attach only if the result is also private and has the same creator; - any lookup error or missing row: skip (the helper already fails open on the webhook, closed on the cover). Unit tests cover the decision table. ## Blast radius Webhook cover fallback only. Results generated from a private image now get no cover unless they are private too. Covers attached before this change are not cleaned up, and cover links in media responses still don't apply the cover's own visibility. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup --tests`. - Not run: the new unit tests (the crate's test build is heavy here) and a webhook replay (needs MySQL). Addresses CodeRabbit security findings (CWE-863). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Prompt image covers are now displayed only when their visibility is compatible with the result. Private images appear only on private results created by the same person. * Covers are skipped when image details are unavailable or cannot be checked, preventing potentially restricted images from appearing. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
5569669446 |
fix: confine the Comfy workflow output path to the job's output directory (#246)
## What was wrong `POST /v1/workflow/comfy/create` accepts `maybe_output_path` from the caller. The inference worker: - joined it onto the Comfy output directory, - copied the input video to it (`SKIP-PROCESS-VIDEO`), - deleted it, or the directory, during cleanup, - and spliced it into `bash -c` command lines for audio restoration (`FfmpegAudioReplaceArgs`) and watermarking. Because of this, an absolute path or `..` escaped the output directory (CWE-22), and shell metacharacters ran commands as the worker (CWE-78). ## What changed `check_and_validate_job` now rejects any output path that is not made only of plain relative segments of `[A-Za-z0-9._-]`. That means no empty, `.` or `..` segments, no leading `/` or `-`, and at most 255 bytes. The check runs before the job does any work. The default path `vid2vid/SparseUpscaleInterp_00001.mp4` and the paths legacy clients send still pass. ## Blast radius Only jobs from the legacy Comfy route that send unusual output paths are affected. Those jobs now fail validation instead of running. Studio and VST jobs do not set an output path, so they are unchanged. Addresses CodeRabbit security findings (CWE-22, CWE-78). ## Checks run - `cargo test -p inference-job --bins check_and_validate_job` (new unit tests for traversal, absolute paths and shell metacharacters) ## Checks not run - An end-to-end worker run. It needs ComfyUI, a GPU and the bucket. - Replacing `bash -c` with direct process arguments in `CommandRunner`. That would be a wider refactor of the deprecated worker. With this change the paths it receives are already inert. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **Bug Fixes** - Output paths for video style transfer jobs are now checked for valid format and length. Invalid paths—including absolute paths, traversal segments, unsupported characters, and paths that are too long—are rejected with an error identifying the path. Valid relative paths continue to be accepted. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
c92c0a61c4 |
fix: pass download URLs to the downloader as arguments, not shell text (#241)
## What was wrong `GoogleDriveDownloadCommand::download_file` and `download_file_with_file_name` put the download URL into a shell string (`--url "<url>"`) and ran it with `sh -c`. Double quotes do not stop `$(...)` or backticks, so a URL submitted to the generic download enqueue routes or the GPT-SoVITS model download route could run commands on the download/inference worker. The Docker variant nested the same string inside `bash -c "..."`, which had the same problem. ## What changed - The URL and output filename are no longer part of the shell source. The script is now `<download_script> --url "$1" --output_filename "$2"` and the values are passed as positional parameters to `sh -c`, so the shell expands them as plain data. The configured script, venv activation and working directory (operator config) keep working as before. - With Docker, the command is built as an argument vector with a new `DockerOptions::to_command_args`. The URL and filename go to the container shell as `$1`/`$2`, and no host shell is involved. - The two methods now share one `run_downloader`/`build_command` helper instead of duplicating the logic. ## Blast radius Deprecated download_job, tts_download_job and inference_job upload paths (GPT-SoVITS, SD/LoRA, workflow uploads). The public method signatures are unchanged. `DockerOptions::to_command_string` is unchanged, and its other callers are not affected. ## Checks run - `cargo test -p google_drive_downloader -p subprocess_common` passed. New tests: a hostile URL containing `$(...)`, backticks and quotes reaches the downloader as one literal argument (run through a real `sh`), the generated shell source never contains the URL, and the Docker argument vector keeps positional arguments separate. ## Checks not run - No end-to-end run of the download workers (they need the Python downloader script, Docker, and a job queue). - `cargo check` was not run on the dependent job binaries (`download_job`, `tts_download_job`, `inference_job`). The public API they use is unchanged. Addresses CodeRabbit security findings (CWE-78). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Downloads now pass the URL and output filename separately, so characters in these values are preserved rather than interpreted as part of a command. * Docker-based downloads retain support for configured environment variables, bind mounts, and GPU options. * Failed downloads continue to report error details when available, with a fallback message when the error output cannot be read. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
581b4e38d0 |
fix: enforce the Google sign-in issue-time cutoff against the token's iat (#288)
## What was wrong `decode_and_verify_token_claims` accepts a `VerificationOptions` whose `reject_before` is meant to refuse tokens issued before a cutoff. The pinned jwt-simple compares `reject_before` with the **current clock**, not the token's `iat`, so once the cutoff is in the past every older token passes and the caller's policy silently does nothing. ## What changed `decode_and_verify_token_claims_with_key` notes `reject_before` before verification and, after the signature checks out, requires the verified `issued_at` to be at or after it. A token without `iat` is rejected when a cutoff is set. Callers that don't set `reject_before` see no change. ## Checks - Run: `cargo test -p google_sign_in` (8 passed, including a new test with the fixture token: a cutoff equal to its `iat` passes, one second later fails). |
||
|
|
1e17f43913 |
fix: grant author media listings by user token, not cached username (#286)
## What was wrong
`GET /v1/media_files/list/user/{username}` (and the v2 handler) decided
author access by comparing the path username with the username in the
cached session. Usernames can change and be reassigned while an old
session cache still holds the previous name, so the old owner of a
released username could list the new owner's private media.
## What changed
Both handlers resolve the path username to its user token
(`get_user_token_by_username`) and grant author access only when that
token equals the session's user token. The listing query is unchanged.
## Blast radius
Two handlers; one extra indexed lookup per request. Users listing their
own media and moderators are unaffected.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0).
- Not run: endpoint tests (need a live MySQL).
|
||
|
|
1bbf69e0f5 |
fix: refuse saved-scene overwrites when ownership can't be verified (#301)
## What was wrong
The legacy saved-scene upload (replace an existing scene's stored file)
checks ownership with `check_creator_tokens`. When neither the record
nor the request carried a user or visitor token, the result was
`InsufficientInformation`, which fell through as "allowed" (marked with
a TODO saying it should be a 401). An unauthenticated caller who knew
such a scene's token could replace its contents.
## What changed
`InsufficientInformation` now returns `NotAuthorizedVerbose("cannot
verify ownership of this scene")` before anything is uploaded. Matching
user or visitor tokens behave as before.
## Blast radius
Scenes created with no user and no visitor token can no longer be
overwritten in place by anyone; saving to a new scene still works. That
is the TODO's intended behavior.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0).
- Not run: endpoint tests (need a live MySQL).
|
||
|
|
a392b59d7c |
fix: drop plaintext legacy origins from the production CORS policy (#305)
## What was wrong The production CORS policy (credentialed) allowed nine plaintext `http://` origins for the legacy `storyteller.stream` and `create/obs/ws.storyteller.ai` hosts, with a TODO to remove them. A network attacker who can rewrite one of those HTTP pages can make a visitor's browser call the API with their cookies and read the responses, including the MCP session tokens returned by `create_mcp_session_handler`. ## What changed `add_legacy_storyteller_stream` now allows only the HTTPS variants in production. The rows for the removed origins are dropped from `allowlist_regression_tests`, and a new test asserts that each removed origin is rejected while `https://create.storyteller.ai` is still allowed. ## Not changed The `devproxy.fakeyou.com` / `devproxy.storyteller.ai` HTTP origins (finding 7020bef5) are also allowed in production, but the regression table pins them as intentional (`Both`), presumably for developers proxying to the production API. Removing them is a product call, so it's left out here. ## Checks - Run: `cargo test -p actix_cors_configs` (79 passed). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Security** * Storyteller production and staging origins, including legacy create, OBS, and WebSocket hosts, no longer accept plaintext HTTP connections. * HTTPS connections to the configured production origins remain available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
446980fa67 |
fix: invalidate pending password resets when the email changes (#258)
## What was wrong A password reset is bound to the user's `password_version`, not to the address it was emailed to. Redeeming it sets `email_confirmed = true` on whatever address the account has *now*. Changing the email (`update_email`) did not invalidate pending resets, so a user could request a reset at a mailbox they control, change the account to an address they don't own, then redeem the reset and have the unverified address marked confirmed. ## What changed `update_email` also bumps `password_version` in the same `UPDATE`. `lookup_password_reset_request` already requires `pw.current_password_version = u.password_version`, so every reset issued before the change stops working. `password_version` is used only for reset binding (checked with a grep), so this does not sign anyone out. `.sqlx` metadata for the changed query was written by hand (query text + SHA-256 hash; the describe block has no columns and 4 parameters, same as before). The old entry is removed. Please run `cargo sqlx prepare` against a database to confirm. ## Blast radius User and moderator email changes. Outstanding reset links stop working after an email change; users request a new one, which goes to the new address. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup --tests` (validates the offline metadata entry is found). - Not run: `cargo sqlx prepare --check`, and reset/email flow tests (need MySQL). Addresses CodeRabbit security findings (CWE-640). |
||
|
|
2fa9ad41d3 |
fix: reject banned callers when setting user roles and creating comments (#242)
## What was wrong Banning an account leaves its role and its live sessions in place. - `POST` set-user-role (`deprecated_endpoints/moderation/user_roles/set_user_role.rs`) only checked `can_ban_users`. A banned staff account with a live session could still change other accounts' roles, for example to hand its privileges to an account that is not banned. - `create_comment_handler` only checked that a session existed, so a banned user could keep posting comments. ## What changed - `set_user_role_handler` now uses `require_user_session`, which rejects banned callers. - `create_comment_handler` returns `NotAuthorized` when `user_session.is_banned`. ## Blast radius Only banned accounts are affected. They get 401 on these two routes. Behaviour for everyone else is unchanged. Addresses CodeRabbit security findings (CWE-863). ## Checks run - `SQLX_OFFLINE=true cargo check -p storyteller-web` ## Checks not run - Handler tests. They need a live MySQL. Separately, revoking sessions on ban, as the finding also suggests, is not part of this change. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Comment submissions from signed-in users marked as banned are now rejected before the comment is processed. * Requests to change a user’s role now apply standard session validation, including handling for callers marked as banned. This makes access checks more consistent across comment creation and role changes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
0cae43fe39 |
fix: report logout failure when the session could not be revoked (#259)
## What was wrong `delete_user_session` dropped the result of its `UPDATE user_sessions SET deleted_at = ...`, and `logout_handler` ignored the helper's return value anyway. If the update failed, logout still returned `success: true` while the session stayed valid in the database, so a copied session cookie kept working. ## What changed - `delete_user_session` propagates the database error. An unknown or already-revoked session is still not an error. - `logout_handler` returns a 500 when revocation fails, instead of reporting success. ## Blast radius Only `POST /v1/logout`. On a database failure the client now sees an error (and the cookie isn't cleared), so it can retry or tell the user the session may still be active. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup --tests`. The query text is unchanged, so no `.sqlx` change. - Not run: endpoint tests (need MySQL). Addresses CodeRabbit security findings (CWE-613). |
||
|
|
ce6281de6e |
fix: purge the session cache after revoking the session on logout (#299)
## What was wrong `logout_handler` purged the Redis session cache *before* revoking the session in MySQL. A request carrying the same cookie that arrived in between re-read the still-valid session from MySQL and re-cached it, so the session kept working after logout until the cache TTL ran out. ## What changed The cache purge now runs after `delete_user_session`, so anything cached afterwards reflects the revoked row. Nothing else changes. ## Notes #259 changes the same few lines (it makes the revocation error fatal). The two changes are compatible; whichever merges second needs a trivial rebase. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: endpoint tests (need a live MySQL). |
||
|
|
7890fb6a86 |
fix: refuse Google sign-in for banned accounts (#298)
## What was wrong Password login refuses banned accounts (`login_handler` checks `is_banned`), but Google sign-in resolved the local account and created a session without that check. A banned user with a linked (or email-matched) Google identity could sign in again and use any endpoint that doesn't re-check the ban. ## What changed After resolving the local user and before `create_user_session_with_transactor`, `google_sso_handler` looks the account up with `lookup_user_for_moderation_by_token` and returns `NotAuthorized` if it is banned. No session is created. ## Blast radius One handler, one extra indexed lookup per Google sign-in. Non-banned users are unaffected. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: endpoint tests (need a live MySQL). |
||
|
|
c886927af6 |
fix: hide private TTS models from other users (#285)
## What was wrong
`GET /tts/model/{token}` returned a model's title, descriptions, creator
details and configuration whatever its visibility. It computed
author/moderator status but only used it to pick the text-pipeline
label, so anyone with a private model token could read it.
## What changed
After the model is loaded (from the Redis TTL cache or the database), a
`Private` model is returned only to its creator or a moderator; everyone
else gets `NotFound`. The check runs after the cache, so a stale cached
entry cannot skip it.
## Blast radius
One handler. Public models and authors' own private models are
unchanged.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0).
- Not run: endpoint tests (need a live MySQL).
|
||
|
|
357c83cd9b |
fix: hide private vocoder models from other users (#260)
## What was wrong
`GET /vocoder/model/{token}` is anonymous. It used the optional session
only to decide moderator fields and whether deleted rows are visible; it
returned private vocoder models (title, description, creator) to anyone
with the token.
## What changed
After loading the model, the handler returns `404` unless the model is
non-private, or the viewer is its creator, or a moderator
(`can_ban_users`, as the handler already uses). The decision is a small
function with unit tests.
## Blast radius
Legacy vocoder read endpoint only. `GET /vocoder/list` still returns all
undeleted models; its query doesn't select visibility, so filtering it
needs a query change with new `.sqlx` metadata and is left out of this
PR.
## Checks
- Run: `SQLX_OFFLINE=true cargo check -p storyteller-web -p db-cleanup
--tests`.
- Not run: the new unit tests and endpoint tests (need MySQL).
Addresses CodeRabbit security findings (CWE-862).
|
||
|
|
8edb687660 |
fix: stop resolving deleted media on public character reads (#263)
## What was wrong
`GET /v1/character/{token}` is anonymous. It looked up the character's
avatar and full-image media with `can_see_deleted = true`, so
soft-deleted images were still returned as CDN links. The list endpoint
already passes `false`.
## What changed
The get handler now passes `false`, so deleted media no longer resolves
to links.
The private-visibility half of the same finding is handled by #229,
which adds a read scope to this lookup. The two changes touch the same
call, so whichever merges second needs a one-line rebase.
## Blast radius
One public read endpoint. Characters whose images were deleted now
return no image links for them, matching the list endpoint.
Addresses CodeRabbit security findings (CWE-862).
## Checks run
- `SQLX_OFFLINE=true cargo check -p storyteller-web`
## Checks not run
- Handler tests. They need a live MySQL.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Character media links no longer resolve to deleted media.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
afa57937fe |
fix: require HTTPS for credentialed FAL queue polling (#264)
## What was wrong `poll_job_status` and `poll_job_response` checked only that the caller-supplied queue URL's host was `queue.fal.run` before attaching `Authorization: Key <FAL API key>`. An `http://queue.fal.run/...` URL passed that check, so the key could be sent in cleartext. A redirect could also downgrade the request. ## What changed - A new shared `polling::queue_url::validate_queue_url` requires the `https` scheme and the `queue.fal.run` host. Both helpers use it instead of each having its own host-only check. - Both helpers send the request through an `https_only(true)` reqwest client, so a redirect cannot downgrade to HTTP either. ## Blast radius Only the `fal_client` polling helpers. Real FAL status and response URLs are always `https://queue.fal.run/...`, so legitimate polling is unchanged. ## Checks run - `cargo test -p fal_client --lib polling` (new tests: plain-HTTP URLs are rejected by both helpers, plus validator unit tests) ## Checks not run - No live polling against FAL (it needs an API key and a job). Addresses CodeRabbit security findings (CWE-319). |
||
|
|
c41edee6a7 |
fix: keep the support-tool media cache private and stop following planted links (#308)
## What was wrong The support-tool's `kinovi_web generate_video` command caches media in `/tmp/media_files` by default, and `artcraft_client::download_media_file` writes downloads into it. - Another local user could pre-create that shared directory and plant entries. `fs::File::create` follows a planted symlink, so a download could create or truncate any file the operator can write. - `find_cached_file` followed symlinks when picking up cached files, so a planted link could make the operator read, and upload, a private file. - In directory mode the filename came from the media token unchanged, so a token containing `/` or `..` could write outside the directory. ## What changed - The default cache is now `~/.cache/storyteller-support-tool/media_files`, created with mode 0700. Any cache directory (default or `--download_path`) must be a real directory with no group/other permission bits, or the command stops with a `chmod 700` hint. An owner-only directory belonging to someone else is unreadable to us, so this rules out foreign-controlled caches without a uid lookup. - Cached entries are inspected with `symlink_metadata` and must be regular files. - `download_media_file` removes any existing destination entry (a symlink is removed, not followed) and creates the file with `create_new`. The token and extension in derived filenames are limited to `[A-Za-z0-9_-]`. ## Checks - Run: `cargo test -p artcraft_client download_media_file` (4 passed, incl. a traversal-token case); `cargo test -p support-tool download_dir_tests` (1 passed: 0700 accepted, 0777 and a symlinked dir rejected). |
||
|
|
4769597d86 |
fix: keep PMX companion files inside their asset directory (#304)
## What was wrong The PMX importer strips a common parent directory from ZIP member names to build storage paths for companion files. `enclosed_name` can still hold inner `..` (for example `a/../b`), so stripping `a` produced `../b`. The bucket client's URL normalization resolves that, so a companion file could be written outside the generated asset directory and overwrite other objects. ## What changed The stripped name is kept only if every component is a plain name (`Component::Normal`). Otherwise the entry falls back to its original enclosed name, which stays inside the asset directory. ## Blast radius Normal archives are unaffected; only names that would gain a leading `..` after stripping change. ## Checks - Run: `SQLX_OFFLINE=true cargo check -p storyteller-web` (exit 0). - Not run: the PMX upload test (needs a live MySQL and bucket). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * PMX uploads now retain the original enclosed name when a safe relative path cannot be derived, avoiding unexpected name changes. When a common parent can be safely removed, the resulting relative path is used. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
352f19e0cd |
fix(vorbis): bound VQ lookup table size in codebook setup parsing (#278)
## What was wrong `VorbisCodebook::read` in the vendored `symphonia-codec-vorbis` crate reads `codebook_entries` (24 bits) and `codebook_dimensions` (16 bits) from the untrusted Vorbis setup header and then allocates `entries * dimensions` `f32`s for the VQ lookup table with no bound. A ~30 byte header in an Ogg/WebM upload could request gigabytes of zeroed memory inside the media-processing worker. For lookup type 2 the product also overflowed `u32`, and `lookup1_values` panicked on `pow` overflow for large dimensions (e.g. 2 entries x 65535 dimensions) even when the table was small. ## What changed - `MAX_VQ_LOOKUP_LEN` (1 << 20 values, 4 MiB) declared next to the parser; codebooks over the budget are rejected with a decode error before any allocation. - Zero dimensions with a VQ lookup are rejected (`lookup1_values` is undefined for them). - `lookup1_values` sanity asserts use `checked_pow`, so large dimensions no longer panic. - Tests: hostile headers (64 x 65535 for lookup types 1 and 2, zero dimensions) are rejected; an in-budget 2 x 65535 codebook parses without panicking. ## Blast radius Only Vorbis decoding via the vendored crate (`crates/lib/files/media`). Real-world codebooks are a few thousand values, far below the limit. ## Checks run - `cargo test -p symphonia-codec-vorbis` (7 passed) - `rustfmt --check` on the changed hunks with Symphonia's own `rustfmt.toml` ## Checks not run - `cargo clippy -D warnings` on the crate fails on pre-existing deprecations in `symphonia-core`; no new warnings in the changed file. - Media/auth integration tests (need live MySQL). |
||
|
|
b948ad4674 |
fix: strip script URL schemes from markdown links; crop before exact-fit resize (#329)
What was wrong: - simple_markdown_to_html escaped literal HTML but let pulldown-cmark emit links/images with executable URL schemes (`[x](javascript:...)`, `data:`, `vbscript:`). - resize_preserving_aspect(exact_fit=true) used resize_to_fill, which scales the entire source to cover the target before cropping; an extreme-aspect source needed a huge intermediate buffer. Change: link and image destinations whose scheme is not http, https or mailto are replaced with `#` (scheme-less relative/anchor URLs pass; control characters and whitespace inside the scheme are ignored when classifying, as browsers do). Exact-fit now crops the source to the target aspect ratio first and then resize_exact's the crop, so the working size is bounded by the target. Blast radius: crates/lib/markdown (simple_markdown_to_html only) and crates/lib/files/images. Behavior changes: links with other schemes (ftp:, tel:, etc.) render as `#`. Exact-fit output has the same dimensions as before; crop offsets can differ by a pixel from resize_to_fill's rounding. Checks run: cargo test -p markdown (36 pass, 2 new); cargo test -p images --lib resize (8 pass, 1 new with a 4000x1 source). Checks not run: fmt/clippy; the ml background-removal resize finding (separate caller bounds) is not addressed here. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Image resizing with exact dimensions now preserves the requested aspect ratio by cropping the image before resizing. Very thin images are also handled reliably. * Markdown links and images now reject unsafe URL schemes, while standard web and email links continue to work. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
3c02b4c569 |
fix: honor can_see_deleted in the legacy TTS info loader and cache key; audit feature-flag edits atomically (#328)
What was wrong:
- get_tts_model_info_migration's legacy-table branch passed
can_see_deleted = true regardless of the caller, so the handler's "only
moderators see deleted models" decision was bypassed.
- The same handler cached the result in Redis under a key containing
only the model token, so a record loaded for a moderator (deleted
visible) was served to everyone for the cache lifetime.
- set_user_feature_flags committed the flag UPDATE first and then ran
the audit insert fail-open; an audit failure (e.g. an oversized
forwarded IP) left an unaudited moderator change.
Change: the legacy branch uses the caller's can_see_deleted;
get_tts_model_for_info_migration_endpoint takes can_see_deleted and adds
it to the key ("get_tts_inf1:<token>:del|pub"); set_user_feature_flags
runs the UPDATE and audit insert in one transaction and fails (rolls
back) if the audit insert fails.
Blast radius: migration crate loader, redis key helper (one caller),
storyteller_web get_tts_model handler, one users update query (two
callers: moderator handler and a test).
Behavior changes: deleted legacy TTS models are no longer returned to
non-moderators; old cache entries under the previous key are simply not
read again; a moderator feature-flag edit now fails if its audit row
cannot be written.
Checks run: cargo check -p storyteller-web (SQLX_OFFLINE=true).
Checks not run: handler/DB tests (need MySQL), fmt/clippy.
|
||
|
|
2dee0ea494 |
fix: bound openart upload and GPT-SoVITS zip reads; escape control characters in video-info-parser (#325)
What was wrong: - openart upload_image_from_file_request read the given path to EOF into a growable Vec: a device/FIFO path or huge file allocates without bound. - extract_and_upload_gpt_sovits_package decompressed every selected ZIP entry fully into memory; a small archive can expand enormously. - video-info-parser printed embedded metadata and filenames raw, so control characters (ESC sequences, CR) could rewrite the terminal report. Change: openart requires a regular file and reads at most 256 MiB (+1 byte to detect excess), erroring otherwise. GPT-SoVITS entries are read through Read::take with a 2 GiB cap per entry and fail extraction when exceeded. video-info-parser escapes control characters in every value it prints (new unit test). Blast radius: openart_client, inference-job (one function), video_info CLI binary. Behavior changes: files over 256 MiB / non-regular paths are rejected by the openart upload; GPT-SoVITS entries over 2 GiB fail extraction. Both limits are well above normal content (images; model checkpoints). Checks run: cargo check -p openart_client -p inference-job; cargo test -p video_info --bin video-info-parser. Checks not run: fmt/clippy, tests of the openart and zip limits (no test fixture added; limits are constants). |
||
|
|
ee86a8bec6 |
fix: resume the C2PA description scan after each value (#311)
## What was wrong `veo_info` and `sora_info` each had a `find_description_containing` that, after reading the CBOR text following a `description` key, resumed searching just past the *key*, not past the value. A `description` key planted inside a value was then re-read as another field. With nested values near the 2-byte length limit, an uploaded file made the scanner copy and search far more bytes than it contained, synchronously on the request worker of the video-info endpoints. ## What changed The two identical copies are replaced by one `scan::find_cbor_description_containing`, which resumes after the end of each value it reads (a new `read_cbor_text_with_end` reports where the value ends). Each byte is examined about once. Both parsers call the shared helper. ## Checks - Run: `cargo test -p video_info scan` (5 passed). New tests: a planted inner key whose value would reach into bytes after the outer value is no longer reinterpreted; a deeply nested hostile input close to the 2-byte length limit returns quickly. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Improved detection of generation and SynthID descriptions in video metadata. The app can now find relevant descriptions among multiple entries, including when earlier entries contain unrelated text or metadata is deeply nested. This helps prevent creation details from being missed when reading video information. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
b4930538db |
fix: fully redact short API keys and keep test fixture cache private (#313)
## What was wrong - `ArtcraftApiKey::redacted()` printed the first 20 characters of the key, so any key of 20 characters or fewer was printed in full by `Display`/`Debug`. - The video-generation test fixture server cached ffmpeg output in a predictable shared `/tmp/artcraft_mysql_testing_fixture_videos` directory and read back whatever was there, so a local user could plant a symlink and have the listener serve an arbitrary file. A request line also chose the ffmpeg duration with no bound. ## What changed - Keys of 40 characters or fewer now redact to just `…`; longer keys behave as before (20-char prefix). - The fixture cache is a per-process private `tempfile::TempDir`; requested fixture durations above 60 s are treated as not found. ## Blast radius / behavior changes Log output for short keys only. Test-only code otherwise (real keys are 50+ chars, so production output is unchanged). Fixture videos are regenerated once per test process instead of being shared across runs. ## Checks - run: `cargo test -p artcraft_api_keys` (13 pass), `cargo check -p storyteller-web --tests` - not run: storyteller_web DB tests (need MySQL); `cargo clippy -D warnings` (fails on unmodified main in `enums`, `deprecated_semver`); repo is not rustfmt-clean so fmt --check is not meaningful. Findings: ef2d014d, 35e48758, f9bab330 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Short API keys are now fully hidden when displayed; longer keys reveal only a limited prefix. * Fixture video requests now reject durations over 60 seconds. Fixture videos are generated in a temporary location and cached in memory; normal video generation is unaffected. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
91278b06c5 |
fix: escape untrusted values written to text logs (#315)
## What was wrong
Untrusted strings (stored-media task ids, character names/descriptions,
URLs, alert summaries, analytics tokens, referral URLs, webhook bodies
and request ids, bucket object names, ffmpeg stderr that echoes
uploaded-file metadata) were written into the line-oriented text log
with `{}`. The logger writes them verbatim, so embedded `\n`/`\r` can
forge extra log records (CWE-117).
## What changed
Those log calls now use `{:?}` (escaped Debug formatting), the same fix
suggested by each finding. In `ffmpeg_trim_and_resample` the raw
`stdout`/`stderr` passthrough on failure is replaced by one escaped
`error!` of the last 4096 chars of stderr.
## Behavior changes
Log text only: the affected values now appear quoted with control
characters escaped. No functional change.
## Not addressed (needs owner)
The two DoS findings on the same ffmpeg function (resampling a sparse
long timeline before a duration check) and the X-Forwarded-For
access-log format are left open.
## Checks
- run: `cargo check` of all touched crates and `storyteller-web --tests`
- not run: tests (no behavior change); clippy -D warnings (fails on
unmodified main in `enums`)
Findings: 3e12b40f c10eca2b 5b5d3ef0 a854bbdb 1bc24295 688c3caa 7d8c80ec
420d5274 f1ef31ed 6c85d749 a09f0426 337212ea c9ed7098 18c19719 6c507d8b
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Failure details from media processing are now recorded in application
logs without forwarding captured process output to the console.
* **Chores**
* Diagnostic messages across uploads, requests, alerts, analytics,
referrals, and webhooks now display values consistently, making unusual
characters and surrounding whitespace easier to distinguish. Request
handling, validation, and upload behavior remain unchanged.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
96f9e469ee |
fix: record metrics counter add() amounts as one sample (#321)
What was wrong: MetricsCollector::add(n) queued n separate samples, so a large u64 (e.g. derived from request data) pinned the caller in a loop and exhausted memory. Change: CounterSample gets a count field; add() pushes one sample carrying the amount and the worker sums counts. Datadog output is unchanged. Blast radius: crates/lib/metrics only (CounterSample is not used elsewhere). Behavior changes: none for existing callers. Checks run: cargo test -p metrics --lib (new tests: one sample for u64::MAX, summing in worker). Checks not run: workspace build. cargo fmt/clippy -D warnings already fail on untouched lines of this crate on main. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Counter metrics now retain and aggregate the full amount added, including very large values, rather than treating each recorded sample as a single increment. * Adding zero or recording metrics while collection is disabled continues to produce no counter sample. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
5f63f94432 |
fix(agent-notify): require POST and reject cross-site requests on playback routes (#280)
## What was wrong `agent-notify-server` is a local HTTP listener (127.0.0.1:43110) that plays the agent's alert sounds. Every playback mutation (`/alert_*`, `/loop_*`, `/stop`) was an unauthenticated GET, so any web page open in the developer's browser could stop or replace the alert loop with an `<img src="http://127.0.0.1:43110/stop">` or a redirect (CSRF against the local listener). ## What changed - Playback routes are `POST` only; `GET` returns 404. Navigation, images and redirects can no longer trigger them. - A route guard (`not_cross_site`) rejects requests a browser sends on behalf of another site: any `Origin` header, or `Sec-Fetch-Site: cross-site` / `same-site` (cross-site form POSTs carry both). curl, the agent script, and typing the URL into the address bar (`Sec-Fetch-Site: none`) still work. - README, the `/` index page and the `agent_notify.sh` helper updated (`curl -X POST`). - Test: POST without browser headers is 200; GET is 404; POST with `Origin` + `Sec-Fetch-Site: cross-site`, or `same-site`, is 404. Not added: a per-instance secret token. POST + fetch-metadata already stops browser-originated requests, and a token would need to be plumbed into the shell hook for a localhost dev tool. ## Blast radius Anyone using `~/.claude/agent_notify.sh` must take the updated script (the `-X POST` line); the old script's GETs will 404. ## Checks run - The guard and its test compile and pass against `actix-web 4.13.0` in an isolated crate (`cargo test`, 1 passed). ## Checks not run - `cargo test -p agent-notify-server` in the workspace: the crate's `rodio` dependency needs the ALSA headers (`alsa-sys` build script fails with `alsa.pc` not found) on this machine, so `main.rs` was not compiled here. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Updates** * Alert, loop, and stop playback requests now use POST instead of GET. * Playback endpoints reject requests identified as cross-site by browser request headers. The status and home pages remain accessible via GET. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
686fff83a8 |
fix: let uploads use the account's preferred visibility unless one is chosen (#275)
## What was wrong Every `MediaUploadApi` upload method (`UploadImage`, `UploadAudio`, `UploadNewEngineAsset`, `UploadSpzFile`, `UploadNewScene`, `UploadNewVideo`, `UploadPmx`) defaulted `maybe_visibility` to `Visibility.Public` and sent it in the form. The upload handlers only fall back to the account's preferred visibility when the field is absent, so this client default overrode a private/hidden preference whenever a caller didn't pass a choice. Affected paths include frame-extractor saves, 3D model / splat uploads from the upload modal, and their thumbnails, which then showed up in public listings. Separately, the video editor's automatic project cover (`thumbnail-capture.ts`) uploaded a render of the timeline through `UploadImage` with no visibility, so a private project got a public cover image. ## What changed - `MediaUploadApi`: removed the `= Visibility.Public` defaults. The field is sent only when the caller chooses a value; otherwise the server applies the account preference (unchanged server logic). - `thumbnail-capture.ts`: reads the project's `creator_set_visibility` and uploads the cover with the same visibility; if it can't be read, the cover is private. - `Visibility` is now exported from `@storyteller/api` so the webapp can pass it. ## Blast radius Uploads from callers that don't choose a visibility now follow the account's preferred visibility instead of always being public. Accounts with no preference get the server default, as before. Explicit choices are unchanged. Existing covers are not updated, and changing a project's visibility later does not update its cover. ## Checks run - `npx vitest run src/lib/MediaUploadApi.spec.ts` in `libs/api`: 8/8 pass (7 fail on `main`). - `npx vitest run src/pages/video-editor/adapters/thumbnail-capture.spec.ts` in `apps/artcraft-webapp`: 2/2. - `tsc -p tsconfig.lib.json` / `tsconfig.spec.json` for `libs/api` and `tsc -p tsconfig.app.json` for the webapp: no errors in touched files (existing errors elsewhere are unchanged). ## Checks not run - Uploads against a running API with a private preferred visibility. - Propagating visibility changes to existing covers (needs a server-side change). Addresses CodeRabbit security findings (CWE-200). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Media uploads without an explicitly selected visibility now use the account’s preferred visibility. * **Bug Fixes** * Video cover uploads now retain a project’s public or hidden visibility. If visibility is missing or unrecognized, the cover is uploaded as private. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
62e673d95b |
fix: bind loaded video projects to their storage id (#238)
## What was wrong When the video editor opened a project, `ProjectManager` copied the document's embedded `project.metadata.id` into the active project. Every later save (`saveCurrentProject`, background rename) passed that id to `ProjectStorageAdapter.saveProject`, and the webapp adapter uses it as the `UpdateProject` target token. The document body is user-authored, so a crafted project could embed the token of another timeline the viewer owns, and opening it would make the viewer's autosave overwrite that timeline. ## What changed - New `deserializeStoredProject(envelope)` in `services/storage/serialization.ts`: deserializes the document and replaces `metadata.id` with the id the storage adapter loaded it under. - `ProjectManager.loadProject`, `openProject` and `renameProject` (background path) use it. - Regression test in `serialization.spec.ts`. ## Blast radius Video editor library (webapp and any host using it). Saves now always target the project that was opened. Legacy documents whose embedded id was a stale `local-*` id are now bound to their real token on open, which also stops them being re-created as new rows. Addresses CodeRabbit security findings (CWE-441). ## Checks run - `npx vitest run src/lib/services/storage src/lib/core` in `libs/components/video-editor`: 13/13 pass. - `npx tsc -p tsconfig.lib.json --noEmit` in `libs/components/video-editor`: clean. ## Checks not run - Manual editor test against the live API. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Projects now retain their storage ID when loaded or opened, even if the ID saved inside the project differs. * Saving an opened project preserves its storage ID, and renaming a background project updates the correct entry without activating it. * Missing or invalid stored projects are handled without returning a project, helping prevent unavailable project data from being treated as a loaded project. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
209e680a19 |
fix: read saved character poses as bone transforms only (#244)
## What was wrong `BoneJSONHelper.poseFromBoneJSON` (3D editor, `libs/components/pagescene`) passed a scene document's `rigData` straight to three.js `ObjectLoader.parse`. `ObjectLoader` builds every section of the document (geometries, materials, textures, images) before returning the object tree, so a scene whose `rigData` contained e.g. a `SphereGeometry` with huge segment counts forced large synchronous allocations on whoever opened it. Only the bone transforms were ever used. ## What changed - New `parseBonePose()` reads only the bone-transform subset of the `Object3D.toJSON()` document: each node's local `matrix` (or `position`/`quaternion`/`scale` fallback), all finite numbers, and child order. Other sections are ignored. - Node count (`MAX_POSE_BONES = 1024`) and depth (`MAX_POSE_DEPTH = 128`) are capped. - `poseFromBoneJSON` uses it instead of `ObjectLoader`; malformed `rigData` is now skipped instead of throwing. - New `BoneJSONHelper.spec.ts`: pose round-trip through `toJSON`, a hostile document with a procedural geometry section, width/depth caps. ## Blast radius Character pose restore when loading 3D scenes. Poses saved by the current `toJSON` path apply exactly as before (same matrix decomposition `ObjectLoader` used). Addresses CodeRabbit security findings (CWE-400). ## Checks run - `npx vitest run src/lib/engine/KinHelpers` in `libs/components/pagescene`: 4/4 pass. - `npx tsc -p tsconfig.lib.json --noEmit`: same 20 pre-existing errors as `main`, none in touched files. ## Checks not run - Manual load of a saved scene with a posed character. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Pose restoration ignores non-bone scene data and leaves the current pose unchanged when the document has no usable object root. * Bone transforms can be restored from a matrix or separate position, rotation, and scale values; unusable values fall back to identity transforms. * Unreadable child entries retain their positions, while poses exceeding parsing limits are not applied. * **Tests** * Added coverage for pose restoration, non-bone data, parsing limits, invalid entries, and unusable roots. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
c281dd320c |
fix: make keyframe listing and composite updates linear (#252)
## What was wrong Two quadratic paths in the video editor's animation code (`libs/components/video-editor/src/lib/animation`), both driven by a project document's animation data: - `getElementKeyframes` (`keyframe-query.ts`) evaluated each listed keyframe with `getChannelValueAtTime`, which copies, normalizes and sorts the whole channel on every call, then scans it from the start. Listing a channel with n keys was O(n^2 log n). With the original code, a 20,000-key channel took about 230 s on the main thread. - `removeElementKeyframe`, `retimeElementKeyframe` and `splitAnimationsAtTime` (`keyframes.ts`) rebuilt a composite property by calling `setChannelInData` once per component. Each call spreads and counts the whole component record, so the cost was quadratic in the number of stored components. ## What changed - `interpolation.ts`: new `getNormalizedScalarChannelValueAtTime` / `getNormalizedDiscreteChannelValueAtTime` evaluate an already-normalized channel. The scalar path starts at the binary-searched segment and the discrete path uses an search on the scan's own predicate (`!(time < key.time)`), so results match the old scan for every query time, NaN included. The existing `get*ChannelValueAtTime` functions now normalize, then delegate. - `keyframe-query.ts`: `createChannelEvaluator` / `createComposedValueEvaluator` normalize each channel once per property, replicating `getChannelValue`'s fallback rules. `getElementKeyframes`, `getKeyframeAtTime` and `getKeyframeById` use them. - `keyframes.ts`: `setChannelsInData` applies a batch of component updates to one record copy. It gives the same result as chaining `setChannelInData`, including leaf/`value` handling and no-op on empty updates. The remove, retime and split loops use it. - New `__tests__/keyframe-scaling.spec.ts`: listed values match direct evaluation for scalar, RGBA and discrete channels; a 20k-key channel lists quickly; remove/retime across 2,000 components is correct. The equivalence tests also pass against the old code, and the 20k-key test fails on it (232 s). ## Blast radius Keyframe listing, keyframe lookup and composite keyframe edits in the video editor. Values and results are unchanged. Addresses CodeRabbit security findings (CWE-407). ## Checks run - `npx vitest run` in `libs/components/video-editor`: 24/24 pass. - New `__tests__/keyframe-equivalence.spec.ts` compares the new paths with the pre-change algorithms over randomized channels (duplicate times, bezier handles, extrapolation, NaN and out-of-range query times) for evaluation, listing, split, remove and retime. Its reference functions also pass against `main`'s `interpolation.ts` / `keyframe-query.ts`. - `npx tsc -p tsconfig.lib.json --noEmit` in `libs/components/video-editor`: clean. ## Checks not run - I did not add a cap on the number of animation keys or components accepted when a project loads. - Manual editor session with a large animated project. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Performance Improvements** * Animation values and keyframes are evaluated and listed more efficiently, particularly in channels with many keyframes. * Splitting, removing, and retiming keyframes across composite animations now process updates more efficiently. * **Tests** * Added coverage for animation evaluation, keyframe listing and updates, interpolation edge cases, and performance with large channels. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
1d874233c0 |
fix: apply model decode budgets in the shared-media 3D viewer (#269)
**Stacked on #248** (`fix/sec-model-decode-budget`): this uses its `modelBudget.ts` helpers. Merge #248 first, and GitHub will retarget this PR to `main`. ## What was wrong #248 added decode budgets for glTF accessors and SPZ splat counts, and applied them in PageScene and the upload preview. The shared-media viewer (`libs/components/viewer-3d/src/lib/viewer-3d.tsx`), which renders models selected through a media share token, still loaded them with no budget: - `new GLTFLoader().load(modelUrl)` reaches count-based typed-array allocation, including implicit-zero accessors with no buffer data, from a small attacker-authored document. - `new SplatMesh({ url })` lets Spark size packed SPZ storage from the header's splat count before it validates the body. ## What changed - glTF/GLB: the loader is wrapped with `applyGltfBudget`, so the parse that `load()` performs after fetching is checked against `MAX_GLTF_DECODED_BYTES` first. - SPZ: the viewer fetches the bytes itself and runs `assertSpzWithinBudget` (header splat count vs `MAX_SPZ_SPLATS`), then passes `fileBytes` to `SplatMesh`, the same pattern PageScene uses after #248. Other splat formats (`ply`, `splat`, `ksplat`) still load by URL. - Load or budget failures log and show the fallback shape, like the existing glTF error path. A load that finishes after the URL changed is still discarded. ## Blast radius Only the shared-media 3D viewer. Models within budget load as before. Over-budget models show the placeholder cube instead of exhausting memory. ## Checks run - `npx vitest run --root libs/components/viewer-3d`: 17/17 pass, including #248's `modelBudget.spec.ts`. - `npx tsc -p libs/components/viewer-3d/tsconfig.lib.json --noEmit`: the 29 errors it reports (missing `three` declarations, unbuilt `@storyteller/ui-select` dist) are the same before and after this change. This change adds none. ## Checks not run - Component-level test of the loading path. jsdom has no WebGL, so the viewer's scene effect never initializes there. - Manual load of an over-budget glTF/SPZ share link in a browser. - Not done: budgets for PLY/splat/ksplat headers and publish-time validation. Addresses CodeRabbit security findings (CWE-789). |
||
|
|
e54f4fd588 |
fix: check glTF and SPZ decode sizes before parsing models (#248)
## What was wrong - three's `GLTFLoader` allocates `new TypedArray(accessor.count * itemSize)` per accessor (zero-filled when the accessor has no `bufferView`, plus sparse arrays). A GLB of a few hundred bytes can declare accessors that request gigabytes. This reached the 3D editor's scene loader (`pagescene/src/lib/engine/scene.ts`), the upload preview (`loadPreviewOnCanvas.ts`) and the GLB animation duration reader. - Spark's SPZ reader sizes its packed splat storage from the header's splat count before reading the body, so a small gzip file with a huge count did the same in the scene loader and the upload preview. ## What changed New `libs/components/viewer-3d/src/lib/modelBudget.ts` (exported from `@storyteller/ui-viewer-3d`, already a dependency of both libs): - `gltfDecodedAccessorBytes` / `assertGltfWithinBudget`: read only the glTF JSON (GLB JSON chunk or `.gltf` text), sum accessor + sparse storage, reject invalid counts and totals above `MAX_GLTF_DECODED_BYTES` (1 GiB). - `applyGltfBudget(loader)`: wraps a `GLTFLoader` instance's `parse` (which `load()` also goes through) so over-budget files go to `onError` without being parsed. - `assertSpzWithinBudget`: inflates only the 16-byte SPZ header (pull-based `DecompressionStream`) and rejects counts above `MAX_SPZ_SPLATS` (10M). Spark reads exactly the header-declared amount of data, so this bounds the decode. Non-gzip/non-SPZ data is left for the decoder. - Applied in `scene.ts` (GLB and splat loaders), `loadPreviewOnCanvas.ts` (GLB and SPZ preview) and `readGlbAnimationDuration.ts`. - Tests in `modelBudget.spec.ts`: compact hostile GLB, sparse accounting, invalid counts, loader wrapper, hostile and normal SPZ headers. ## Blast radius Model loading in the 3D editor and upload modal. Models whose accessors decode to more than 1 GiB, or SPZ splats with more than 10M points, are now rejected with an error instead of loaded. Both limits sit well above the assets we produce, but they are a behavior change for very large files. Addresses CodeRabbit security findings (CWE-789). ## Checks run - `npx vitest run src/lib` in `libs/components/viewer-3d`: 17/17 pass. - `npx vitest run src/lib/UploadModal3D` in `libs/components/upload-modal`: pass (spec mock gained a `parse` stub). - `npx vitest run` in `libs/components/pagescene`: 16/16 pass. - `npx tsc -p tsconfig.lib.json --noEmit` for viewer-3d, upload-modal, pagescene: error counts identical to `main` (pre-existing; `three` typings are not installed in this checkout), none in new code. ## Checks not run - Loading real large GLB/SPZ assets in a browser. - FBX decompression limits (separate PR). |
||
|
|
8c7500f95e |
fix: bound FBX array decompression before converting uploads (#251)
## What was wrong
The 3D uploader converts FBX to GLB with three's `FBXLoader`
(`convertFbxToGlb.worker.ts`, with a main-thread fallback in
`convertFbxToGlb.ts`). `FBXLoader` inflates every compressed array
property with `fflate.unzlibSync`, which has no output limit. A small,
highly compressible FBX could expand to gigabytes and take down the
worker; the worker's `onerror` then retried the same file, unbounded, on
the main thread.
## What changed
- New `fbxBudget.ts` with `assertFbxWithinBudget(buffer)`:
- walks the binary FBX node tree the same way `FBXLoader`'s
`BinaryParser` does (32- and 64-bit offsets, node depth capped at 256);
- caps the total declared array storage at `MAX_FBX_ARRAY_BYTES` (512
MiB);
- inflates each compressed array through
`DecompressionStream("deflate")`, fed in 16 KiB slices and discarding
output, and cancels as soon as it produces more than the array's
declared size.
- ASCII FBX and structurally odd files are left for `FBXLoader` to
handle.
- Both the worker and the main-thread fallback call it before
`FBXLoader.parse`.
- `fbxBudget.spec.ts`: a matching compressed array passes, a 16 MiB
zero-bomb declared as 4 floats is rejected, an over-budget declaration
is rejected, ASCII passes.
## Blast radius
FBX upload conversion. Valid files cost one extra streaming inflate
pass. Files whose arrays declare more than 512 MiB are rejected.
Addresses CodeRabbit security findings (CWE-409).
## Checks run
- `npx vitest run src/lib/UploadModal3D` in
`libs/components/upload-modal`: 8/8 pass.
- Ran the check against the three binary FBX files in
`old_assets/resources/models/Bot_F/`: all pass at the default budget,
and lowering the budget shows the walker reaches their arrays (>1 MB of
declared arrays found).
- `npx tsc -p tsconfig.lib.json --noEmit`: same error count as `main`
(pre-existing; `three` typings are not installed in this checkout).
## Checks not run
- End-to-end upload of an FBX in the browser (worker path).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* FBX uploads are checked before conversion. Binary files with declared
arrays exceeding the 512 MiB limit, or compressed arrays that expand
beyond their declared size, are rejected.
* These checks apply whether conversion runs in a worker or on the main
thread.
* ASCII FBX files and binary files without oversized arrays continue
through the existing conversion flow.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
7f8e2be29d |
fix(moodboard): keep owner-stamped boards from being pushed or deleted by other sessions (#293)
## What was wrong Board replicas live in machine-shared `localStorage` and are stamped with the owning account's `ownerId`. `saveBoard` already refused to push a board owned by a different account, but: - **Edits by other sessions became the owner's pushes.** A signed-out visitor or another account could edit a cached owner-stamped board. `markBoardDirty` recorded a durable `needsSync`, and the owner's next session uploaded those changes as its own. - **Remote deletes had no owner check.** `deleteBoardEverywhere` queued a tombstone for any board with a `remoteToken`. Those tombstones were later retried with the owner's credentials, soft-deleting the owner's project. - **The account could change mid-flush.** `flush` captured `userId` once, then awaited several saves, so a session change during the flush could upload a board with the new account's credentials. ## What changed - New `isOwnedByCurrentAccount(board, userId)`: unstamped local boards are open to anyone; owner-stamped boards only to that account. - `markBoardDirty` does not record pending pushes for boards the live account doesn't own. - `deleteBoardEverywhere` only tombstones and deletes remotely when the live account owns the board; otherwise it just drops the local replica. - `flush` re-reads `persistence.getUserId()` before every save and keeps the board dirty if the account changed. - Test: `moodboardSync.spec.ts` covers the ownership rule. Not done: making owner-stamped boards read-only in the UI for other sessions. Their edits now stay local and are never uploaded. ## Blast radius Moodboard sync only. The owner's own edits, saves and deletes are unchanged. ## Checks run - `vitest run src/lib/persistence` in `libs/components/moodboard`: 7/7 pass. - `tsc -p libs/components/moodboard/tsconfig.lib.json`: no new errors compared with `main`. ## Checks not run - Two-account manual test in a browser. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Moodboard changes are now synced only when the board is unowned or belongs to the current account. * Queued saves are paused for retry if the active account changes during a sync. * Deleting a board still removes it locally, but remote deletion is limited to boards owned by the current account. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
899936d945 |
fix(webapp): drop account-scoped caches when the signed-in identity changes (#294)
## What was wrong Several webapp caches held one account's data in account-independent browser state and survived logout, or a login as someone else in the same tab or browser profile: - `create-video-store` (persisted in localStorage): prompt draft, settings and pending batches restored into the form. - `library-folders-store` / `library-tags-store` (module singletons): folder media, tag names and use counts, with `*Loaded` flags that suppressed a refetch. - `scene-cache-store` (sessionStorage): serialized scenes and the last-scene link, restored before the server load. - `@storyteller/ui-vfx` store (persisted): prompts and generation history. - `useAnimationLibrary` (module store): the user's private animation list. - `gallery-modal`: on an identity change it cleared only root items, and on logout it kept everything. ## What changed - `lib/session.ts`: `reconcileAccountOwner` records which account last filled this browser (`artcraft-webapp-session-owner`). When a confirmed session answer names a different identity (logout, or another user), it runs the clearers registered with `onAccountChange`. A failed or timed-out session check does not trigger it, so an outage never wipes a draft. The first run only records the current identity. - `lib/account-caches.ts` (imported from `main.tsx`) registers one clearer per cache. Each store gets a `resetAccountState()` (VFX reuses its existing `reset()`), the gallery uses the existing `clearGalleryCache()`, and pagescene exports a new `clearAnimationLibraryAccountState()`. - `gallery-modal`: on logout or a different user it now also clears folders, folder and tag media, tags and the bulk selection. - Test: `session.spec.ts` covers when the clearers fire. ## Blast radius A user who logs out, or switches accounts, loses their unsent video draft and cached library state (as intended). Same-account reloads are unaffected. ## Checks run - `vitest run src/lib/session.spec.ts` in `apps/artcraft-webapp`: 1/1 pass. - `tsc` for `apps/artcraft-webapp` and `libs/components/gallery-modal`: no new errors compared with `main`. ## Checks not run - Manual logout/login walkthrough in a browser. - The desktop (Tauri) host does not use `lib/session.ts`, so it is not covered by this change. |
||
|
|
63059c2475 |
fix: keep the session until logout is confirmed by the server (#273)
## What was wrong - `UsersApi.Logout` in `@storyteller/api` cleared the stored signed session *before* sending `POST /v1/logout`. That stored value is what `buildSessionHeaders` sends as the `session` header when third-party cookies are blocked, so in the cookie-free flow the logout request carried no credential: the server could not find the session to revoke, yet the client went on as if logged out. The copied session stayed valid. - The moderator dashboard's `NavUser.handleLogout` ignored the `Logout` result and always called `logoutState()`, so a failed request showed the login page while the session cookie still worked. ## What changed - `UsersApi.Logout` sends the request first and clears the stored session in `.finally()`, so the local credential is still removed whatever the outcome. It also passes the server's `error_message` through. - The dashboard only clears its auth state when logout succeeds. On failure it shows a toast saying the session is still active, with a Retry action. ## Blast radius - All `@storyteller/api` `Logout()` callers (webapp top bar, pagescene adapter, genhub): the request now carries the session header; local clearing is unchanged apart from happening after the response. - Dashboard: on a failed logout the moderator stays signed in and sees an error, instead of a misleading login page. ## Checks run - `npx vitest run src/lib/UsersApi.spec.ts` in `libs/api`: 2/2 pass; the header test fails on `main`. (The spec stubs `localStorage` because Node 26 shadows jsdom's; the existing `MediaFilesApi.spec.ts` fails here for that reason.) - Dashboard: `pnpm install --frozen-lockfile`, `tsc -p tsconfig.app.json --noEmit` clean, `eslint src/components/nav-user.tsx` clean. ## Checks not run - Logout against a running API in cookie-free (header) mode. - Manual dashboard logout with the API unreachable. Addresses CodeRabbit security findings (CWE-613). |
||
|
|
0e13ad0b10 |
fix(scripts): revoke every source session when copying account credentials (#274)
## What was wrong `script/database/copy_user_account.py` moves an account's email and password onto another account and says it ends the source account's sessions. The revocation `UPDATE` had `LIMIT 10` and also matched sessions that were already deleted. If the source account had more than ten session rows, some live sessions could survive the transfer and keep working, because session lookups accept any row with `deleted_at IS NULL` and `expires_at > NOW()`. ## What changed - The revocation `UPDATE` has no row limit and only targets live sessions (`deleted_at IS NULL`), so the timestamps on rows that were already deleted stay as they were. - After the update, the script counts the source's remaining live sessions inside the same transaction. If any are left, it raises, and the existing handler rolls back. - The confirmation preview counts live sessions, and the docstring lists the revocation step. ## Blast radius This only affects the oncall script that an operator runs by hand. No service code changed. Session lookups do not use a cache (`crates/lib/actix_artcraft/src/sessions` reads MySQL directly), so nothing else needs invalidating. ## Checks - Run: `python3 -m py_compile script/database/copy_user_account.py` - Not run: running the script against a database (it needs a live MySQL and secrets.toml). Addresses CodeRabbit security findings (CWE-613). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Account-copy operations now stop and roll back if any live source sessions remain, rather than committing an incomplete transfer. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
90f6e08972 |
ci: don't require portable, web, or FreeBSD assets from ArtCraft Studio releases (#371)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Chores** * Release checks no longer require portable ZIP, web, or FreeBSD builds. The setup EXE and universal DMG remain required, along with the other previously required release assets. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
5282911e4e |
fix: serve dev CDN proxy responses as inert downloads (#239)
## What was wrong The webapp's dev-only `/__cdn/<host>/<path>` middleware (`apps/artcraft-webapp/vite.config.ts`) fetches any HTTPS host named in the path and returns the upstream bytes with the upstream `Content-Type` from the app's own origin. A link to `/__cdn/attacker.example/page.html` would render the attacker's HTML (or SVG) as a same-origin document on the dev server, with script access to the app's storage and any signed session kept there. ## What changed - Proxied responses now always carry `Content-Security-Policy: sandbox; default-src 'none'`, `X-Content-Type-Options: nosniff` and `Content-Disposition: attachment`, so a navigated-to response cannot run as a document on the app origin. `fetch()` and `<img>` loads (the only callers, via `maybeProxyCdnUrl` in `pagescene/web-adapter.tsx`) ignore these headers. - The host segment must be a bare hostname (no `user@` or `:port`). ## Blast radius Local dev server only; production builds do not include this middleware. Addresses CodeRabbit security findings (CWE-79). ## Checks run - Started `vite` for the webapp and probed the proxy with curl: `/__cdn/example.com/` returns 200 with the new headers; `/__cdn/user@example.com/` and `/__cdn/example.com:8443/` return 400. ## Checks not run - Loading a real scene with CDN splats/GLBs through the dev proxy in a browser. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Security** * The `/__cdn` proxy now rejects invalid host values and adds protective response headers to proxied content. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
64750ea5a2 |
fix: escape raw HTML and script URLs in the markdown renderer (#272)
## What was wrong The help menu (`libs/components/help-menu`) fetches `news.json` from the website at runtime and renders each article with `markdownToHtml` into `dangerouslySetInnerHTML`. `markdownToHtml` copied the source text into its output unescaped, so any raw HTML in an article body (`<img onerror=...>`, `<script>`, `<svg onload=...>`) went straight into the app's DOM, including the desktop webview. Link and media targets were also unchecked, so `[x](javascript:...)` produced a script URL, and a `"` in a URL, alt text or `@image` size broke out of the attribute. ## What changed - `markdownToHtml` now HTML-escapes every input line before applying markdown syntax (blockquote `>` is matched first, then its content is escaped). The only tags in the output are the ones the renderer builds. - New `safeUrl`: link, image and video targets must be relative or `http`/`https`/`mailto`; anything else becomes `#`. - `@image` / `` sizes must be `N`, `Npx`, `N%` or `WxH`; other values are ignored since they go into a `style` attribute. ## Blast radius Every caller of `markdownToHtml` from `@storyteller/markdown-content`: the help menu and the library's own `NewsPost` page. The bundled news/FAQ/tutorial markdown uses no raw HTML or non-http links, so its rendering is unchanged (apostrophes and quotes now render via entities). The website's separate copy in `apps/artcraft-website-next/src/lib/markdown.ts` is not touched. ## Checks run - `npx vitest run src/lib/utils/markdown.spec.ts` in `libs/markdown-content`: 6/6 pass; 4 of them fail on `main`. - `tsc -p tsconfig.lib.json` / `tsconfig.spec.json`: no errors in touched files (existing TS6305 unbuilt-reference errors are unrelated). ## Checks not run - Opening the help menu news view in the desktop app or webapp. Addresses CodeRabbit security findings (CWE-79). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Markdown content now displays embedded HTML as text and blocks unsafe link destinations, reducing the risk of unwanted markup or navigation. * Safe relative, web, and email links continue to work. Image sizing now accepts only valid values, and malformed sizes are rejected. * **Tests** * Added coverage for supported Markdown, safe URL handling, embedded HTML, and crafted links, images, and media. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
25b40e0efb |
fix(pagedraw): bound imported line points, data-URL parsing and 3D render size (#295)
## What was wrong
`importSceneFromJson` in `libs/components/pagedraw` handed untrusted
scene JSON straight to the renderer:
- Drawing and mask line `points` weren't checked to be an array. Konva's
spline expansion loops over the declared `length`, so `{ "length": 1e9
}` blocked the UI thread.
- `base64ToFile` parsed the data-URL header with `/:(.*?);/`, which
rescans overlapping suffixes of a malformed header, giving quadratic
time on about 100 KB.
- `model3dParams.nativeWidth`/`nativeHeight` sized the WebGL framebuffer
(`renderer.setSize`) with no limit, both in the live overlay and in the
commit path that calls `toDataURL`.
## What changed
- `isValidLineNode`: `points` must be an array of finite numbers no
longer than `MAX_LINE_POINTS = 100_000`; invalid lines are dropped from
`drawNodes` and `inpaintLineNodes` on import.
- The data-URL MIME type is read with `indexOf`/`slice` (linear).
- `clampNativeSize` rounds the size and clamps it to
1..`MAX_NATIVE_DIMENSION = 4096` (non-finite values fall back), used at
both `setSize` sites.
- Test: `stores/importBounds.spec.ts` covers hostile `points` and huge,
NaN and negative sizes.
Not done: budgeting GLTF accessor counts (finding `1dc9e1f2`). That
needs a custom loader or worker and is left for a human to scope.
## Blast radius
Scene import and the 3D overlay. Valid scenes and normal sizes are
unchanged.
## Checks run
- `vitest run src/lib/stores/importBounds.spec.ts` in
`libs/components/pagedraw`: 2/2 pass.
- `tsc -p libs/components/pagedraw/tsconfig.lib.json`: the remaining
errors are the existing missing `three` type declarations.
## Checks not run
- Manually importing a scene in the editor.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Imported 3D model dimensions are now kept within supported limits,
with invalid values handled safely.
* Invalid or excessively large line data is skipped during scene import,
helping prevent malformed content from disrupting the scene.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
8fb04b39bc |
fix(dashboard): bound the Rust Debug reformatter and fix escape handling (#291)
## What was wrong
`formatRustyDebug` in
`apps/artcraft-dashboard/src/components/DebugLogCard.tsx` re-indents
Rust `Debug` strings from job logs, which include user-supplied prompt
text. It decided a quote was escaped by checking only the previous
character, so `"x\\"` (escaped backslash, then a closing quote) made it
treat the rest of the string as structure. Every misread `{`/`[` then
added indentation with no limit (output grows about quadratically),
which could hang a moderator's tab.
## What changed
- Escape sequences inside strings are consumed as a pair, so `\\` and
`\"` are read correctly.
- Budgets declared next to the formatter: input 64 KiB, depth 32, output
256 KiB. Past any of them the raw message is shown unformatted.
- `formatRustyDebug` is exported for testing.
- Test (`DebugLogCard.spec.ts`): escaped-backslash case; hostile input
with 5000 nested `[` and a 300 KB message both fall back to the raw
text.
## Blast radius
Display of debug logs in the dashboard only.
## Checks run
- `vitest run DebugLogCard.spec.ts`: 2/2 pass; the escape test fails on
the old code.
## Checks not run
- The dashboard's own vite config needs `@vitejs/plugin-react-swc` and
`@tabler/icons-react`, which aren't installed in the frontend root. The
spec was run with a minimal config that aliases `@/` and stubs the icon
package.
|
||
|
|
b7c5d0bd77 |
fix(moodboard): bound group nesting and star ratings from loaded documents (#292)
## What was wrong Moodboard documents come from storage or the server and were installed without checking their graph shape: - `GroupNode` renders every child group recursively, so a group that lists itself, an ancestor, or shared descendants rendered without bound (cycle → infinite recursion; DAG with shared children → exponential expansion). - `BoardCard` used `item.rating` directly as an array length for star icons, so a stored rating of `1e9` became a huge allocation. ## What changed - `pruneCanvasGraph` (in `persistence/documents.ts`, applied in `deserializeMoodboardDocument`) turns the loaded canvas into a bounded forest: each node keeps only its first parent, self/ancestor references are dropped, and nesting is capped at `MAX_CANVAS_NESTING_DEPTH = 16`. - `GroupNode` also gets an `ancestorIds` set and skips any child that is already an ancestor, as a guard for state that didn't come through deserialization. - `BoardCard` clamps the rating to an integer 0..5 before rendering stars. - Tests in `documents.spec.ts`: cycles, shared descendants and depth capping. ## Blast radius Loading moodboard documents. Valid documents (trees within 16 levels) come through unchanged. ## Checks run - `vitest run src/lib/persistence/documents.spec.ts` in `libs/components/moodboard`: 7/7 pass. - `tsc -p libs/components/moodboard/tsconfig.lib.json`: no new errors compared with `main`. ## Checks not run - Manually opening a malformed board in the UI. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Prevented moodboard groups from rendering recursively when they contain circular references. * Cleaned up invalid, repeated, or excessively deep canvas references when loading a moodboard, helping keep nested content stable. * Corrected rating displays so they show between zero and five stars, with no star overlay for zero or invalid ratings. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
cdd4b093ef |
fix: bound moodboard grid drawing and deletion walks on loaded documents (#270)
## What was wrong Two moodboard paths trust values from a loaded board document (`MoodboardPersistenceAdapter.loadBoard` / the local canvas cache): - `MoodboardBackground` stepped its dot loops by the document's `gridSpacing`. A zero, negative or non-finite spacing (or a pan so large that `x += step` stops changing `x`) made the loop never reach the end of the viewport and froze the tab. - `deleteSelected` walked group/card `childIds` recursively without skipping nodes it had already collected. A small graph with shared descendants costs 2^depth work; a cycle overflows the stack. ## What changed - New `canvas/layout/gridDots.ts`: `effectiveGridSpacing` returns null for non-positive or non-finite spacing/zoom, and `gridDotLayout` returns a start point plus column/row counts (null over a 20,000-dot budget or for non-finite input). The background now iterates by index. - `applyCanvasDocument` replaces a stored `gridSpacing` outside 1..4096 (or non-numeric) with the default 32. - `deleteSelected` uses an iterative walk that visits each node once. ## Blast radius Moodboard canvas only. Valid documents render and delete exactly as before (default spacing is 32 and nothing in the UI changes it). ## Checks run - `npx vitest run` for the new specs in `libs/components/moodboard` (gridDots, MoodboardStore, canvasBridge): 10/10 pass. The 64-level shared-descendant delete test hangs on `main`. - `tsc -p tsconfig.lib.json` and `tsconfig.spec.json`: no errors in touched files (the existing TS6305 unbuilt-reference errors are unrelated). ## Checks not run - Manual moodboard session in the webapp. Addresses CodeRabbit security findings (CWE-835, CWE-674). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * The moodboard grid adjusts dot spacing as you zoom, keeping it readable across different zoom levels. * **Bug Fixes** * Deleting selected items now completes reliably when nested content contains shared references or cycles. * Invalid saved grid spacing now falls back to a valid default. * Grid rendering handles invalid viewport or zoom values and unusually large layouts safely. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
a07e105735 |
fix: restore loaded scene objects by reference, not uuid search (#245)
## What was wrong `StoryTellerProxyScene.loadFromSceneJson` (3D editor, `libs/components/pagescene`) looked up every primitive with `scene.get_object_by_uuid` right after `instantiate` had returned it, then restored visibility and color through `setVisible(uuid)` / `setColor(uuid)`, which each search the whole scene again. Every search is a recursive `getObjectByProperty` over all scene objects, so a scene document with n primitives cost O(n^2) on the main thread and a large shared scene could freeze the viewer's tab. ## What changed - The loader uses the object returned by `instantiate` (Parim shapes and `Image::` planes) instead of searching for it. - `Scene.setObjectVisible(object, visible)` and `Scene.setObjectColor(object, hex)` take the object directly; `setVisible`/`setColor` look the uuid up once and delegate, so other callers are unchanged. - `setColor`'s point-light branch finds the attached light inside the marker mesh's subtree (where `instantiate` attaches it) instead of searching the scene. - Spec: restoring 50 primitives performs no scene-wide `getObjectByProperty` searches (fails on `main`), and a point-light shape still colors its light. ## Blast radius 3D scene loading and the shape color/visibility setters. Behavior is the same; only the lookup strategy changed. No object-count cap was added. Addresses CodeRabbit security findings (CWE-407). ## Checks run - `npx vitest run src/lib/proxy src/lib/engine/scene.spec.ts` in `libs/components/pagescene`: 12/12 pass. - `npx tsc -p tsconfig.lib.json --noEmit`: same 20 pre-existing errors as `main`, none introduced. ## Checks not run - Manual load of a large saved scene in the 3D editor. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Scene restoration now reliably reapplies primitive visibility and color, as well as point-light colors. * Restored objects use their instantiated references directly, avoiding UUID-based lookups. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
eab955932d |
fix(pagescene): cap recorded frame count from imported timelines (#297)
## What was wrong `recordTimeline` computed `frameCount = round(timeline.duration * fps)` straight from the loaded scene. The editor's own setter limits duration to 1..60 s, but an uploaded scene isn't held to that. A scene declaring a huge duration or fps made the recorder seek, render and encode an unbounded number of frames into an in-memory `BufferTarget`. ## What changed - `recordingFrameBudget` clamps fps to (0, 120] (non-finite or ≤0 falls back to 30) and duration to [0, 60] s before the frame count is computed. The constants are declared next to the recorder. - Test: `TimelineRecorder.spec.ts` covers normal and hostile timelines. ## Blast radius Recording only; supported timelines produce the same frame count. ## Checks run - `vitest run src/lib/engine/recording` in `libs/components/pagescene`: 2/2 pass. - `tsc -p libs/components/pagescene/tsconfig.lib.json`: 98 errors, the same count as `main` (all existing three.js typing issues). ## Checks not run - Manually recording a scene. |
||
|
|
b8ac52dc17 |
fix: bound loaded 3D timeline durations and ruler ticks (#243)
## What was wrong
In the 3D editor (`libs/components/pagescene`),
`TimelineController.setDuration` clamps interactive edits to 1-60 s, but
`loadTimeline` accepted any positive `duration` from a scene document.
`TimelineEditor` builds the ruler with `Array.from({ length: duration *
subsPerSecond + 1 })`, so a shared scene with `duration: 1e8` made the
viewer's tab allocate and render that many React elements.
## What changed
- `engine/timeline/types.ts`: `MIN_TIMELINE_DURATION` /
`MAX_TIMELINE_DURATION` and `clampTimelineDuration()` (non-numeric,
non-finite and non-positive values fall back to the default; others are
clamped).
- `TimelineController.loadTimeline` clamps the loaded duration with it
and treats non-finite fps as missing. `setDuration` uses the shared
constants (same behavior as before).
- `TimelineEditor` caps the ruler tick count independently
(`MAX_TIMELINE_DURATION + 1`).
- New `TimelineController.spec.ts` with hostile durations (1e9,
Infinity, NaN, string, negative).
## Blast radius
3D editor timeline only. Saved scenes with durations above 60 s (not
creatable through the UI) now load clamped to 60 s.
Addresses CodeRabbit security findings (CWE-770, CWE-400).
## Checks run
- `npx vitest run src/lib/engine/editor/TimelineController.spec.ts` in
`libs/components/pagescene`: 3/3 pass.
- `npx tsc -p tsconfig.lib.json --noEmit`: same 20 pre-existing errors
as `main`, none in touched files.
## Checks not run
- Manual load of a scene in the 3D editor.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Timelines now stay within the supported 1–60 second range when loaded
or edited. Invalid durations use the 10-second default, while valid
durations are preserved.
* Invalid or nonpositive frame rates now use the default frame rate.
* Timeline rulers no longer display ticks beyond the maximum supported
duration.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
395fba30f7 |
fix: keep ruler tick spacing when zoomed out on long timelines (#265)
## What was wrong `TimelineRuler` renders one `TimelineTick` element per tick in the visible range. `findOptimalInterval` in `ruler-utils.ts` returned a fixed 60 s interval when no candidate (up to 3600 s) met the minimum pixel spacing. A project whose elements reach far along the timeline drives zoom-to-fit very low, so the visible range spans a huge number of seconds. At a 60 s tick that meant hundreds of thousands to millions of React elements created synchronously. ## What changed - `ruler-utils.ts`: past the largest fixed interval, the interval is the smallest whole number of hours that still meets the minimum spacing for the current pixels per second. Non-finite or non-positive zoom gets 3600 s. Hour multiples keep labels landing on tick positions. - `timeline-ruler.tsx`: renders at most 2000 ticks per pass (`MAX_RENDERED_RULER_TICKS`). The existing scroll buffer grows with `scrollLeft`, so on a long timeline scrolled far right the range can exceed the budget; `clampRenderedTickRange` then trims the buffer around the viewport and always keeps the visible ticks. Ranges within budget are unchanged. ## Blast radius Frontend only, the video-editor timeline ruler. Behaviour is unchanged at every zoom level where one of the existing intervals fits. Only the extreme zoomed-out case gets sparser, hour-based ticks. ## Checks run - `npx vitest run --root libs/components/video-editor src/lib/timeline/__tests__`: new `ruler-utils.spec.ts` (spacing at zoom 1e-6, degenerate zoom, normal zoom) passes, plus `clampRenderedTickRange` cases (within budget unchanged, viewport kept when far-scrolled, viewport at end, unbounded end). - `npx tsc -p libs/components/video-editor/tsconfig.lib.json --noEmit`: clean. ## Checks not run - Manual zoom-to-fit check in the running editor. - Restored-project timing validation (rejecting extreme `startTime`/`duration` on load) is not part of this change. Addresses CodeRabbit security findings (CWE-400). |
||
|
|
5812b78bbc |
fix: group pasted clips and fill transparent gradient stops in linear time (#261)
## What was wrong Two video-editor helpers did quadratic work on input that a stored project controls: - `groupClipboardItemsByTrackId` (clipboard paste) rebuilt each track's group with `[...existingItems, item]` for every clip, so pasting many clips from one track copied O(n^2) array entries before any placement check. - `fixTransparentStops` (CSS gradient backgrounds) searched backwards and then forwards through the whole stop list for every transparent stop. An all-transparent stop list in `project.settings.background` made the synchronous preview render quadratic in the stop count. ## What changed - Paste grouping appends to the existing per-track array. - Transparent-stop donors are found with one backward pass (nearest following opaque colour) and one forward pass (nearest preceding opaque colour). Each opaque stop is parsed once. Output is unchanged: a transparent stop still takes the previous parseable opaque colour, otherwise the next one, with alpha 0. - `fixTransparentStops` is exported from `gradients/canvas.ts` (not from the package index) so it can be tested. ## Blast radius Frontend only, `@storyteller/ui-video-editor`. No behaviour change for normal projects. Only clipboard paste and gradient background rendering are affected. ## Checks run - `npx vitest run --root libs/components/video-editor src/lib/gradients`: new `transparent-stops.spec.ts` (ordering, unparseable donors, 200k all-transparent stops) passes. - `npx tsc -p libs/components/video-editor/tsconfig.lib.json --noEmit`: clean. ## Checks not run - Manual paste/background check in the running editor. - `tsconfig.spec.json` typecheck. It reports TS6305 project-reference errors for every spec in this checkout (pre-existing, needs a built `dist`). Addresses CodeRabbit security findings (CWE-407). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Performance Improvements** * Gradients with many transparent color stops are processed more efficiently, while preserving transparency. * **Bug Fixes** * Transparent stops now use the nearest usable opaque color, preferring a preceding color and falling back to a following one. * Unparseable opaque colors are skipped when choosing a color, and consecutive transparent stops can share a usable donor. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
cb915f0d5b |
fix: frame upload previews in a single bounds pass (#249)
## What was wrong
`glbLoader` in `libs/components/upload-modal/.../loadPreviewOnCanvas.ts`
framed the camera with:
```ts
scene.traverse((object) => {
if (object instanceof THREE.Mesh) {
object.geometry.computeBoundingBox();
box.expandByObject(object);
}
});
```
`Box3.expandByObject` recurses into the object's children, so a chain of
nested meshes was walked O(n^2) times, and a geometry referenced by many
meshes had all its vertices rescanned once per reference. A small GLB
(one large geometry instanced across many nested nodes) could stall the
upload tab.
## What changed
- New `computeMeshBounds(root)`: one `updateMatrixWorld`, one traversal,
each distinct geometry's bounds computed once, object-level boxes for
skinned/instanced meshes (same choice `expandByObject` makes), unioned
in world space.
- The preview uses it; the mesh-less fallback is unchanged.
- Spec: 200 nested meshes sharing one geometry compute its bounds once
and produce the expected box.
## Blast radius
Upload preview camera framing only; resulting box is the same as before.
Addresses CodeRabbit security findings (CWE-407).
## Checks run
- `npx vitest run src/lib/UploadModal3D` in
`libs/components/upload-modal`: 5/5 pass.
- `npx tsc -p tsconfig.lib.json --noEmit`: same error count as `main`
(pre-existing; `three` typings are not installed in this checkout).
## Checks not run
- Manual preview of real GLB uploads.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Improvements**
* Improved camera framing in 3D upload previews for complex models,
including models with many meshes that share geometry. Framing now
accounts for transformed meshes and other visible model elements, such
as lines and points, so more of the model’s full extent is included when
the preview opens.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
944d7378bc |
fix: validate mention colors before writing them into editor HTML (#247)
## What was wrong
`MentionTextarea` (`libs/components/promptbox`) renders its
contenteditable content by building an HTML string and assigning it to
`editor.innerHTML`. Values from the public `colorMap` prop were
interpolated into `style="color:${color}"` without encoding, so a color
string containing `"` could close the attribute and inject elements with
event handlers that run with the page's authority. Current hosts pass
constant `rgb(...)` values, but the component accepted anything.
## What changed
- New `cssColor.ts` with `sanitizeCssColor()`: accepts hex colors, bare
keywords and `rgb/rgba/hsl/hsla()` with numeric arguments; rejects
everything else.
- `lowerColorMap` keeps only sanitized colors (an invalid color renders
the mention uncolored), and both interpolation sites also HTML-escape
the value.
- Specs: `cssColor.spec.ts`, and `MentionTextarea.spec.tsx` rendering a
hostile `colorMap` value (fails on `main`, passes here).
## Blast radius
Prompt box mention coloring. All palette values in `mentionColors.ts`
(`rgb(r, g, b)`) pass the validator unchanged.
Addresses CodeRabbit security findings (CWE-79).
## Checks run
- `npx vitest run src/lib/cssColor.spec.ts
src/lib/MentionTextarea.spec.tsx` in `libs/components/promptbox`: 3/3
pass.
- `npx tsc -p tsconfig.lib.json --noEmit`: same 29 pre-existing errors
as `main`, none in touched files.
## Checks not run
- Manual check in the webapp prompt box.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Mention colors are validated before display. Invalid colors are
omitted, while valid colors continue to appear as expected.
* Color values can no longer inject unwanted markup into mention chips
or text.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
41463fc4ee |
fix: require a positive Seedance 2.0 identity for the real verdict (#240)
## What was wrong `apps/video-info-website/src/lib/classify.ts` returned "Yes! It's Real Seedance 2.0" for any Seedance manifest whose model name did not contain `-fast` or `mini`. It ignored the parsed `maybe_model_version` and `is_lite` fields, so an older or Lite clip (e.g. `doubao-seedance-1-0-lite`, version 1.0, `is_lite=true`) received a false "verified full Seedance 2.0" verdict that a reseller could use to misrepresent it. ## What changed - The real verdict now requires a parsed version of `2.0` (a trailing numeric date suffix such as `2.0.260128` is accepted) and a model that is not Fast, Lite or Mini. - Other Seedance versions get a "Seedance X (not 2.0)" verdict; a manifest whose version could not be parsed gets an `unknown` verdict instead of an affirmative one. - Fast detection also honors the backend's `is_fast` flag; new Lite 2.0 verdict. - New `classify.spec.ts` covering full 2.0, date-suffixed 2.0, 1.0 Lite/Pro, 2.0 Fast/Mini/Lite and missing version. ## Blast radius Video info website verdict text only. No API changes. Addresses CodeRabbit security findings (verdict integrity; no CWE assigned). ## Checks run - `npx vitest run src/lib/classify.spec.ts`: 4/4 pass. - `npx tsc -p tsconfig.app.json --noEmit`: clean. ## Checks not run - Manual upload of real Seedance sample clips. |
||
|
|
4b8c3ecd0d |
fix: keep password reset tokens out of analytics page URLs (#237)
## What was wrong `frontend/apps/artcraft-webapp/index.html` loads Google Analytics on every route except `/login/desktop`. Password reset links (`/forgot-password/verify?token=...`) carry a bearer reset token in the query string, and gtag's automatic `page_view` reports the full page URL, so opening a reset link sent a credential that can change the password to the analytics provider. The token also stayed in the address bar, history, and referrers while the form was open. ## What changed - `index.html`: `/forgot-password/verify` is now treated like `/login/desktop` (no analytics script, `no-referrer`). Trailing slashes are normalized before the comparison. - `verify-reset.tsx`: after the token is captured into form state, it is removed from the URL with a `replace` navigation. Other query params (`from`) are kept. - Regression spec in `login-bridge-continuation.spec.tsx`: the token pre-fills the form and is gone from the location search. ## Blast radius Webapp only. Analytics no longer records visits to the reset verification page. The reset form behaves the same. Addresses CodeRabbit security findings (CWE-201). ## Checks run - `npx vitest run src/pages/login/login-bridge-continuation.spec.tsx` (with `NODE_OPTIONS=--no-experimental-webstorage`; Node 26's built-in localStorage shadows jsdom otherwise): 6/6 pass; the new test fails without the fix. ## Checks not run - Full `tsc -b` for the webapp (library `dist` declarations are not built in this checkout; no new type errors in the touched lines). - Manual check against live GA. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Security & Privacy** * Analytics is suppressed on desktop login and password verification pages, including URLs with different capitalization, percent-encoded paths, or trailing slashes. Referrer information is no longer sent from these pages. * Reset tokens are removed from the verification page URL after being read, while other query parameters are preserved. * **Tests** * Added coverage for prefilled reset codes and URL cleanup. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
65e0feccd5 |
fix(promptbox): ignore empty mention labels (#306)
## What was wrong `MentionTextarea` builds one regex from all `mentionItems` labels. An empty label made the alternation match the empty string, and the `while ((match = regex.exec(text)) !== null)` loops in `buildHTML` and the other render paths never advance after a zero-length match, so the page hung. ## What changed Empty labels are dropped before the regex is built (with no labels left, the regex is `null`, as before). ## Blast radius Prompt-box mention highlighting only; non-empty labels behave the same. ## Checks run - `tsc -p libs/components/promptbox/tsconfig.lib.json`: no new errors compared with `main`. ## Checks not run - No test added: the change is a one-line filter. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Empty mention labels are now ignored when matching text, preventing them from interfering with the recognition and display of valid mentions. When no nonempty labels are available, the existing fallback behavior is preserved. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
704e6a5c52 |
frontend: Number.parseFloat/parseInt/isFinite/isNaN (Sonar S7773) (#372)
Clears the 93 open typescript:S7773 issues (40 files), only on the lines Sonar flagged. Same change as storytold/artcraft#2819 for the libraries both repos share. - `parseFloat` / `parseInt` / `NaN` → `Number.parseFloat` / `Number.parseInt` / `Number.NaN`: the same values. - `isFinite` / `isNaN` → `Number.isFinite` / `Number.isNaN`: they differ only for arguments that aren't numbers, and TypeScript types the globals as taking `number`. Typechecked locally against main: no new errors in the 9 projects touched (dashboard, webapp, website-next, and the input, modal, pagedraw, pagescene, promptbox and video-editor libraries). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Prompt limits now distinguish finite numeric values from non-numeric or unlimited values, improving limit checks and display. * Numeric inputs across prompt tools, editors, and controls retain their existing parsing, validation, and bounds behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
d903ff2e2c |
Sonar: [[ ]] in scripts, npm install --ignore-scripts, retired local-dev setup out of scope (#373)
- **shell:S7688 (43)**: `[[ ]]` in place of `[ ]` in
`script/metrics/apply_{dashboards,metric_configs,monitors}.sh`,
`script/common/frontend_preflight.sh` and
`script/website/unix_frontend_dashboard_dev.sh`. Every script has a bash
shebang and `bash -n` passes. No test uses `-a`/`-o`, escaped
parentheses or an unquoted pattern on the right of `=`. The numeric
operands are `$#`, internal flags, exit codes, a parsed Node major
version and curl's status code, so `[[ ]]`'s arithmetic reading changes
nothing.
- **shell:S6505 (4)**: `npm install --ignore-scripts` in
`frontend_preflight.sh`, `unix_frontend_webapp_dev.sh` and
`frontend/build_modules.sh`. The frontend has no install scripts of its
own, and this repo's CI already builds with `npm ci --ignore-scripts`.
Same change as storytold/artcraft#2818.
- **Scope**: `_docs/old/**` joins `sonar.exclusions`. It's the retired
local-dev setup (an old Dockerfile, `kubernetes.yml`, nginx config) that
nothing references, and it held the docker and kubernetes findings under
`_docs/old/old_localdev_setup`.
Same as the other PRs here: not merged without the owner's go-ahead
(production service).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Chores**
* Frontend dependency installation now skips package-provided lifecycle
scripts, including during development setup. This changes which scripts
run during installation but does not change the frontend’s intended
features or behavior.
* Updated internal checks used by dashboard, metric, and monitor scripts
without changing their conditions or outcomes.
* Expanded static-analysis exclusions to include archived documentation.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|