diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 6c711e6..dce3796 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -117,17 +117,17 @@ jobs: - name: Checkout code if: env.SKIP != 'true' - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Initialize CodeQL if: env.SKIP != 'true' - uses: github/codeql-action/init@v4 + uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} - name: Analyze if: env.SKIP != 'true' - uses: github/codeql-action/analyze@v4 + uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4 with: category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0da9a2a..e09f7fb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,13 +43,13 @@ jobs: tag: ${{ steps.decide.outputs.tag }} prerelease: ${{ steps.decide.outputs.prerelease }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # Full history and tags: the compare link in the release body is built from the # previous tag, and a shallow clone has neither. fetch-depth: 0 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 22 @@ -149,7 +149,7 @@ jobs: echo "--- release notes ---" cat release-notes.md - - uses: actions/upload-artifact@v7 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: release-notes path: release-notes.md @@ -177,7 +177,7 @@ jobs: outputs: release_id: ${{ steps.create.outputs.release_id }} steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-notes @@ -270,7 +270,7 @@ jobs: # for a cold dependency cache. timeout-minutes: 60 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -293,14 +293,15 @@ jobs: sudo rm -rf /opt/ghc /usr/local/share/boost >/dev/null 2>&1 & - name: setup node - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 22 cache: 'npm' - name: install Rust stable - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable branch with: + toolchain: stable # Those targets are only used on macos runners so it's skip on linux and windows targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }} @@ -309,7 +310,7 @@ jobs: # roughly 600 of windows-latest's 694. test.yml has cached since it was written; the # build matrix simply never got one. - name: Cache Rust dependencies - uses: swatinem/rust-cache@v2 + uses: swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: workspaces: src-tauri -> target @@ -443,7 +444,7 @@ jobs: # is what the in-app updater renders, and composing it once per leg is five more # chances for the release body and the update notes to come apart - which is how they # came apart before. - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-notes @@ -458,7 +459,7 @@ jobs: printf '%s\n' "$delim" } >> "$GITHUB_ENV" - - uses: tauri-apps/tauri-action@v1 + - uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # action-v1.0.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: @@ -505,6 +506,22 @@ jobs: args: ${{ matrix.args }} + # The signing keys went into $GITHUB_ENV above, conditionally, because an exported + # empty value makes the bundler try to sign with nothing and fail - so they cannot + # simply be scoped to the tauri-action step with `env:`. That leaves them visible to + # every later step, and post-steps such as rust-cache's run with the job's environment + # at the very end. Blank them as soon as the build is done, whatever its outcome, so + # nothing after this point can read the updater key or the Apple credentials. + - name: Forget the signing secrets + if: always() + shell: bash + run: | + for name in TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD \ + APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY \ + APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID; do + echo "$name=" >> "$GITHUB_ENV" + done + publish: name: Publish release needs: [prepare, draft, build] diff --git a/.github/workflows/screenshots.yml b/.github/workflows/screenshots.yml index e6d4ebb..8147c29 100644 --- a/.github/workflows/screenshots.yml +++ b/.github/workflows/screenshots.yml @@ -25,21 +25,30 @@ concurrency: group: screenshots cancel-in-progress: false +# Nothing here needs to write to this repository. +permissions: + contents: read + jobs: + # Runs the app's code and every dependency's, so it holds no secret at all. The website + # token used to be checked out in this same job, after `npm ci` and the capture had run, + # where anything they left running could read it from website/.git/config and push to + # the website's main - which is a production deploy. capture: - name: Capture and publish to the website + name: Capture runs-on: ubuntu-latest steps: - name: Check out the app - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + persist-credentials: false # A release event's default checkout is the default branch, not the released # commit. Photographing main would silently ship pictures of work that has not # been released yet. ref: ${{ github.event.release.tag_name || inputs.ref }} - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: "22" cache: "npm" @@ -58,8 +67,28 @@ jobs: SCREENSHOT_VERSION: ${{ github.event.release.tag_name || '' }} run: npm run screenshots + - name: Hand the pictures to the publish job + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: screenshots + path: screenshots/out + retention-days: 1 + if-no-files-found: error + + # Holds the website token, and runs nothing but git and cp. + publish: + name: Publish to the website + needs: capture + runs-on: ubuntu-latest + steps: + - name: Receive the pictures + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: screenshots + path: screenshots/out + - name: Check out the website - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: EarMaster/stashpad-website # A fine-grained PAT with contents:write on the website repo. The default @@ -78,6 +107,10 @@ jobs: - name: Commit and push, if anything actually changed working-directory: website + # The tag goes through the environment, never into the script text: a + # perfectly valid tag name containing `$(...)` would otherwise have run as shell. + env: + VERSION: ${{ github.event.release.tag_name || 'a manual run' }} run: | git config user.name 'stashpad-bot' git config user.email 'noreply@stashpad.org' @@ -93,7 +126,6 @@ jobs: exit 0 fi - VERSION="${{ github.event.release.tag_name || 'a manual run' }}" git commit -m "Update the app screenshots for ${VERSION}" -m \ "Regenerated from the released build by the app's screenshots workflow." git push diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a725714..a09f4ae 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,6 +33,11 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.head.sha || github.sha }} cancel-in-progress: true +# Tests read the code and nothing else; the token they get says so, whatever the repository +# default is. +permissions: + contents: read + jobs: # Green between releases, since package.json and the newest CHANGELOG.md heading agree. # It goes red in the window between a version bump and a written changelog - which is @@ -47,10 +52,10 @@ jobs: timeout-minutes: 20 steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: "22" @@ -69,10 +74,10 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: "22" cache: "npm" @@ -97,7 +102,7 @@ jobs: - name: Upload coverage to Codecov if: matrix.os == 'ubuntu-latest' - uses: codecov/codecov-action@v7 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: # `files`, plural: v5 deprecated the singular `file`, and a v7 that does not # recognise the input uploads nothing while still reporting success. @@ -116,7 +121,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # Backgrounded, because as a blocking step this cost 91 seconds in a job whose actual # work - `cargo test` - takes 24. Almost all of it is /usr/local/lib/android, nine @@ -145,8 +150,9 @@ jobs: # and pins a deprecated Node runtime - tolerable in an advisory job, a latent hard failure # now that this suite gates every release. - name: Setup Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable branch with: + toolchain: stable components: rustfmt, clippy # `save-if` is what keeps this affordable. Every push and every pull_request run used to @@ -166,7 +172,7 @@ jobs: # roughly daily. A `Cargo.lock` or rustc change between releases means develop runs cold # until the next one - the honest cost of three entries instead of nine. - name: Cache Rust dependencies - uses: swatinem/rust-cache@v2 + uses: swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: workspaces: src-tauri -> target save-if: ${{ github.ref == 'refs/heads/main' }} @@ -204,12 +210,12 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # 22, matching every other job and the toolchain the release actually builds on. This was # 20, which is a poor thing for a release gate to be compiling against. - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: "22" cache: "npm" diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9e00e09..2d28a8c 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -85,7 +85,7 @@ export interface IStorageService { ### 3.2 Implementation Strategy -1. **`src/lib/services/adapters/desktop.adapter.ts`**: Implements `IStorageService` using Tauri `invoke` commands and `tauri-plugin-fs`. +1. **`src/lib/services/adapters/desktop.adapter.ts`**: Implements `IStorageService` using Tauri `invoke` commands. 2. **`src/lib/services/index.ts`**: Detects environment and exports the correct adapter. ```typescript // Pseudo-code diff --git a/CHANGELOG.md b/CHANGELOG.md index d3921c8..d0559f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,72 @@ popover, not for the person who wrote the commit. ## [Unreleased] +## [1.11.0] - 2026-10-11 + +### Added +- **Search your stashes with Cmd+F (Ctrl+F on Windows and Linux).** It searches the current + context; press it again to search all of them. Unlike finding text on the page, it also + looks through completed stashes, the hidden part of long stashes, AI-enhanced versions and + attachment names, and it forgives typos and unfinished words. Matching stashes open up with + the words marked, and a result from another context takes you there + +### Changed +- **When a subscription ends, Stashpad says so instead of showing a sync error.** If the cloud + no longer counts your account as entitled to sync - a subscription that ran out while the + app stayed signed in - sync now stops and Settings offers the upgrade, rather than failing + with the same error every few minutes. A full cloud storage is reported in plain words too +- **A link to a finished stash now looks finished, not deleted.** Links to completed stashes + were struck through, which read as if the stash were gone. They now show the checkmark in + green, like the complete button, and so does their hover preview. Strikethrough is kept for + links to stashes that were deleted. Link labels are also shorter, so a line of them stays + readable + +### Security +- **A synced stash can no longer place files outside Stashpad's own folder.** Stash and + context ids from the cloud were used as folder names when an attachment was downloaded, so a + stash pushed with a crafted id could write a file anywhere on every device linked to the + account - including a folder whose contents run when you sign in. Ids that are not in the + expected format are now refused when they arrive, and downloads are checked to stay inside + the attachment cache +- **Stashpad only ever uploads files from its own attachment folder.** A file location + received through sync was stored and later read by the upload step, so a compromised sync + server could have named any file on your computer and had it uploaded. Synced attachments no + longer carry a location, and uploads refuse any file outside the attachment cache +- **A crafted import file can no longer write outside its folder on Windows.** An entry named + with a drive letter, such as `C:file.dll`, slipped past the check while the file was being + previewed, before you had confirmed anything. Import files now only accept plain names inside + the archive +- **Hashtags in a stash can no longer be used to sneak in page elements.** The step that turns + `#tags` into badges ran after the content was cleaned, and a link title written a particular + way let text through as real page elements, such as a form or an overlay. Tags are now found + in the text itself, so the cleaned content stays clean, and tags render exactly as before +- **An encrypted account no longer accepts unencrypted stashes from the server.** While an + account was being converted, unencrypted records were accepted on purpose, and that stayed + true after the conversion had finished - so the server could have slipped in content it never + encrypted. Once your account is fully encrypted, Stashpad now leaves such records out of the + sync instead of showing them +- **Changing the cloud server address now signs you out of the old one.** Your sign-in used to + carry over to whatever address was entered, so it would have been sent to that server too. + The app window can also no longer reach Stashpad's own settings and database files, only + attachments +- **Your sign-in no longer appears in web addresses during live sync.** The connection that + tells Stashpad about changes from your other devices carried your session in its address, + where servers along the way can log it. It now travels in a header instead. This version + needs the matching update to Stashpad Cloud, which ships with it +- **Only the browser page you opened from Stashpad can link it to an account.** While the link + dialog was open, any web page could open a Stashpad link of its own and connect the app to + a different account, so your stashes would sync there. The app now ignores links it did + not ask for; typing the code by hand works as before +- **Your AI provider key now stays inside Stashpad's backend.** The app window used to hold + the key and call the provider itself, so it had to be allowed to connect anywhere. The + backend now makes those requests, the window can no longer reach the network at all, and + Settings only shows that a key is saved. A saved key is kept for the endpoint it was + entered for: change the endpoint, and enter the key again +- **Stashpad only reads the files you give it.** The app window could read any file in your + Downloads, Desktop and Documents folders, and could ask the backend to attach a file from + anywhere on your computer. Now only files you drop on the window or choose in a file dialog + can be attached, imported or exported to, and the window itself can no longer read files + ## [1.10.2] - 2026-10-05 ### Added diff --git a/package-lock.json b/package-lock.json index 3af3aaf..2777b01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,20 +13,20 @@ "@tauri-apps/plugin-autostart": "^2.5.1", "@tauri-apps/plugin-deep-link": "^2.4.7", "@tauri-apps/plugin-dialog": "^2.6.0", - "@tauri-apps/plugin-fs": "^2.4.5", "@tauri-apps/plugin-opener": "^2.5.3", "@tauri-apps/plugin-process": "^2.3.1", "@tauri-apps/plugin-updater": "^2.10.0", "@thisux/sveltednd": "^0.0.20", "@types/dompurify": "^3.0.5", "clsx": "^2.1.1", - "dompurify": "^3.3.2", + "dompurify": "^3.4.16", "fuzzysort": "^3.1.0", "highlight.js": "^11.11.1", "jwt-decode": "^4.0.0", "lucide-svelte": "^0.556.0", "marked": "^17.0.1", "marked-highlight": "^2.2.3", + "minisearch": "^7.2.0", "svelte-dnd-action": "^0.9.68", "svelte-i18n": "^4.0.1", "tailwind-merge": "^3.4.0", @@ -48,7 +48,7 @@ "jsdom": "^27.4.0", "playwright": "^1.63.0", "postcss": "^8.5.6", - "svelte": "^5.45.6", + "svelte": "^5.57.2", "tailwindcss": "^4.1.17", "tailwindcss-animate": "^1.0.7", "typescript": "~5.9.3", @@ -879,9 +879,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "license": "MIT" }, "node_modules/@jridgewell/trace-mapping": { @@ -1217,9 +1217,9 @@ "license": "MIT" }, "node_modules/@sveltejs/acorn-typescript": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.8.tgz", - "integrity": "sha512-esgN+54+q0NjB0Y/4BomT9samII7jGwNy/2a3wNZbT2A2RpmXsXwUt24LvLhx6jUq2gVk4cWEvcRO6MFQbOfNA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", + "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", "license": "MIT", "peerDependencies": { "acorn": "^8.9.0" @@ -1816,15 +1816,6 @@ "@tauri-apps/api": "^2.8.0" } }, - "node_modules/@tauri-apps/plugin-fs": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-fs/-/plugin-fs-2.4.5.tgz", - "integrity": "sha512-dVxWWGE6VrOxC7/jlhyE+ON/Cc2REJlM35R3PJX3UvFw2XwYhLGQVAIyrehenDdKjotipjYEVc4YjOl3qq90fA==", - "license": "MIT OR Apache-2.0", - "dependencies": { - "@tauri-apps/api": "^2.8.0" - } - }, "node_modules/@tauri-apps/plugin-opener": { "version": "2.5.3", "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.5.3.tgz", @@ -2253,9 +2244,9 @@ } }, "node_modules/acorn": { - "version": "8.15.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", - "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "license": "MIT", "bin": { "acorn": "bin/acorn" @@ -2301,6 +2292,7 @@ "version": "5.3.2", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", + "dev": true, "license": "Apache-2.0", "engines": { "node": ">= 0.4" @@ -2642,9 +2634,9 @@ } }, "node_modules/devalue": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.5.0.tgz", - "integrity": "sha512-69sM5yrHfFLJt0AZ9QqZXGCPfJ7fQjvpln3Rq5+PS03LD32Ost1Q9N+eEnaQwGRIriKkMImXD56ocjQmfjbV3w==", + "version": "5.9.4", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz", + "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", "license": "MIT" }, "node_modules/dom-accessibility-api": { @@ -2655,13 +2647,10 @@ "license": "MIT" }, "node_modules/dompurify": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.2.tgz", - "integrity": "sha512-6obghkliLdmKa56xdbLOpUZ43pAR6xFy1uOrxBaIDjT+yaRuuybLjGS9eVBoSR/UPU5fq3OXClEHLJNGvbxKpQ==", + "version": "3.4.16", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", "license": "(MPL-2.0 OR Apache-2.0)", - "engines": { - "node": ">=20" - }, "optionalDependencies": { "@types/trusted-types": "^2.0.7" } @@ -2833,12 +2822,20 @@ } }, "node_modules/esrap": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.2.1.tgz", - "integrity": "sha512-GiYWG34AN/4CUyaWAgunGt0Rxvr1PTMlGC0vvEov/uOQYWne2bpN03Um+k8jT+q3op33mKouP2zeJ6OlM+qeUg==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", + "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==", "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } } }, "node_modules/estree-walker": { @@ -3636,6 +3633,12 @@ "node": ">=4" } }, + "node_modules/minisearch": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", + "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", + "license": "MIT" + }, "node_modules/mri": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", @@ -4042,22 +4045,22 @@ } }, "node_modules/svelte": { - "version": "5.45.6", - "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.45.6.tgz", - "integrity": "sha512-V3aVXthzPyPt1UB1wLEoXnEXpwPsvs7NHrR0xkCor8c11v71VqBj477MClqPZYyrcXrAH21sNGhOj9FJvSwXfQ==", + "version": "5.57.2", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.2.tgz", + "integrity": "sha512-1YiPCAXT0Ct6g1vOMmSLa0Nsc3QRMvtDF32ihgglGVrugIuIK38RyDiFNXVDhtQ81TJjSO57NdMw6DyYLqSGDQ==", "license": "MIT", "dependencies": { - "@jridgewell/remapping": "^2.3.4", - "@jridgewell/sourcemap-codec": "^1.5.0", - "@sveltejs/acorn-typescript": "^1.0.5", - "@types/estree": "^1.0.5", - "acorn": "^8.12.1", - "aria-query": "^5.3.1", + "@jridgewell/remapping": "^2.3.5", + "@jridgewell/sourcemap-codec": "^1.6.0", + "@sveltejs/acorn-typescript": "^1.0.13", + "@types/estree": "^1.0.9", + "acorn": "^8.18.0", + "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", - "devalue": "^5.5.0", + "devalue": "^5.9.2", "esm-env": "^1.2.1", - "esrap": "^2.2.1", + "esrap": "^2.3.6", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", @@ -4506,6 +4509,21 @@ "@esbuild/win32-x64": "0.19.12" } }, + "node_modules/svelte/node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "license": "MIT" + }, + "node_modules/svelte/node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", diff --git a/package.json b/package.json index 55419c2..d2dd30f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad", - "version": "1.10.2", + "version": "1.11.0", "description": "The staging area for your AI context.", "author": { "name": "Nico Wiedemann", @@ -58,7 +58,7 @@ "jsdom": "^27.4.0", "playwright": "^1.63.0", "postcss": "^8.5.6", - "svelte": "^5.45.6", + "svelte": "^5.57.2", "tailwindcss": "^4.1.17", "tailwindcss-animate": "^1.0.7", "typescript": "~5.9.3", @@ -70,20 +70,20 @@ "@tauri-apps/plugin-autostart": "^2.5.1", "@tauri-apps/plugin-deep-link": "^2.4.7", "@tauri-apps/plugin-dialog": "^2.6.0", - "@tauri-apps/plugin-fs": "^2.4.5", "@tauri-apps/plugin-opener": "^2.5.3", "@tauri-apps/plugin-process": "^2.3.1", "@tauri-apps/plugin-updater": "^2.10.0", "@thisux/sveltednd": "^0.0.20", "@types/dompurify": "^3.0.5", "clsx": "^2.1.1", - "dompurify": "^3.3.2", + "dompurify": "^3.4.16", "fuzzysort": "^3.1.0", "highlight.js": "^11.11.1", "jwt-decode": "^4.0.0", "lucide-svelte": "^0.556.0", "marked": "^17.0.1", "marked-highlight": "^2.2.3", + "minisearch": "^7.2.0", "svelte-dnd-action": "^0.9.68", "svelte-i18n": "^4.0.1", "tailwind-merge": "^3.4.0", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index d192aa5..f74a7f0 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1458,7 +1458,7 @@ dependencies = [ [[package]] name = "drag" version = "2.1.0" -source = "git+https://github.com/crabnebula-dev/drag-rs#8c88ba0084615f2b1e7796d9ff7611b37f5ea31b" +source = "git+https://github.com/crabnebula-dev/drag-rs?rev=8c88ba0084615f2b1e7796d9ff7611b37f5ea31b#8c88ba0084615f2b1e7796d9ff7611b37f5ea31b" dependencies = [ "cocoa", "core-graphics 0.24.0", @@ -5557,7 +5557,7 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stashpad" -version = "1.10.2" +version = "1.11.0" dependencies = [ "active-win-pos-rs", "aes-gcm", @@ -5589,7 +5589,6 @@ dependencies = [ "tauri-plugin-autostart", "tauri-plugin-deep-link", "tauri-plugin-dialog", - "tauri-plugin-fs", "tauri-plugin-global-shortcut", "tauri-plugin-log", "tauri-plugin-opener", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4d19ca2..7357d33 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stashpad" -version = "1.10.2" +version = "1.11.0" description = "The staging area for your AI context." authors = ["Nico Wiedemann "] repository = "https://github.com/EarMaster/stashpad" @@ -32,7 +32,7 @@ temporal_rs = { version = "0.2.6", default-features = false, features = ["sys"] base64 = "0.22" dirs = "6.0.0" arboard = "3.6.1" -drag = { git = "https://github.com/crabnebula-dev/drag-rs" } +drag = { git = "https://github.com/crabnebula-dev/drag-rs", rev = "8c88ba0084615f2b1e7796d9ff7611b37f5ea31b" } tauri-plugin-global-shortcut = "2.3.1" # Only for its error type: the plugin flattens errors to strings, and telling "another app # holds this shortcut" apart from other failures means rebuilding that exact message. @@ -40,7 +40,6 @@ global-hotkey = "0.7" tauri-plugin-dialog = "2" window-vibrancy = "0.5" tauri-plugin-window-state = "2.4.1" -tauri-plugin-fs = "2.4.4" tauri-plugin-shell = "2.3.3" rusqlite = { version = "0.32", features = ["bundled"] } uuid = { version = "1.11", features = ["v4", "serde"] } diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 2253bde..0660d81 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -8,22 +8,7 @@ "permissions": [ "core:default", "core:window:allow-start-dragging", - "dialog:default", - "dialog:allow-save", - "fs:default", - "fs:allow-read", - "fs:allow-write", - "fs:allow-write-text-file", - "fs:allow-write-file", - { - "identifier": "fs:scope", - "allow": [ - "$HOME/.stashpad/**/*", - "$DOWNLOAD/**/*", - "$DESKTOP/**/*", - "$DOCUMENT/**/*" - ] - }, + "dialog:allow-message", "shell:default", "opener:default", "window-state:default", diff --git a/src-tauri/src/account_export.rs b/src-tauri/src/account_export.rs index c319f66..2c236ec 100644 --- a/src-tauri/src/account_export.rs +++ b/src-tauri/src/account_export.rs @@ -300,7 +300,8 @@ pub struct AccountExportSummary { pub stashes: usize, } -/// Write every context out as Markdown, one file per context, into a directory. +/// Write every context out as Markdown, one file per context, into a directory - one the +/// user handed over, see handover.rs. /// /// Reuses the per-context writer rather than inventing a second format, so what comes out /// is the same thing the existing exporter produces and the existing importer reads. @@ -309,6 +310,7 @@ pub async fn export_whole_account( state: State<'_, Arc>, dest_dir: String, ) -> Result { + crate::handover::check(&dest_dir)?; let (contexts, by_context) = { let db = state.lock_db(); let contexts = db.get_contexts().map_err(|e| e.to_string())?; @@ -343,7 +345,7 @@ pub async fn export_whole_account( let file = std::path::Path::new(&dest_dir).join(format!("{}.md", safe_file_name(&context.name))); - crate::transfer::export_context_archive( + crate::transfer::write_context_archive( state.clone(), context.id.clone(), ids, diff --git a/src-tauri/src/ai.rs b/src-tauri/src/ai.rs new file mode 100644 index 0000000..b96792a --- /dev/null +++ b/src-tauri/src/ai.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Copyright (C) 2026 Nico Wiedemann +// +// This file is part of Stashpad. +// Stashpad is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License, version 3, +// as published by the Free Software Foundation. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +// See the GNU Affero General Public License for more details. + +//! Requests to an OpenAI-compatible AI provider, made from here rather than the webview. +//! +//! The provider calls used to be `fetch`es in the frontend, which meant the API key had to +//! be handed to the webview - and that any script running there could read it, or send it +//! anywhere, since the page's `connect-src` had to be `*` for providers on any host. Now the +//! key never leaves the backend: [`ai_enhance`] uses the saved configuration as it is, and +//! [`ai_test_connection`] only ever pairs the saved key with the saved endpoint. + +use std::sync::Arc; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use tauri::State; + +use crate::state::SettingsState; +use crate::uierror::UiError; + +const AI_TIMEOUT: Duration = Duration::from_secs(120); +const AI_CONNECT_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Serialize)] +struct ChatMessage<'a> { + role: &'a str, + content: &'a str, +} + +#[derive(Serialize)] +struct ChatRequest<'a> { + model: &'a str, + messages: Vec>, + #[serde(skip_serializing_if = "Option::is_none")] + temperature: Option, + max_tokens: u32, + stream: bool, +} + +fn chat_url(endpoint: &str) -> String { + format!("{}/chat/completions", endpoint.trim_end_matches('/')) +} + +/// Whether two endpoints are the same provider, ignoring a trailing slash. +pub fn same_endpoint(a: &str, b: &str) -> bool { + a.trim().trim_end_matches('/') == b.trim().trim_end_matches('/') +} + +async fn post_chat( + endpoint: &str, + api_key: &str, + request: &ChatRequest<'_>, +) -> Result { + let client = reqwest::Client::builder() + .connect_timeout(AI_CONNECT_TIMEOUT) + .timeout(AI_TIMEOUT) + .build() + .map_err(|e| format!("Failed to build HTTP client: {}", e))?; + + let mut builder = client.post(chat_url(endpoint)).json(request); + if !api_key.is_empty() { + builder = builder.bearer_auth(api_key); + } + let response = builder + .send() + .await + .map_err(|e| format!("Could not reach the AI provider: {}", e))?; + + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + let snippet: String = body.chars().take(300).collect(); + return Err(format!("{}: {}", status.as_u16(), snippet).into()); + } + response + .json() + .await + .map_err(|e| format!("The AI provider sent an unreadable answer: {}", e).into()) +} + +/// Improve a stash's text with the saved provider. The frontend supplies the prompt and the +/// text; the endpoint, model and key come from the saved settings only. +#[tauri::command] +pub async fn ai_enhance( + settings_state: State<'_, Arc>, + system_prompt: String, + user_content: String, +) -> Result { + let config = settings_state + .lock_settings() + .ai_config + .clone() + .ok_or("AI configuration is missing")?; + if !config.enabled { + return Err("AI configuration is disabled".into()); + } + if config.endpoint.trim().is_empty() || config.model.trim().is_empty() { + return Err("AI configuration is incomplete".into()); + } + + let request = ChatRequest { + model: &config.model, + messages: vec![ + ChatMessage { + role: "system", + content: &system_prompt, + }, + ChatMessage { + role: "user", + content: &user_content, + }, + ], + temperature: Some(0.3), + max_tokens: 1024, + stream: false, + }; + let data = post_chat(&config.endpoint, &config.api_key, &request).await?; + data["choices"][0]["message"]["content"] + .as_str() + .map(str::to_string) + .ok_or_else(|| "No content in API response".into()) +} + +/// The settings a connection test runs against: what the form currently shows, which may not +/// be saved yet. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConnectionTest { + pub endpoint: String, + pub model: String, + /// A key typed into the form. Empty means "the saved one" - which is only used when the + /// endpoint is the saved endpoint, so a test can never carry the saved key elsewhere. + #[serde(default)] + pub api_key: String, +} + +#[tauri::command] +pub async fn ai_test_connection( + settings_state: State<'_, Arc>, + test: ConnectionTest, +) -> Result<(), UiError> { + if test.endpoint.trim().is_empty() || test.model.trim().is_empty() { + return Err("Configuration is incomplete".into()); + } + let api_key = if test.api_key.is_empty() { + let saved = settings_state.lock_settings().ai_config.clone(); + match saved { + Some(saved) if same_endpoint(&saved.endpoint, &test.endpoint) => saved.api_key, + _ => String::new(), + } + } else { + test.api_key + }; + + let request = ChatRequest { + model: &test.model, + messages: vec![ + ChatMessage { + role: "system", + content: "You are a connection tester.", + }, + ChatMessage { + role: "user", + content: "Say \"OK\" to confirm the connection works.", + }, + ], + temperature: None, + max_tokens: 10, + stream: false, + }; + post_chat(&test.endpoint, &api_key, &request) + .await + .map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_compare_without_a_trailing_slash() { + assert!(same_endpoint( + "https://api.openai.com/v1/", + "https://api.openai.com/v1" + )); + assert!(!same_endpoint( + "https://api.openai.com/v1", + "https://evil.example/v1" + )); + } + + #[test] + fn the_chat_url_is_built_once() { + assert_eq!( + chat_url("http://localhost:11434/v1/"), + "http://localhost:11434/v1/chat/completions" + ); + } +} diff --git a/src-tauri/src/browser_drop.rs b/src-tauri/src/browser_drop.rs index c1b6835..9492b37 100644 --- a/src-tauri/src/browser_drop.rs +++ b/src-tauri/src/browser_drop.rs @@ -44,7 +44,10 @@ fn nothing_usable() -> UiError { pub async fn read_dropped_image() -> Result { #[cfg(target_os = "macos")] { - macos::read().await + // The scratch file is the user's drop in another form, so it may be saved like one. + let path = macos::read().await?; + crate::handover::record([&path]); + Ok(path) } #[cfg(not(target_os = "macos"))] { @@ -88,7 +91,7 @@ mod macos { use crate::uierror::UiError; /// Scratch folder for the image of the latest browser drop. Emptied on every drop, so at - /// most one stale file lingers - and it is under the app folder the fs scope allows. + /// most one stale file lingers. fn scratch_dir() -> PathBuf { crate::utils::get_app_dir().join("tmp").join("drop") } diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index c93ee2f..03b8edf 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -760,6 +760,12 @@ impl DbManager { pub fn import_contexts(&mut self, contexts: &[Context]) -> Result> { let tx = self.conn.transaction()?; for ctx in contexts { + // A context id names a cache directory, so one that is not a UUID is refused + // rather than written: see `ids`. + if !crate::ids::is_context_id(&ctx.id) { + log::warn!("Skipping a synced context with a malformed id"); + continue; + } // Nothing deletes the default context, so a tombstone for it is dropped rather // than allowed to take every unfiled stash with it. if ctx.id == "default" && ctx.deleted { @@ -1218,6 +1224,15 @@ impl DbManager { }; let tx = self.conn.transaction()?; for stash in stashes { + // These ids become cache directory names, and they come from the server, another + // device or an imported file. One that is not a UUID is dropped here, at the + // door, so nothing downstream ever has to wonder: see `ids`. + if !crate::ids::is_record_id(&stash.id) || !crate::ids::is_context_id(&stash.context_id) + { + log::warn!("Skipping a stash with a malformed id"); + continue; + } + let files_json = serde_json::to_string(&stash.files).unwrap_or_default(); let existing_pos = read_position(&tx, &stash.id)?; @@ -1256,6 +1271,15 @@ impl DbManager { )?; for att in &stash.attachments { + // An attachment hangs off this stash and nowhere else, and its id names the + // partial file a download writes. + // An empty `stash_id` means the parent below; any other one must match it. + if !crate::ids::is_record_id(&att.id) + || !(att.stash_id.is_empty() || att.stash_id == stash.id) + { + log::warn!("Skipping an attachment with a malformed id"); + continue; + } tx.execute( // Never blank an existing local path: the server has no concept of a // local file_path and always sends it empty, so an incoming empty @@ -1263,8 +1287,14 @@ impl DbManager { "INSERT INTO attachments (id, stash_id, file_path, file_name, file_size, mime_type, syntax, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) ON CONFLICT(id) DO UPDATE SET stash_id=excluded.stash_id, file_path=CASE WHEN TRIM(excluded.file_path)='' THEN attachments.file_path ELSE excluded.file_path END, file_name=excluded.file_name, file_size=excluded.file_size, mime_type=excluded.mime_type, syntax=excluded.syntax", params![ att.id, - att.stash_id, - att.file_path, + stash.id, + // A path is only ever this device's own. One arriving through sync + // could name any file the user can read, and the upload pass would + // send it to the server, so a sync import never records one. + match origin { + WriteOrigin::SyncImport => "", + WriteOrigin::LocalEdit => att.file_path.as_str(), + }, att.file_name, att.file_size, att.mime_type, @@ -1720,20 +1750,38 @@ mod tests { #[test] fn deleting_a_context_deletes_its_stashes() { let mut db = create_test_db(); - db.save_context(&plain_context("work", false), WriteOrigin::LocalEdit) - .unwrap(); - insert_raw_stash(&db, "s-work", Some("work")); + db.save_context( + &plain_context("00000000-0000-4000-8000-00000000c0de", false), + WriteOrigin::LocalEdit, + ) + .unwrap(); + insert_raw_stash( + &db, + "00000000-0000-4000-8000-0000000000a1", + Some("00000000-0000-4000-8000-00000000c0de"), + ); insert_raw_stash(&db, "s-default", Some("default")); - let deleted = db.delete_context("work").unwrap(); + let deleted = db + .delete_context("00000000-0000-4000-8000-00000000c0de") + .unwrap(); - assert_eq!(deleted, vec![("s-work".to_string(), "work".to_string())]); - assert_eq!(stored(&db, "s-work"), ("work".to_string(), true)); + assert_eq!( + deleted, + vec![( + "00000000-0000-4000-8000-0000000000a1".to_string(), + "00000000-0000-4000-8000-00000000c0de".to_string() + )] + ); + assert_eq!( + stored(&db, "00000000-0000-4000-8000-0000000000a1"), + ("00000000-0000-4000-8000-00000000c0de".to_string(), true) + ); assert_eq!(stored(&db, "s-default"), ("default".to_string(), false)); let pending: i32 = db .conn .query_row( - "SELECT pending_sync FROM stashes WHERE id = 's-work'", + "SELECT pending_sync FROM stashes WHERE id = '00000000-0000-4000-8000-0000000000a1'", [], |row| row.get(0), ) @@ -1744,14 +1792,21 @@ mod tests { #[test] fn a_context_deleted_on_another_device_takes_its_stashes_here_too() { let mut db = create_test_db(); - db.import_contexts(&[plain_context("work", false)]).unwrap(); - insert_raw_stash(&db, "s-work", Some("work")); + db.import_contexts(&[plain_context("00000000-0000-4000-8000-00000000c0de", false)]) + .unwrap(); + insert_raw_stash( + &db, + "00000000-0000-4000-8000-0000000000a1", + Some("00000000-0000-4000-8000-00000000c0de"), + ); - let deleted = db.import_contexts(&[plain_context("work", true)]).unwrap(); + let deleted = db + .import_contexts(&[plain_context("00000000-0000-4000-8000-00000000c0de", true)]) + .unwrap(); assert_eq!(deleted.len(), 1); assert!( - stored(&db, "s-work").1, + stored(&db, "00000000-0000-4000-8000-0000000000a1").1, "a stash in a deleted context is deleted" ); } @@ -2316,7 +2371,7 @@ mod tests { let mut db = create_test_db(); db.import_stashes(&vec![stash_with_updated_at( - "s-remote", + "00000000-0000-4000-8000-0000000000a2", "from elsewhere", Some(1_000), )]) @@ -2331,7 +2386,7 @@ mod tests { // And the placeholder ordering must not block the real one from being applied. let applied = db .import_positions(&[StashPosition { - id: "s-remote".to_string(), + id: "00000000-0000-4000-8000-0000000000a2".to_string(), position: -5.0, position_updated_at: 1_500, }]) @@ -2341,7 +2396,7 @@ mod tests { let position: f64 = db .conn .query_row( - "SELECT position FROM stashes WHERE id = 's-remote'", + "SELECT position FROM stashes WHERE id = '00000000-0000-4000-8000-0000000000a2'", [], |r| r.get(0), ) @@ -2524,6 +2579,94 @@ mod tests { assert_eq!(row.3, 0, "and must not queue the record for a push"); } + #[test] + fn a_synced_attachment_never_brings_a_local_path() { + // The upload pass reads `file_path` and sends the bytes to the server, so a path + // accepted from sync would let the server ask for any file on the machine. + let mut db = create_test_db(); + let id = "00000000-0000-4000-8000-0000000000d1"; + let mut stash = stash_with_updated_at(id, "x", Some(1_000)); + stash.attachments.push(Attachment { + id: "00000000-0000-4000-8000-0000000000d2".to_string(), + stash_id: id.to_string(), + file_path: "/home/user/.ssh/id_ed25519".to_string(), + file_name: "id_ed25519".to_string(), + file_size: 1, + mime_type: None, + syntax: None, + created_at: crate::time::now_iso(), + }); + db.import_stashes(&vec![stash]).unwrap(); + + let path: String = db + .conn + .query_row( + "SELECT file_path FROM attachments WHERE id = '00000000-0000-4000-8000-0000000000d2'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(path, ""); + } + + #[test] + fn synced_records_with_path_shaped_ids_are_refused() { + // A stash id became a cache directory name, so one pushed as `..\..\Startup` put + // its attachment in the Startup folder of every device that downloaded it. + let mut db = create_test_db(); + let good = "00000000-0000-4000-8000-0000000000b1"; + let mut traversal = stash_with_updated_at("..\\..\\..\\Startup", "x", Some(1_000)); + traversal.attachments.push(Attachment { + id: "00000000-0000-4000-8000-0000000000b2".to_string(), + stash_id: traversal.id.clone(), + file_path: String::new(), + file_name: "x.bat".to_string(), + file_size: 1, + mime_type: None, + syntax: None, + created_at: crate::time::now_iso(), + }); + let mut bad_context = stash_with_updated_at(good, "y", Some(1_000)); + bad_context.context_id = "../../.config/autostart".to_string(); + let mut bad_attachment = stash_with_updated_at(good, "z", Some(1_000)); + bad_attachment.attachments.push(Attachment { + id: "../escape".to_string(), + stash_id: good.to_string(), + file_path: String::new(), + file_name: "x".to_string(), + file_size: 1, + mime_type: None, + syntax: None, + created_at: crate::time::now_iso(), + }); + + db.import_stashes(&vec![traversal, bad_context]).unwrap(); + db.import_contexts(&[plain_context("..", false)]).unwrap(); + db.import_stashes(&vec![bad_attachment]).unwrap(); + + let stashes: i64 = db + .conn + .query_row( + "SELECT COUNT(*) FROM stashes WHERE id LIKE '%..%' OR context_id LIKE '%..%'", + [], + |r| r.get(0), + ) + .unwrap(); + let attachments: i64 = db + .conn + .query_row("SELECT COUNT(*) FROM attachments", [], |r| r.get(0)) + .unwrap(); + let contexts: i64 = db + .conn + .query_row("SELECT COUNT(*) FROM contexts WHERE id = '..'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(stashes, 0, "no path-shaped id is written"); + assert_eq!(attachments, 0, "an attachment with a bad id is dropped"); + assert_eq!(contexts, 0); + } + fn stash_with_updated_at(id: &str, content: &str, updated_at: Option) -> StashItem { StashItem { id: id.to_string(), @@ -2596,12 +2739,16 @@ mod tests { let mut db = create_test_db(); let server_ts = 1_700_000_000_u64; - let stash = stash_with_updated_at("from-server", "remote content", Some(server_ts)); + let stash = stash_with_updated_at( + "00000000-0000-4000-8000-0000000000a3", + "remote content", + Some(server_ts), + ); db.import_stashes(&vec![stash]) .expect("import should succeed"); assert_eq!( - stored_updated_at(&db, "from-server"), + stored_updated_at(&db, "00000000-0000-4000-8000-0000000000a3"), server_ts, "sync import must not restamp the server's timestamp" ); @@ -2616,7 +2763,7 @@ mod tests { let server_ts = 1_700_000_000_u64; let ctx = Context { - id: "ctx-remote".to_string(), + id: "00000000-0000-4000-8000-0000000000c3".to_string(), name: "Remote".to_string(), description: Some("Rust + Svelte".to_string()), rules: vec![], @@ -2630,7 +2777,7 @@ mod tests { let stored = db.get_contexts().expect("load should succeed"); let found = stored .iter() - .find(|c| c.id == "ctx-remote") + .find(|c| c.id == "00000000-0000-4000-8000-0000000000c3") .expect("context should be present"); assert_eq!(found.updated_at, Some(server_ts)); @@ -2850,19 +2997,26 @@ mod tests { // Otherwise every pulled record would bounce straight back, and the incremental // push would never shrink. let mut db = create_test_db(); - let stash = stash_with_updated_at("s-remote", "from another device", Some(1_700_000_000)); + let stash = stash_with_updated_at( + "00000000-0000-4000-8000-0000000000a2", + "from another device", + Some(1_700_000_000), + ); db.import_stashes(&vec![stash]) .expect("import should succeed"); - assert_eq!(pending_flag(&db, "stashes", "s-remote"), 0); + assert_eq!( + pending_flag(&db, "stashes", "00000000-0000-4000-8000-0000000000a2"), + 0 + ); // Scoped to this record: a fresh database also seeds starter stashes, which are // local creations and legitimately do need pushing. assert!( !db.claim_pending_stashes() .expect("claim") .iter() - .any(|s| s.id == "s-remote"), + .any(|s| s.id == "00000000-0000-4000-8000-0000000000a2"), "imported records are already in sync by definition" ); } @@ -2991,10 +3145,13 @@ mod tests { // And a pulled context is not queued. let mut remote = ctx.clone(); - remote.id = "c-remote".to_string(); + remote.id = "00000000-0000-4000-8000-0000000000c2".to_string(); remote.updated_at = Some(1_700_000_000); db.import_contexts(&[remote]).expect("import"); - assert_eq!(pending_flag(&db, "contexts", "c-remote"), 0); + assert_eq!( + pending_flag(&db, "contexts", "00000000-0000-4000-8000-0000000000c2"), + 0 + ); } #[test] diff --git a/src-tauri/src/e2ee_enrol.rs b/src-tauri/src/e2ee_enrol.rs index 5e3b907..2990312 100644 --- a/src-tauri/src/e2ee_enrol.rs +++ b/src-tauri/src/e2ee_enrol.rs @@ -134,6 +134,9 @@ async fn fetch_state( }; let state: ServerState = serde_json::from_value(body) .map_err(|e| format!("Could not read the account's encryption state: {}", e))?; + if state.state == "sealed" { + e2ee_session::mark_sealed(); + } Ok((state, user_id, device_id)) } diff --git a/src-tauri/src/e2ee_session.rs b/src-tauri/src/e2ee_session.rs index 833961b..8240d7e 100644 --- a/src-tauri/src/e2ee_session.rs +++ b/src-tauri/src/e2ee_session.rs @@ -60,6 +60,24 @@ static CONTENT_KEY: Mutex> = Mutex::new(None); /// Which generation of content key [`CONTENT_KEY`] is. static EPOCH: Mutex = Mutex::new(0); +/// Whether the server has said this account finished converting. +/// +/// While an account is `migrating`, plaintext and sealed records legitimately coexist, so +/// a plaintext field is left as it is. Once it is `sealed` nothing plaintext should ever +/// arrive again, and one that does is either a bug or a server injecting content it was +/// never able to seal - accepting it would let the server write into an encrypted account +/// at will. So the flag only ever goes one way within a session. +static SEALED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Record that the account is fully sealed. Never cleared, except by [`clear_content_key`]. +pub fn mark_sealed() { + SEALED.store(true, std::sync::atomic::Ordering::Relaxed); +} + +fn is_sealed() -> bool { + SEALED.load(std::sync::atomic::Ordering::Relaxed) +} + /// Where the device key pair lives, sealed by the same protection as every other local /// secret: the OS credential store, or the device passphrase where there is none. fn device_key_path() -> PathBuf { @@ -128,6 +146,7 @@ pub fn set_content_key(key: ContentKey, epoch: u32) { pub fn clear_content_key() { *lock_or_recover(&CONTENT_KEY) = None; *lock_or_recover(&EPOCH) = 0; + SEALED.store(false, std::sync::atomic::Ordering::Relaxed); } pub fn is_unlocked() -> bool { @@ -476,6 +495,10 @@ fn open_field( return Ok(()); }; if !envelope::is_envelope(value) { + if is_sealed() && !value.is_empty() { + // See `SEALED`: dropped like a record that will not open. + return Err("plaintext on an encrypted account".into()); + } // Plaintext, from an account part-way through converting. Leave it alone. return Ok(()); } @@ -589,6 +612,10 @@ pub fn open_attachment_metadata( use base64::{engine::general_purpose::STANDARD, Engine as _}; if !envelope::is_envelope(sealed) { + if is_sealed() { + // See `SEALED`. + return Err("plaintext attachment details on an encrypted account".into()); + } // Plaintext, from before this account was converted. Nothing to open. return Ok(None); } @@ -884,6 +911,29 @@ mod tests { }); } + /// Once the account is sealed, plaintext can only be content the server made up. + #[test] + fn plaintext_on_a_sealed_account_is_dropped() { + with_key(|| { + mark_sealed(); + let mut body = serde_json::json!({ + "synced": [ + { "id": "33333333-3333-4333-8333-333333333333", "content": "injected" }, + { "id": "44444444-4444-4444-8444-444444444444", "content": "" } + ] + }); + let unreadable = open_stash_response(&mut body, USER); + assert_eq!(unreadable.len(), 1); + assert_eq!( + body["synced"].as_array().unwrap().len(), + 1, + "a tombstone has no text" + ); + assert!(open_attachment_metadata("plain.txt", "a", USER).is_err()); + SEALED.store(false, std::sync::atomic::Ordering::Relaxed); + }); + } + /// The rule that matters most: a record this installation cannot open is dropped from /// the merge, never written locally with a placeholder. #[test] diff --git a/src-tauri/src/handover.rs b/src-tauri/src/handover.rs new file mode 100644 index 0000000..9aa7bad --- /dev/null +++ b/src-tauri/src/handover.rs @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Copyright (C) 2026 Nico Wiedemann +// +// This file is part of Stashpad. +// Stashpad is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License, version 3, +// as published by the Free Software Foundation. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +// See the GNU Affero General Public License for more details. + +//! Files the user handed over: dropped on the window, or picked in a file dialog. +//! +//! The commands that read or write an outside path used to take whatever path the webview +//! sent, and the webview could also read Downloads, Desktop and Documents itself through the +//! fs plugin. A script that got into the page - through a rendered stash, say - could +//! therefore copy any file the user can read into an attachment, and from there into sync. +//! +//! Now only the backend learns these paths: from the window's drop event, and from the file +//! dialogs, which run here rather than in the webview. Every command that touches an outside +//! path asks [`check`] first, so a path the user never handed over is refused however it +//! reaches the backend. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use serde::Deserialize; +use tauri::AppHandle; +use tauri_plugin_dialog::{DialogExt, FilePath}; + +use crate::uierror::UiError; + +/// More than any session hands over; past it the oldest choices simply stop counting. +const MAX_REMEMBERED: usize = 4096; + +static HANDED_OVER: OnceLock>> = OnceLock::new(); + +fn handed_over() -> &'static Mutex> { + HANDED_OVER.get_or_init(|| Mutex::new(HashSet::new())) +} + +/// The one spelling of a path that is compared: canonical where the file exists, and for a +/// save target that does not exist yet, its canonical folder plus the file name. +fn normalize(path: &Path) -> Option { + if let Ok(canonical) = path.canonicalize() { + return Some(canonical); + } + let name = path.file_name()?; + let parent = path.parent()?.canonicalize().ok()?; + Some(parent.join(name)) +} + +/// Remember paths the user handed over. +pub fn record(paths: I) +where + I: IntoIterator, + P: AsRef, +{ + let mut set = crate::state::lock_or_recover(handed_over()); + if set.len() > MAX_REMEMBERED { + set.clear(); + } + for path in paths { + if let Some(normalized) = normalize(path.as_ref()) { + set.insert(normalized); + } + } +} + +/// Whether the user handed this path over. +pub fn is_handed_over(path: &Path) -> bool { + match normalize(path) { + Some(normalized) => crate::state::lock_or_recover(handed_over()).contains(&normalized), + None => false, + } +} + +/// The path, if the user handed it over; otherwise the refusal every caller returns. +pub fn check(path: &str) -> Result { + let path = PathBuf::from(path); + if is_handed_over(&path) { + Ok(path) + } else { + log::warn!( + "Refused a path that was not dropped or picked: {}", + path.display() + ); + Err("Only files you dropped or picked can be used here".into()) + } +} + +/// A file type a dialog offers, as the frontend describes it. +#[derive(Deserialize)] +pub struct DialogFilter { + pub name: String, + pub extensions: Vec, +} + +fn into_paths(picked: Vec) -> Vec { + picked + .into_iter() + .filter_map(|p| p.into_path().ok()) + .collect() +} + +fn to_strings(paths: &[PathBuf]) -> Vec { + paths + .iter() + .map(|p| p.to_string_lossy().into_owned()) + .collect() +} + +/// Ask the user for files to open. What they pick may then be read; nothing else may. +#[tauri::command] +pub async fn pick_files( + app: AppHandle, + title: String, + filters: Option>, + multiple: bool, +) -> Result, UiError> { + let mut dialog = app.dialog().file().set_title(title); + for filter in filters.unwrap_or_default() { + let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect(); + dialog = dialog.add_filter(filter.name, &extensions); + } + // The dialog blocks until the user answers, so it waits on the blocking pool. + let picked = tauri::async_runtime::spawn_blocking(move || { + if multiple { + dialog.blocking_pick_files().unwrap_or_default() + } else { + dialog.blocking_pick_file().into_iter().collect() + } + }) + .await + .map_err(|e| format!("File dialog failed: {}", e))?; + + let paths = into_paths(picked); + record(&paths); + Ok(to_strings(&paths)) +} + +/// Ask the user where to save. Only the place they choose may then be written. +#[tauri::command] +pub async fn pick_save_path( + app: AppHandle, + title: String, + default_name: String, + filters: Option>, +) -> Result, UiError> { + let mut dialog = app + .dialog() + .file() + .set_title(title) + .set_file_name(default_name); + for filter in filters.unwrap_or_default() { + let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect(); + dialog = dialog.add_filter(filter.name, &extensions); + } + let picked = tauri::async_runtime::spawn_blocking(move || dialog.blocking_save_file()) + .await + .map_err(|e| format!("File dialog failed: {}", e))?; + + let Some(path) = picked.and_then(|p| p.into_path().ok()) else { + return Ok(None); + }; + record([&path]); + Ok(Some(path.to_string_lossy().into_owned())) +} + +/// The bytes of a file the user handed over - for resizing a dropped image before it is +/// saved. +#[tauri::command] +pub async fn read_handed_over_file(path: String) -> Result { + let path = check(&path)?; + let bytes = tokio::fs::read(&path) + .await + .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?; + Ok(tauri::ipc::Response::new(bytes)) +} + +/// The size of a file the user handed over or one in the attachment cache; `None` for any +/// other path, or one that is gone. +#[tauri::command] +pub async fn file_size(path: String) -> Option { + let path = PathBuf::from(path); + if !is_handed_over(&path) && !crate::utils::is_inside_cache(&path) { + return None; + } + tokio::fs::metadata(&path).await.ok().map(|m| m.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_recorded_paths_pass() { + let dir = tempfile::tempdir().unwrap(); + let picked = dir.path().join("picked.txt"); + let other = dir.path().join("other.txt"); + std::fs::write(&picked, b"x").unwrap(); + std::fs::write(&other, b"x").unwrap(); + + record([&picked]); + assert!(check(&picked.to_string_lossy()).is_ok()); + assert!(check(&other.to_string_lossy()).is_err()); + } + + #[test] + fn another_spelling_of_a_recorded_path_still_matches() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("sub")).unwrap(); + let file = dir.path().join("dropped.png"); + std::fs::write(&file, b"x").unwrap(); + + record([&file]); + let detour = dir.path().join("sub").join("..").join("dropped.png"); + assert!(is_handed_over(&detour)); + } + + #[test] + fn a_save_target_counts_before_it_exists() { + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("export.zip"); + + record([&target]); + assert!(is_handed_over(&target)); + assert!(!is_handed_over(&dir.path().join("elsewhere.zip"))); + } +} diff --git a/src-tauri/src/ids.rs b/src-tauri/src/ids.rs new file mode 100644 index 0000000..852373a --- /dev/null +++ b/src-tauri/src/ids.rs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Copyright (C) 2026 Nico Wiedemann +// +// This file is part of Stashpad. +// Stashpad is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License, version 3, +// as published by the Free Software Foundation. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +// See the GNU Affero General Public License for more details. + +//! The shape a record id must have before it is trusted. +//! +//! Ids arrive from places this device does not control - the sync server, another +//! device, an imported file - and some of them end up as directory names under +//! `~/.stashpad/cache`. An id of `..\..\Startup` would put an attachment wherever it +//! pointed, so an id that is not a UUID is refused at the door rather than cleaned up +//! wherever it happens to be used. + +/// A stash or attachment id: a hyphenated UUID, and nothing else. +/// +/// `Uuid::try_parse` alone also accepts the braced and `urn:uuid:` forms; the length check +/// limits it to the 36-character hyphenated one every client generates, so no `:` or +/// brace ever reaches a path. +pub fn is_record_id(id: &str) -> bool { + id.len() == 36 && uuid::Uuid::try_parse(id).is_ok() +} + +/// A context id: a record id, or the literal `default` context every account has. +pub fn is_context_id(id: &str) -> bool { + id == "default" || is_record_id(id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_hyphenated_uuids_only() { + assert!(is_record_id("0f8fad5b-d9cb-469f-a165-70867728950e")); + assert!(is_record_id("0F8FAD5B-D9CB-469F-A165-70867728950E")); + assert!(!is_record_id("0f8fad5bd9cb469fa16570867728950e")); + assert!(!is_record_id("{0f8fad5b-d9cb-469f-a165-70867728950e}")); + assert!(!is_record_id( + "urn:uuid:0f8fad5b-d9cb-469f-a165-70867728950e" + )); + assert!(!is_record_id("default")); + assert!(!is_record_id("")); + } + + #[test] + fn refuses_anything_that_could_walk_a_path() { + for id in [ + "..", + "../../../.config/autostart", + "..\\..\\..\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup", + "/etc", + "C:\\Windows", + "C:version.dll", + ] { + assert!(!is_record_id(id), "{id}"); + assert!(!is_context_id(id), "{id}"); + } + } + + #[test] + fn context_ids_also_allow_default() { + assert!(is_context_id("default")); + assert!(is_context_id("0f8fad5b-d9cb-469f-a165-70867728950e")); + assert!(!is_context_id("Default")); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 86c20cb..65a2d31 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -26,6 +26,7 @@ use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder}; use tauri::Manager; mod account_export; +mod ai; mod browser_drop; mod contexts; pub mod db; @@ -33,6 +34,8 @@ mod e2ee; mod e2ee_enrol; mod e2ee_session; mod envelope; +mod handover; +pub mod ids; mod keychain; mod localkey; mod logging; @@ -440,7 +443,6 @@ pub fn run() { .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_process::init()) .plugin(tauri_plugin_window_state::Builder::default().build()) - .plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_dialog::init()) @@ -508,6 +510,8 @@ pub fn run() { stashes::trigger_auto_cleanup, stashes::save_asset, stashes::save_asset_from_path, + ai::ai_enhance, + ai::ai_test_connection, stashes::delete_asset, stashes::read_file_for_preview, utils::show_in_folder, @@ -538,6 +542,10 @@ pub fn run() { account_export::read_account_export, account_export::import_account_export, account_export::export_whole_account, + handover::pick_files, + handover::pick_save_path, + handover::read_handed_over_file, + handover::file_size, utils::is_windows_10, contexts::get_contexts, contexts::save_contexts, @@ -585,6 +593,31 @@ pub fn run() { .build(tauri::generate_context!()) .expect("error while building tauri application") .run(|app_handle, event| { + // A drop is the user handing these files over; only they may be read later. + // Recorded here, before the webview hears of the drop. Enter carries the same + // paths, so they are known even before the drop lands. See handover.rs. + if let tauri::RunEvent::WindowEvent { + event: + tauri::WindowEvent::DragDrop( + tauri::DragDropEvent::Enter { paths, .. } + | tauri::DragDropEvent::Drop { paths, .. }, + ), + .. + } = &event + { + handover::record(paths); + } + if let tauri::RunEvent::WebviewEvent { + event: + tauri::WebviewEvent::DragDrop( + tauri::DragDropEvent::Enter { paths, .. } + | tauri::DragDropEvent::Drop { paths, .. }, + ), + .. + } = &event + { + handover::record(paths); + } if let tauri::RunEvent::Exit = event { log::info!("App exiting, cleaning up..."); cleanup_websocket_state(app_handle); diff --git a/src-tauri/src/models.rs b/src-tauri/src/models.rs index ed63377..68e55bf 100644 --- a/src-tauri/src/models.rs +++ b/src-tauri/src/models.rs @@ -258,6 +258,10 @@ pub struct AiConfig { pub model: String, #[serde(default)] pub preset_id: Option, + /// Whether a key is saved. Set only on the way out to the webview, which is never given + /// the key itself; ignored on the way in. + #[serde(default)] + pub has_api_key: bool, } pub fn default_clear_completed_strategy() -> String { diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index df11570..e4fe29c 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -377,6 +377,12 @@ pub async fn get_settings(state: State<'_, Arc>) -> Result Option { + if status != reqwest::StatusCode::FORBIDDEN { + return None; + } + let json: serde_json::Value = serde_json::from_str(body).ok()?; + match json["code"].as_str()? { + "subscription_required" => Some(UiError::new( + "cloud.subscription_required", + "Cloud sync needs a subscription.", + )), + "storage_full" => Some(UiError::new( + "cloud.storage_full", + "Your cloud storage is full.", + )), + _ => None, + } +} + fn error_snippet(body: &str) -> String { let snippet: String = body.chars().take(ERROR_SNIPPET_CHARS).collect(); if body.chars().nth(ERROR_SNIPPET_CHARS).is_some() { @@ -336,6 +360,9 @@ pub async fn sync_stashes_api( if !response.status().is_success() { let status = response.status(); let body = response.text().await.unwrap_or_default(); + if let Some(refusal) = coded_refusal(status, &body) { + return Err(refusal); + } let snippet = error_snippet(&body); return Err(format!("Stash sync failed ({}): {}", status, snippet).into()); } @@ -517,6 +544,17 @@ pub async fn upload_attachment_to_cloud( return Ok(false); } + // Only a file in the attachment cache is ever uploaded. A recorded path elsewhere did + // not come from this device, and a server that wanted `~/.ssh/id_ed25519` could + // otherwise name it and receive the bytes at a URL of its choosing. + if !crate::utils::is_inside_cache(std::path::Path::new(&attachment.file_path)) { + log::warn!( + "[Attachment] {} points outside the attachment cache; not uploading it", + attachment.id + ); + return Err("Attachment is not in the attachment cache".into()); + } + // The row and the file can disagree about how big the file is. Two attachments with // the same name used to be written to the same path, so the loser's row went on // recording the size of bytes that had since been overwritten - and the cloud confirms @@ -644,6 +682,9 @@ pub async fn upload_attachment_to_cloud( .map_err(|e| format!("Failed to read upload URL response: {}", e))?; if !status.is_success() { + if let Some(refusal) = coded_refusal(status, &resp_text) { + return Err(refusal); + } let msg = format!( "Cloud rejected upload request for {}: {} - {}", attachment.id, status, resp_text @@ -870,12 +911,34 @@ pub async fn download_attachment_from_cloud( }; // Mirror the layout save_asset uses so cleanup on delete keeps working. - let mut dir = get_app_dir().join("cache"); + // + // Every one of these ids came from sync, and each becomes part of a path: a stash id of + // `..\..\Startup` used to put the download in the Startup folder of every linked + // device. They are checked here as well as on import, because a row written before + // that check existed would otherwise still reach this join. + if !crate::ids::is_record_id(&stash_id) + || !crate::ids::is_record_id(&attachment_id) + || !context_id + .as_deref() + .map_or(true, crate::ids::is_context_id) + { + return Err("Attachment has a malformed id".into()); + } + let cache_root = get_app_dir().join("cache"); + let mut dir = cache_root.clone(); if let Some(cid) = context_id.as_deref() { dir = dir.join(cid); } dir = dir.join(&stash_id); fs::create_dir_all(&dir).map_err(|e| format!("Failed to create cache dir: {}", e))?; + // Belt and braces: whatever the ids were, the directory must still be inside the cache. + let inside_cache = match (dir.canonicalize(), cache_root.canonicalize()) { + (Ok(d), Ok(root)) => d.starts_with(root), + _ => false, + }; + if !inside_cache { + return Err("Attachment would be written outside the cache".into()); + } // Write to a temporary file and rename into place. A direct write that is // interrupted - crash, power loss, full disk - leaves a truncated file at the real @@ -983,6 +1046,9 @@ pub async fn sync_contexts_api( if !response.status().is_success() { let status = response.status(); let body = response.text().await.unwrap_or_default(); + if let Some(refusal) = coded_refusal(status, &body) { + return Err(refusal); + } let snippet = error_snippet(&body); return Err(format!("Context sync failed ({}): {}", status, snippet).into()); } @@ -1040,12 +1106,10 @@ pub async fn connect_websocket( .replace("http://", "ws://") .replace("https://", "wss://"); - // Append the token to the URL query string - let ws_url = format!( - "{}/ws?token={}", - ws_endpoint.trim_end_matches('/'), - urlencoding::encode(&token) - ); + // The token travels in the upgrade request's Authorization header. It used to be in + // the query string, where every proxy and CDN on the way could write it to a log. + let ws_url = format!("{}/ws", ws_endpoint.trim_end_matches('/')); + let bearer = format!("Bearer {}", token); // Spawn a persistent task for the WebSocket connection with reconnect logic let task_app = app.clone(); @@ -1078,16 +1142,22 @@ pub async fn connect_websocket( // TCP or TLS handshake never returns on its own, so the reconnect loop // stopped looping: the app kept believing a connection was pending and // fell back to the 15-minute poll, which reads as sync being broken. - let attempt = tokio::time::timeout(WS_CONNECT_TIMEOUT, connect_async(ws_url.clone())); - let connected = match attempt.await { - Ok(result) => result, - Err(_elapsed) => Err(tokio_tungstenite::tungstenite::Error::Io( - std::io::Error::new( - std::io::ErrorKind::TimedOut, - "WebSocket handshake timed out", - ), - )), - }; + let connected: Result<_, String> = async { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let mut request = ws_url + .as_str() + .into_client_request() + .map_err(|e| e.to_string())?; + let value = bearer + .parse() + .map_err(|_| "the token is not a valid header value".to_string())?; + request.headers_mut().insert("Authorization", value); + match tokio::time::timeout(WS_CONNECT_TIMEOUT, connect_async(request)).await { + Ok(result) => result.map_err(|e| e.to_string()), + Err(_elapsed) => Err("WebSocket handshake timed out".to_string()), + } + } + .await; match connected { Ok((ws_stream, _)) => { log::info!("[WebSocket] Connected successfully"); @@ -1295,6 +1365,23 @@ mod tests { ); } + #[test] + fn a_coded_storage_refusal_reaches_the_interface_as_a_code() { + let refused = coded_refusal( + reqwest::StatusCode::FORBIDDEN, + r#"{"error":"Cloud sync needs a subscription.","code":"subscription_required"}"#, + ) + .expect("a coded refusal"); + assert_eq!(refused.code, "cloud.subscription_required"); + assert!( + coded_refusal(reqwest::StatusCode::FORBIDDEN, r#"{"error":"suspended"}"#).is_none() + ); + assert!(coded_refusal( + reqwest::StatusCode::BAD_REQUEST, + r#"{"code":"subscription_required"}"# + ) + .is_none()); + } #[test] fn a_short_error_body_is_quoted_whole_and_unmarked() { let snippet = error_snippet("Bad Gateway"); @@ -1506,6 +1593,10 @@ async fn reencrypt_attachment( let plaintext = match source { PlaintextSource::Local(path) => { + // The same rule as an upload: these bytes leave the machine. + if !crate::utils::is_inside_cache(std::path::Path::new(&path)) { + return Err("Attachment is not in the attachment cache".into()); + } tauri::async_runtime::spawn_blocking(move || fs::read(path)) .await .map_err(|e| format!("Attachment read task failed: {}", e))? diff --git a/src-tauri/src/transfer.rs b/src-tauri/src/transfer.rs index 2d5fb27..2c347db 100644 --- a/src-tauri/src/transfer.rs +++ b/src-tauri/src/transfer.rs @@ -678,12 +678,17 @@ fn transfer_temp_root() -> PathBuf { } /// Reject an archive entry whose name would escape the directory it is extracted into. +/// +/// Only plain names are allowed. Rejecting `..` and a leading `/` was not enough on +/// Windows: an entry named `C:version.dll` has a drive prefix and no root, and +/// `base.join` *replaces* the base with it - a path relative to the process's working +/// directory on that drive, written during the preview, before anything was confirmed. fn safe_entry_path(base: &Path, name: &str) -> Option { let candidate = Path::new(name); - if candidate.components().any(|c| { + if !candidate.components().all(|c| { matches!( c, - std::path::Component::ParentDir | std::path::Component::RootDir + std::path::Component::Normal(_) | std::path::Component::CurDir ) }) { return None; @@ -696,7 +701,8 @@ fn safe_entry_path(base: &Path, name: &str) -> Option { // --------------------------------------------------------------------------- /// Write a context's stashes to `dest_path`, as a zip when attachments are included and -/// there is at least one, otherwise as a plain markdown file. +/// there is at least one, otherwise as a plain markdown file. `dest_path` has to be the +/// place the user chose in the save dialog - see handover.rs. #[tauri::command] pub async fn export_context_archive( state: State<'_, Arc>, @@ -704,6 +710,18 @@ pub async fn export_context_archive( stash_ids: Vec, include_attachments: bool, dest_path: String, +) -> Result { + crate::handover::check(&dest_path)?; + write_context_archive(state, context_id, stash_ids, include_attachments, dest_path).await +} + +/// [`export_context_archive`] without the check, for callers that chose the path themselves. +pub async fn write_context_archive( + state: State<'_, Arc>, + context_id: String, + stash_ids: Vec, + include_attachments: bool, + dest_path: String, ) -> Result { let wanted: HashSet = stash_ids.into_iter().collect(); @@ -876,7 +894,8 @@ pub async fn read_import_archive( path: String, context_id: String, ) -> Result { - let source = PathBuf::from(&path); + // Only an archive the user dropped or picked - see handover.rs. + let source = crate::handover::check(&path)?; if !source.exists() { return Err("File does not exist".into()); } @@ -991,6 +1010,12 @@ pub async fn commit_import( stashes: Vec, token: String, ) -> Result { + // The token names a directory that is removed recursively at the end, so it has to be + // the UUID `read_import_archive` issued - `..\..` would have deleted the home folder. + // `discard_import` already checked this; this command did not. + if Uuid::parse_str(&token).is_err() { + return Err("Invalid import token".into()); + } let temp_dir = transfer_temp_root().join(&token); // All the file copying happens on the blocking pool: an import can move hundreds of @@ -1469,5 +1494,18 @@ old let base = Path::new("/tmp/import"); assert!(safe_entry_path(base, "attachments/ok.png").is_some()); assert!(safe_entry_path(base, "../../etc/passwd").is_none()); + assert!(safe_entry_path(base, "/etc/passwd").is_none()); + } + + #[cfg(windows)] + #[test] + fn a_drive_prefixed_archive_entry_is_refused() { + // `C:version.dll` has a prefix and no root, so it slipped past a check for `..` + // and `/` while `join` threw the base away. + let base = Path::new("C:\\import"); + assert!(safe_entry_path(base, "C:version.dll").is_none()); + assert!(safe_entry_path(base, "C:\\Windows\\x.dll").is_none()); + assert!(safe_entry_path(base, "\\\\server\\share\\x").is_none()); + assert!(safe_entry_path(base, "attachments\\ok.png").is_some()); } } diff --git a/src-tauri/src/utils.rs b/src-tauri/src/utils.rs index 23982f1..00aaee6 100644 --- a/src-tauri/src/utils.rs +++ b/src-tauri/src/utils.rs @@ -81,6 +81,22 @@ TAGS: ) point to other stashes: copy every one EXACTLY, unchanged. "#; +/// Whether `path` resolves to a file inside `~/.stashpad/cache`. +/// +/// Every attachment Stashpad owns is copied into the cache before it is recorded, so a +/// recorded path anywhere else did not come from this device - and a path that arrived +/// through sync can name any file the user can read. Anything that reads a recorded path +/// to send its bytes somewhere asks this first. +pub fn is_inside_cache(path: &Path) -> bool { + match ( + path.canonicalize(), + get_app_dir().join("cache").canonicalize(), + ) { + (Ok(p), Ok(root)) => p.starts_with(root), + _ => false, + } +} + pub fn get_system_prompt_path() -> PathBuf { get_app_dir().join("enhancement_prompt.txt") } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index d7a1e0a..6d114a6 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "stashpad", - "version": "1.10.2", + "version": "1.11.0", "identifier": "org.stashpad", "build": { "frontendDist": "../dist", @@ -26,11 +26,12 @@ } ], "security": { - "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' asset: https://asset.localhost data: blob:; connect-src * ipc: http://ipc.localhost; font-src 'self' data:; media-src 'self' asset: https://asset.localhost", + "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' asset: https://asset.localhost data: blob:; connect-src ipc: http://ipc.localhost; font-src 'self' data:; media-src 'self' asset: https://asset.localhost; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'", + "devCsp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' asset: https://asset.localhost data: blob:; connect-src ipc: http://ipc.localhost ws://localhost:1420 http://localhost:1420; font-src 'self' data:; media-src 'self' asset: https://asset.localhost; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'", "assetProtocol": { "enable": true, "scope": [ - "$HOME/.stashpad/**/*" + "$HOME/.stashpad/cache/**/*" ] } } diff --git a/src/app.css b/src/app.css index 32ffe5b..4067ce8 100644 --- a/src/app.css +++ b/src/app.css @@ -338,8 +338,17 @@ white-space: nowrap; } -.stash-ref-completed .stash-ref-label { - text-decoration: line-through; +/* Done, not gone: the checkmark and the green of the complete button, readable as ever. + Strikethrough is for a stash that no longer exists. */ +.stash-ref-completed { + border-color: color-mix(in srgb, var(--color-green-500), transparent 60%); + background-color: color-mix(in srgb, var(--color-green-500), transparent 90%); + color: var(--color-green-500); +} + +.stash-ref-completed[role="link"]:hover, +.stash-ref-completed[role="link"]:focus-visible { + background-color: color-mix(in srgb, var(--color-green-500), transparent 80%); } .stash-ref-completed::before { @@ -359,6 +368,30 @@ cursor: default; } +.stash-ref-gone .stash-ref-label { + text-decoration: line-through; +} + +/* A word a search matched, in a stash card or a search result. */ +mark.search-hit { + background-color: color-mix(in srgb, var(--primary), transparent 60%); + color: inherit; + border-radius: 2px; + padding: 0 1px; +} + +/* The match the search's previous/next buttons are on. */ +mark.search-hit.search-hit-current { + background-color: var(--primary); + color: var(--primary-foreground); +} + +/* A match with no word to mark - in an attachment name, or a search result. */ +.search-hit-current:not(mark) { + border-radius: 0.5rem; + box-shadow: 0 0 0 2px var(--primary); +} + /* Brief highlight on a stash revealed by clicking a reference to it. */ .stash-ref-target { border-radius: 0.5rem; diff --git a/src/lib/components/CloudAuthModal.svelte b/src/lib/components/CloudAuthModal.svelte index b98df25..38651f5 100644 --- a/src/lib/components/CloudAuthModal.svelte +++ b/src/lib/components/CloudAuthModal.svelte @@ -81,14 +81,24 @@ * Falls back to the API endpoint's /account/home route if the endpoint does * not follow the expected pattern. */ + /** + * A fresh random value for each time this dialog opens. The browser carries it to the + * account page and back in the `stashpad://` link, and a link without it is ignored. + * Any page the user happened to visit while the dialog was open could otherwise fire + * its own `stashpad://auth/callback?token=…` and link this app to someone else's + * account, sending its stashes there. + */ + let linkNonce = $state(""); + function getAccountUrl(): string { const endpoint = settings.cloudConfig?.endpoint; if (!endpoint) return ""; const origin = websiteOriginFromEndpoint(endpoint); + const query = `action=link-desktop&nonce=${encodeURIComponent(linkNonce)}`; return origin - ? `${origin}/account?action=link-desktop` - : `${endpoint}/account/home?action=link-desktop`; + ? `${origin}/account?${query}` + : `${endpoint}/account/home?${query}`; } /** @@ -177,6 +187,11 @@ try { const parsedUrl = new URL(url); const token = parsedUrl.searchParams.get("token"); + // Only the link that carries this dialog's nonce; see `linkNonce`. + if (!linkNonce || parsedUrl.searchParams.get("nonce") !== linkNonce) { + log.warn("[CloudAuthModal] Ignoring a sign-in link this dialog did not ask for"); + continue; + } if (token) { linkCode = token; exchangeLinkCode(); @@ -214,6 +229,7 @@ linkCode = ""; linkCodeError = null; linkCodeLoading = false; + linkNonce = crypto.randomUUID(); openBrowser(); } }); diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index 81495d8..c0013e4 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -59,8 +59,7 @@ import { onMount, onDestroy, untrack, tick } from "svelte"; import { findStashAtPosition, findEditorAtPosition } from "$lib/stores/drag-state.svelte"; - import { stat } from "@tauri-apps/plugin-fs"; - import { open, message } from "@tauri-apps/plugin-dialog"; + import { message } from "@tauri-apps/plugin-dialog"; import { checkAttachmentSizeLimits, calculateTotalAttachmentSize, @@ -71,7 +70,6 @@ import { resizeImage, getAttachmentKind } from "$lib/utils/files"; import { reportError } from "$lib/utils/error-reporting"; import { errorText } from "$lib/errors"; - import { readFile } from "@tauri-apps/plugin-fs"; import { log } from "$lib/utils/log"; let { @@ -280,7 +278,7 @@ if (resizeImages && isImage) { try { // Read the file manually to resize it - const data = await readFile(path); + const data = await adapter.readHandedOverFile(path); const blob = new Blob([data], { type: "image/jpeg" }); // mime type guess, resizeImage handles check // resizeImage expects File or Blob. @@ -1151,13 +1149,9 @@ async function handleAddFile() { try { - const selected = await open({ - multiple: true, - title: $_("editor.selectFilesTitle"), - }); - if (selected) { - // selected can be a string or string[] depending on multiple option - const paths = Array.isArray(selected) ? selected : [selected]; + // The backend opens the dialog, so it knows these files were picked - see handover.rs. + const paths = await adapter.pickFiles($_("editor.selectFilesTitle"), true); + if (paths.length > 0) { for (const path of paths) { try { const attachment = await adapter.saveAssetFromPath( @@ -1370,7 +1364,7 @@ }} > {candidate.completed ? "✓" : "→"} - {refLabel(candidate.content)} diff --git a/src/lib/components/ExportDialog.svelte b/src/lib/components/ExportDialog.svelte index 7980366..c4e1aa1 100644 --- a/src/lib/components/ExportDialog.svelte +++ b/src/lib/components/ExportDialog.svelte @@ -8,8 +8,6 @@ import { compareTimestamps, localTimeZone, now } from "$lib/utils/time"; import { portal } from "$lib/actions/portal"; import { trapFocus } from "$lib/actions/trapFocus"; - import { save } from "@tauri-apps/plugin-dialog"; - import { stat } from "@tauri-apps/plugin-fs"; import { DesktopStorageAdapter } from "$lib/services/desktop-adapter"; import { attachmentSync } from "$lib/stores/attachment-sync.svelte"; import { errorCode, errorText } from "$lib/errors"; @@ -106,7 +104,7 @@ (s.attachments || []).map((a) => a.fileSize || 0), ); - // Legacy files still need stat() calls + // Legacy files have no stored size, so the backend measures them const legacyFilePaths = selectedStashes.flatMap((s) => s.files || []); if (attachmentSizes.length === 0 && legacyFilePaths.length === 0) { @@ -122,13 +120,12 @@ return; } - // Only use stat() for legacy files + // Only measure legacy files isCalculatingSize = true; Promise.all( legacyFilePaths.map(async (filePath) => { try { - const info = await stat(filePath); - return info.size; + return (await adapter.fileSize(filePath)) ?? 0; } catch { return 0; } @@ -198,13 +195,14 @@ const time = `${String(local.hour).padStart(2, "0")}-${String(local.minute).padStart(2, "0")}`; const defaultFileName = `${safeName}_${date}_${time}.${asZip ? "zip" : "md"}`; - const filePath = await save({ - title: $_("contexts.exportTitle"), - defaultPath: defaultFileName, - filters: asZip + // The backend opens the dialog, and writes only where the user chose - see handover.rs. + const filePath = await adapter.pickSavePath( + $_("contexts.exportTitle"), + defaultFileName, + asZip ? [{ name: $_("contexts.exportDialog.zipFilter"), extensions: ["zip"] }] : [{ name: $_("contexts.exportDialog.markdownFilter"), extensions: ["md"] }], - }); + ); if (!filePath) return; diff --git a/src/lib/components/ImportDialog.svelte b/src/lib/components/ImportDialog.svelte index 27e488e..a4f40a5 100644 --- a/src/lib/components/ImportDialog.svelte +++ b/src/lib/components/ImportDialog.svelte @@ -8,7 +8,6 @@ import { compareTimestamps } from "$lib/utils/time"; import { portal } from "$lib/actions/portal"; import { trapFocus } from "$lib/actions/trapFocus"; - import { open as openFile } from "@tauri-apps/plugin-dialog"; import { getCurrentWebview } from "@tauri-apps/api/webview"; import { onDestroy } from "svelte"; import type { @@ -196,19 +195,16 @@ * Open file picker and load file */ async function selectFile() { - const filePath = await openFile({ - title: $_("contexts.importDialog.selectFile"), - filters: [ - { - name: $_("contexts.importDialog.fileFilter"), - extensions: ["md", "zip"], - }, - ], - }); + // The backend opens the dialog, so it knows this file was picked - see handover.rs. + const [filePath] = await adapter.pickFiles( + $_("contexts.importDialog.selectFile"), + false, + [{ name: $_("contexts.importDialog.fileFilter"), extensions: ["md", "zip"] }], + ); if (!filePath) return; - await loadFromPath(filePath as string); + await loadFromPath(filePath); } /** diff --git a/src/lib/components/Queue.svelte b/src/lib/components/Queue.svelte index be52f37..93d331e 100644 --- a/src/lib/components/Queue.svelte +++ b/src/lib/components/Queue.svelte @@ -53,6 +53,9 @@ Video, FileText, File as FileIcon, + Search, + X, + ChevronUp, } from "lucide-svelte"; import { tooltip } from "$lib/actions/tooltip"; import { @@ -62,9 +65,18 @@ } from "$lib/utils/stash-filters"; import { parseRefIds, + refLabel, resolveRef, type ResolvedRef, } from "$lib/utils/stash-refs"; + import { + buildSearchIndex, + searchStashes, + segments, + snippets, + type SearchHits, + } from "$lib/utils/stash-search"; + import { liveAttachments } from "$lib/utils/stash-filters"; import { reportError } from "$lib/utils/error-reporting"; import { log } from "$lib/utils/log"; @@ -204,11 +216,323 @@ selectedTags.length > 0 || selectedAttachmentFilters.length > 0, ); + // Search. Cmd/Ctrl+F opens it on this context; pressing it again searches every + // context. It looks through what the page cannot show - collapsed completed stashes, + // the hidden part of long cards, AI-enhanced text, attachment names. + const isMacPlatform = navigator.platform.includes("Mac"); + const searchShortcut = isMacPlatform ? "⌘F" : "Ctrl+F"; + let searchOpen = $state(false); + let searchQuery = $state(""); + let searchScope = $state<"context" | "all">("context"); + let searchInput = $state(); + + // `stashes` holds every context, so one index serves both scopes. + let searchIndex = $derived(buildSearchIndex(stashes)); + // The query the search runs on: what was typed, once typing pauses. Every search + // re-renders the cards it touches, so one per keystroke made typing stutter. + let appliedQuery = $state(""); + $effect(() => { + const query = searchQuery; + const timer = setTimeout(() => (appliedQuery = query), 150); + return () => clearTimeout(timer); + }); + // Two letters at least: a single one prefix-matches nearly every stash, and marking + // and unfolding all of them froze the window. + const MIN_QUERY = 2; + let searching = $derived( + searchOpen && appliedQuery.trim().length >= MIN_QUERY, + ); + let searchHits = $derived( + searching ? searchStashes(searchIndex, appliedQuery) : new Map(), + ); + let searchingEverywhere = $derived(searching && searchScope === "all"); + + /** Tag, attachment or search filters - anything that hides part of the queue. */ + let isFiltering = $derived(hasActiveFilters || searching); + + function passes(stash: StashItem): boolean { + return ( + (!hasActiveFilters || + matchesFilters(stash, selectedTags, selectedAttachmentFilters)) && + (!searching || searchHits.has(stash.id)) + ); + } + + /** + * Matches across every context, grouped by context, best first. Groups are ordered by + * their best match, not with the current context first: opening a result switches the + * context, and the list - and every position in it - must not reshuffle because of it. + */ + let globalResults = $derived.by(() => { + if (!searchingEverywhere) return []; + const byId = new Map(stashes.map((s) => [s.id, s])); + const groups = new Map< + string, + { contextId: string; items: { item: StashItem; terms: string[] }[] } + >(); + for (const [id, terms] of searchHits) { + const item = byId.get(id); + if (!item || item.deleted) continue; + const contextId = item.contextId || "default"; + if (!groups.has(contextId)) groups.set(contextId, { contextId, items: [] }); + groups.get(contextId)!.items.push({ item, terms }); + } + return [...groups.values()]; + }); + + /** + * A result's lines of context, one per match: from the text, else the enhanced text, + * else a file name - the same place its card shows, so the counts agree. + */ + function resultSnippets(item: StashItem, terms: string[]) { + const sources = [ + item.content, + item.enhancedContent ?? "", + liveAttachments(item) + .map((a) => a.fileName) + .join(", "), + ]; + const text = + sources.find((t) => segments(t, terms).some((seg) => seg.hit)) ?? + item.content; + return snippets(text, terms); + } + + async function openSearch(scope: "context" | "all" = "context") { + searchOpen = true; + searchScope = scope; + await tick(); + searchInput?.focus(); + searchInput?.select(); + } + + function closeSearch() { + searchOpen = false; + searchQuery = ""; + appliedQuery = ""; + searchScope = "context"; + } + + /** Shared by every card the search did not match, so none of them re-renders. */ + const NO_TERMS: string[] = []; + + /** Whether a card in this context is hidden by the search. */ + function hiddenBySearch(stash: StashItem): boolean { + return searching && !searchingEverywhere && !searchHits.has(stash.id); + } + + // Previous/next, like a browser's find: through every marked word in this context's + // cards - or the card itself, when its match is in something not shown, such as an + // attachment name - and through the results when searching everywhere. + let searchTargets = $state([]); + let searchCurrent = $state(-1); + + function collectSearchTargets(): HTMLElement[] { + if (!scrollContainer) return []; + if (searchingEverywhere) { + const targets: HTMLElement[] = []; + for (const result of scrollContainer.querySelectorAll( + "[data-search-result]", + )) { + const marks = result.querySelectorAll("mark.search-hit"); + if (marks.length > 0) targets.push(...marks); + else targets.push(result); + } + return targets; + } + const targets: HTMLElement[] = []; + // The list items only: the card inside each carries the id too. + for (const card of scrollContainer.querySelectorAll( + '[role="listitem"][data-stash-id]', + )) { + if (!searchHits.has(card.dataset.stashId ?? "")) continue; + const marks = card.querySelectorAll("mark.search-hit"); + if (marks.length > 0) targets.push(...marks); + else targets.push(card); + } + return targets; + } + + function goToSearchTarget(index: number) { + for (const el of scrollContainer?.querySelectorAll(".search-hit-current") ?? []) { + el.classList.remove("search-hit-current"); + } + const count = searchTargets.length; + if (count === 0) { + searchCurrent = -1; + return; + } + searchCurrent = ((index % count) + count) % count; + const el = searchTargets[searchCurrent]; + el.classList.add("search-hit-current"); + el.scrollIntoView({ behavior: "smooth", block: "center" }); + } + + /** Move to the next (1) or previous (-1) match, from wherever the last one was. */ + function stepSearch(delta: 1 | -1) { + // Cards re-render as they are edited or synced, so the marks are found afresh and + // the position kept by element where it still exists. + const previous = searchTargets[searchCurrent]; + searchTargets = collectSearchTargets(); + const at = previous ? searchTargets.indexOf(previous) : -1; + goToSearchTarget( + at >= 0 ? at + delta : searchCurrent < 0 ? (delta > 0 ? 0 : -1) : searchCurrent, + ); + } + + /** A stash opened from an all-contexts search: the count starts at its matches. */ + let searchFocusId: string | null = null; + /** Where the all-contexts results were when a result was opened, to return to. */ + let savedEverywhere: { query: string; index: number } | null = null; + + // A new query, scope or context starts the count again - at the first match, or at + // the stash just opened from a result - once the cards have marked theirs (they do + // that a tick after rendering). The context matters on its own: opening a result in + // another one switches the scope first, while the results are still on screen, and + // the context only after. + $effect(() => { + searchHits; + searchScope; + currentContextId; + if (!searching) { + searchTargets = []; + searchCurrent = -1; + return; + } + let cancelled = false; + tick() + .then(() => tick()) + .then(() => + requestAnimationFrame(() => { + if (cancelled) return; + searchTargets = collectSearchTargets(); + const focus = searchFocusId; + const at = focus + ? searchTargets.findIndex((el) => + el.closest('[role="listitem"][data-stash-id]')?.getAttribute("data-stash-id") === focus, + ) + : -1; + if (at >= 0) searchFocusId = null; + // Back on "All" for the same search: where it was left, not the top. + const back = + searchingEverywhere && savedEverywhere?.query === appliedQuery + ? savedEverywhere.index + : -1; + goToSearchTarget(back >= 0 ? back : Math.max(at, 0)); + }), + ); + return () => { + cancelled = true; + }; + }); + + /** Open the result the previous/next buttons are on, when searching everywhere. */ + function openCurrentResult() { + const id = searchTargets[searchCurrent] + ?.closest("[data-search-result]") + ?.dataset.searchResult; + const item = stashes.find((s) => s.id === id) ?? globalResults[0]?.items[0]?.item; + if (item) openResult(item); + } + + /** + * Cmd/Ctrl+F: open on this context; again, while in the field, switch scope. + * F3 and Cmd/Ctrl+G step through the matches, Shift going back. + */ + function handleSearchShortcut(e: KeyboardEvent) { + const mod = isMacPlatform ? e.metaKey : e.ctrlKey; + if ( + searchOpen && + searching && + !e.altKey && + (e.key === "F3" || (mod && e.key.toLowerCase() === "g")) + ) { + e.preventDefault(); + stepSearch(e.shiftKey ? -1 : 1); + return; + } + if (!mod || e.shiftKey || e.altKey || e.key.toLowerCase() !== "f") return; + e.preventDefault(); + if (!searchOpen) { + openSearch("context"); + } else if (document.activeElement !== searchInput) { + searchInput?.focus(); + searchInput?.select(); + } else { + searchScope = searchScope === "context" ? "all" : "context"; + } + } + + function handleSearchKeydown(e: KeyboardEvent) { + if (e.key === "Escape") { + e.preventDefault(); + closeSearch(); + } else if (e.key === "Enter" && searchingEverywhere && !e.shiftKey) { + e.preventDefault(); + openCurrentResult(); + } else if (e.key === "Enter") { + e.preventDefault(); + stepSearch(e.shiftKey ? -1 : 1); + } else if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + stepSearch(e.key === "ArrowDown" ? 1 : -1); + } + } + + /** Go to a stash found by an all-contexts search, in its own context. */ + function openResult(item: StashItem) { + // The result opened, clicked or stepped to: its first match is where to return. + const current = searchTargets[searchCurrent] + ?.closest("[data-search-result]") + ?.dataset.searchResult; + const index = + current === item.id + ? searchCurrent + : searchTargets.findIndex( + (el) => + el.closest("[data-search-result]")?.dataset + .searchResult === item.id, + ); + savedEverywhere = { query: appliedQuery, index: Math.max(index, 0) }; + searchFocusId = item.id; + searchScope = "context"; + const contextId = item.contextId || "default"; + if (contextId !== (currentContextId || "default")) { + pendingRevealId = item.id; + onSwitchContext?.(contextId); + return; + } + revealStash(item.id); + } + + // A search matching completed stashes shows them, rather than a count behind a fold, + // and folds them away again when it ends - left open, closing the search rendered + // every completed stash at once. + let collapsedBeforeSearch: boolean | null = null; + $effect(() => { + if (searching && filteredCompletedStashes.length > 0) { + untrack(() => { + collapsedBeforeSearch ??= completedCollapsed; + completedCollapsed = false; + }); + } else if (!searching) { + untrack(() => { + if (collapsedBeforeSearch !== null) { + completedCollapsed = collapsedBeforeSearch; + collapsedBeforeSearch = null; + } + }); + } + }); + let showFilterButton = $derived( availableTags.length > 0 || availableAttachmentFilters.length > 0, ); // Filtered Active Stashes + // Tag and attachment filters only. The search hides the active stashes it does not + // match instead (see hiddenBySearch): unmounting and re-creating every card when it + // closed is what froze the window. let filteredStashes = $derived.by(() => { if (!hasActiveFilters) return activeStashes; return activeStashes.filter((stash) => @@ -216,12 +540,15 @@ ); }); + let visibleActiveCount = $derived( + filteredStashes.filter((s) => !s.isDndShadowItem && !hiddenBySearch(s)) + .length, + ); + // Filtered Completed Stashes let filteredCompletedStashes = $derived.by(() => { - if (!hasActiveFilters) return completedStashes; - return completedStashes.filter((stash) => - matchesFilters(stash, selectedTags, selectedAttachmentFilters), - ); + if (!isFiltering) return completedStashes; + return completedStashes.filter(passes); }); $effect(() => { @@ -326,6 +653,7 @@ selectedTags = []; selectedAttachmentFilters = []; } + if (searching && !searchHits.has(id)) searchQuery = ""; if (target.completed) completedCollapsed = false; await tick(); @@ -702,6 +1030,8 @@ let unlistenLeave: UnlistenFn | null = null; onMount(async () => { + window.addEventListener("keydown", handleSearchShortcut); + // Listen for Tauri's native drag events to coordinate StashCard drop zones unlistenEnter = await listen<{ position: { x: number; y: number } }>( "tauri://drag-enter", @@ -782,6 +1112,7 @@ }); onDestroy(() => { + window.removeEventListener("keydown", handleSearchShortcut); unlistenEnter?.(); unlistenOver?.(); unlistenLeave?.(); @@ -790,6 +1121,104 @@
+ + {#if searchOpen} +
+
+
+ + +
+ {#if searching} + + {searchTargets.length > 0 + ? `${searchCurrent + 1}/${searchTargets.length}` + : "0/0"} + +
+ + +
+ {/if} +
+ {#each [["context", $_("queue.search.scopeContext")], ["all", $_("queue.search.scopeAll")]] as [scope, label] (scope)} + + {/each} +
+ +
+
+ {/if}
{/if} + + + {#if showFilterButton} + {/each} +
+ {:else} +
+ {$_("queue.search.noResults")} +
+ {/each} +
+ {:else}
{/if}
{/each} - {#if filteredStashes.filter((s) => !s.isDndShadowItem).length === 0} + {#if visibleActiveCount === 0}
- {hasActiveFilters - ? $_("queue.noActiveStashesFound") - : $_("queue.noActiveStashes")} + {searching && !hasActiveFilters + ? $_("queue.search.noActive") + : isFiltering + ? $_("queue.noActiveStashesFound") + : $_("queue.noActiveStashes")}
{/if} + {/if} - {#if filteredCompletedStashes.length > 0 || (completedStashes.length > 0 && !hasActiveFilters)} + {#if !searchingEverywhere && (filteredCompletedStashes.length > 0 || (completedStashes.length > 0 && !isFiltering))}
- {$_("queue.completed")} ({hasActiveFilters + {$_("queue.completed")} ({isFiltering ? filteredCompletedStashes.length : completedStashes.length}) @@ -1142,6 +1640,7 @@ onReferenceClick={followRef} {refCandidates} {autoDetectedWindowTitle} + searchTerms={searchHits.get(item.id) ?? NO_TERMS} />
{/each} diff --git a/src/lib/components/Settings.svelte b/src/lib/components/Settings.svelte index 9e7657c..1120eb9 100644 --- a/src/lib/components/Settings.svelte +++ b/src/lib/components/Settings.svelte @@ -1621,7 +1621,9 @@ { if (settings.aiConfig) { diff --git a/src/lib/components/StashCard.svelte b/src/lib/components/StashCard.svelte index 31310a8..841e2d3 100644 --- a/src/lib/components/StashCard.svelte +++ b/src/lib/components/StashCard.svelte @@ -29,6 +29,8 @@ checkAttachmentSizeLimits, } from "$lib/utils/format"; import { fade, fly } from "svelte/transition"; + import { tick } from "svelte"; + import { highlight } from "$lib/utils/stash-search"; import { dragHandle } from "svelte-dnd-action"; import { Circle, @@ -55,8 +57,7 @@ import Editor from "./Editor.svelte"; import FilePreviewTooltip from "./FilePreviewTooltip.svelte"; import FilePreviewModal from "./FilePreviewModal.svelte"; - import { stat } from "@tauri-apps/plugin-fs"; - import { open, message } from "@tauri-apps/plugin-dialog"; + import { message } from "@tauri-apps/plugin-dialog"; import { getRelativeTime } from "$lib/utils/date"; import { safeParse, @@ -105,6 +106,7 @@ contextName, onReferenceClick, refCandidates = [], + searchTerms = [], } = $props<{ item: StashItem; mode: "Drag" | "Copy"; @@ -136,6 +138,8 @@ onReferenceClick?: (ref: ResolvedRef) => void; /** Stashes the editor's `>>` picker offers */ refCandidates?: StashItem[]; + /** Words a search matched in this stash: shown marked, and the card unclamped */ + searchTerms?: string[]; }>(); const adapter = new DesktopStorageAdapter(); @@ -193,7 +197,18 @@ let contentHeight = $state(0); let expanded = $state(false); let isLong = $derived(contentHeight > COLLAPSED_MAX_PX + COLLAPSE_SLACK_PX); - let isClamped = $derived(isLong && !expanded); + // A search match may sit below the fold, so a matched card shows all of itself. + let isClamped = $derived(isLong && !expanded && searchTerms.length === 0); + + // Re-marked whenever the rendered content or the search changes; the marks go in + // after the content is rendered, as text, never through the HTML. + $effect(() => { + renderedContent; + const terms = searchTerms; + const el = contentRef; + if (!el) return; + tick().then(() => highlight(el, terms)); + }); $effect(() => { if (!contentRef) return; @@ -439,12 +454,9 @@ */ async function handleAddFile() { try { - const selected = await open({ - multiple: true, - title: "Select files to attach", - }); - if (selected) { - const paths = Array.isArray(selected) ? selected : [selected]; + // The backend opens the dialog, so it knows these files were picked - see handover.rs. + const paths = await adapter.pickFiles($_("editor.selectFilesTitle"), true); + if (paths.length > 0) { let newAttachments = [...item.attachments]; const currentTotal = calculateTotalAttachmentSize(item.attachments); @@ -453,9 +465,9 @@ for (const path of paths) { try { // Check size limits - const metadata = await stat(path); + const size = (await adapter.fileSize(path)) ?? 0; const results = checkAttachmentSizeLimits( - metadata.size, + size, currentTotal + plannedAddition, ); @@ -490,7 +502,7 @@ } // If check passes, track the size - plannedAddition += metadata.size; + plannedAddition += size; const attachment = await adapter.saveAssetFromPath( path, diff --git a/src/lib/components/StashRefPreview.svelte b/src/lib/components/StashRefPreview.svelte index 57330ee..ba3672a 100644 --- a/src/lib/components/StashRefPreview.svelte +++ b/src/lib/components/StashRefPreview.svelte @@ -89,7 +89,12 @@ {#snippet children()}
{status} {#if attachmentCount > 0} @@ -104,7 +109,7 @@
{@html previewHtml} diff --git a/src/lib/i18n/locales/de.json b/src/lib/i18n/locales/de.json index 4bbdd00..354dae0 100644 --- a/src/lib/i18n/locales/de.json +++ b/src/lib/i18n/locales/de.json @@ -158,7 +158,8 @@ "label": "API-Schlüssel", "description": "Dein API-Schlüssel (optional)", "show": "API-Schlüssel anzeigen", - "hide": "API-Schlüssel verbergen" + "hide": "API-Schlüssel verbergen", + "savedPlaceholder": "Gespeichert - zum Ersetzen eintippen" }, "model": { "label": "Modellname", @@ -434,6 +435,21 @@ "noActiveStashes": "Keine aktiven Stashes", "noActiveStashesFound": "Keine aktiven Stashes mit diesen Filtern gefunden.", "filterStashes": "Stashes filtern", + "search": { + "open": "Suchen ({shortcut})", + "label": "Stashes durchsuchen", + "placeholder": "Diesen Kontext durchsuchen…", + "placeholderAll": "Alle Kontexte durchsuchen…", + "scope": "Suchen in", + "scopeContext": "Dieser Kontext", + "scopeAll": "Alle", + "close": "Suche schließen", + "previous": "Vorheriger Treffer (Umschalt+Enter)", + "next": "Nächster Treffer (Enter)", + "position": "Treffer {current} von {total}", + "noResults": "Kein Stash passt zu deiner Suche.", + "noActive": "Kein aktiver Stash passt zu deiner Suche." + }, "attachmentFilter": { "any": "Beliebiger Anhang", "none": "Keine Anhänge", @@ -602,6 +618,10 @@ "taken": "Eine andere App verwendet dieses Tastenkürzel bereits. Wähle ein anderes.", "failed": "Dieses Tastenkürzel konnte nicht eingerichtet werden: {reason}", "invalid": "Dieses Tastenkürzel kann nicht verwendet werden. Wähle ein anderes." + }, + "cloud": { + "subscription_required": "Für die Cloud-Synchronisierung brauchst du ein Abo. Du kannst es in den Einstellungen abschließen.", + "storage_full": "Dein Cloud-Speicher ist voll. Entferne Anhänge oder erweitere dein Abo, um mehr hinzuzufügen." } } } diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 11e1997..a50192f 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -158,7 +158,8 @@ "label": "API Key", "description": "Your API key (optional)", "show": "Show API key", - "hide": "Hide API key" + "hide": "Hide API key", + "savedPlaceholder": "Saved - type to replace" }, "model": { "label": "Model Name", @@ -442,6 +443,21 @@ "sortNewest": "Date: Newest first", "stashAdded": "Stash added", "filterStashes": "Filter stashes", + "search": { + "open": "Search ({shortcut})", + "label": "Search stashes", + "placeholder": "Search this context…", + "placeholderAll": "Search all contexts…", + "scope": "Search in", + "scopeContext": "This context", + "scopeAll": "All", + "close": "Close search", + "previous": "Previous match (Shift+Enter)", + "next": "Next match (Enter)", + "position": "Match {current} of {total}", + "noResults": "No stash matches your search.", + "noActive": "No active stash matches your search." + }, "attachmentFilter": { "any": "Any attachment", "none": "No attachments", @@ -602,6 +618,10 @@ "taken": "Another app already uses this shortcut. Choose a different one.", "failed": "This shortcut couldn't be set up: {reason}", "invalid": "This shortcut can't be used. Choose a different one." + }, + "cloud": { + "subscription_required": "Cloud Sync needs a subscription. You can upgrade under Settings.", + "storage_full": "Your cloud storage is full. Remove attachments or upgrade to add more." } } } diff --git a/src/lib/i18n/locales/zh.json b/src/lib/i18n/locales/zh.json index d45f05f..30befee 100644 --- a/src/lib/i18n/locales/zh.json +++ b/src/lib/i18n/locales/zh.json @@ -158,7 +158,8 @@ "label": "API 密钥", "description": "你的 API 密钥(可选)", "show": "显示 API 密钥", - "hide": "隐藏 API 密钥" + "hide": "隐藏 API 密钥", + "savedPlaceholder": "已保存 - 输入以替换" }, "model": { "label": "模型名称", @@ -442,6 +443,21 @@ "sortNewest": "日期:最新的在前", "stashAdded": "已添加暂存项", "filterStashes": "筛选暂存项", + "search": { + "open": "搜索({shortcut})", + "label": "搜索暂存项", + "placeholder": "在当前上下文中搜索…", + "placeholderAll": "在所有上下文中搜索…", + "scope": "搜索范围", + "scopeContext": "当前上下文", + "scopeAll": "全部", + "close": "关闭搜索", + "previous": "上一个匹配项(Shift+Enter)", + "next": "下一个匹配项(Enter)", + "position": "第 {current} 个,共 {total} 个匹配项", + "noResults": "没有与你的搜索匹配的暂存项。", + "noActive": "没有与你的搜索匹配的活动暂存项。" + }, "attachmentFilter": { "any": "有附件", "none": "无附件", @@ -602,6 +618,10 @@ "taken": "其他应用已在使用此快捷键。请选择其他快捷键。", "failed": "无法设置此快捷键:{reason}", "invalid": "无法使用此快捷键。请选择其他快捷键。" + }, + "cloud": { + "subscription_required": "云同步需要订阅。你可以在设置中升级。", + "storage_full": "你的云存储空间已满。请删除一些附件,或升级以获得更多空间。" } } } diff --git a/src/lib/services/ai-service.svelte.ts b/src/lib/services/ai-service.svelte.ts index 33f1781..0b36797 100644 --- a/src/lib/services/ai-service.svelte.ts +++ b/src/lib/services/ai-service.svelte.ts @@ -173,53 +173,16 @@ Use this context to make the prompt more specific and relevant to the project. return await adapter.appleIntelligenceEnhance(content, systemPrompt); } - // API key is optional if (!config.endpoint || !config.model) { throw new Error('AI configuration is incomplete'); } - // Build the API URL - const url = `${config.endpoint.replace(/\/$/, '')}/chat/completions`; - - // Prepare the request body - const body = { - model: config.model, - messages: [ - { role: 'system', content: systemPrompt }, - { role: 'user', content: `\n${content}\n` }, - ], - temperature: 0.3, // Lower temperature for more consistent, focused output - max_tokens: 1024, // Reduced since we want concise output - stream: false, - }; - - // Build headers - only add Authorization if API key is provided - const headers: Record = { - 'Content-Type': 'application/json', - }; - if (config.apiKey) { - headers['Authorization'] = `Bearer ${config.apiKey}`; - } - - // Make the API request - const response = await fetch(url, { - method: 'POST', - headers, - body: JSON.stringify(body), - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error(`API error: ${response.status} - ${errorText}`); - } - - const data = await response.json(); - - // Extract the enhanced content from the response - let enhancedContent = data.choices?.[0]?.message?.content; - if (!enhancedContent) { - throw new Error('No content in API response'); - } + // The backend makes the request with the saved endpoint, model and key - the key is + // never handed to this webview. See ai.rs. + let enhancedContent = await adapter.aiEnhance( + systemPrompt, + `\n${content}\n`, + ); // Post-process to ensure no hallucinated tag headers if original had none const originalTags = content.match(/#[\w-]+/g); @@ -247,42 +210,18 @@ Use this context to make the prompt more specific and relevant to the project. return true; } - // API key is optional if (!config.endpoint || !config.model) { throw new Error('Configuration is incomplete'); } - const url = `${config.endpoint.replace(/\/$/, '')}/chat/completions`; - - const body = { + // What the form shows, which may not be saved yet. An empty key means the saved one, + // and the backend only pairs that with the saved endpoint. + await adapter.aiTestConnection({ + endpoint: config.endpoint, model: config.model, - messages: [ - { role: 'system', content: 'You are a connection tester.' }, - { role: 'user', content: 'Say "OK" to confirm the connection works.' }, - ], - max_tokens: 10, - stream: false, - }; - - // Build headers - only add Authorization if API key is provided - const headers: Record = { - 'Content-Type': 'application/json', - }; - if (config.apiKey) { - headers['Authorization'] = `Bearer ${config.apiKey}`; - } - - const response = await fetch(url, { - method: 'POST', - headers, - body: JSON.stringify(body), + apiKey: config.apiKey ?? '', }); - if (!response.ok) { - const errorText = await response.text(); - throw new Error(`${response.status}: ${errorText}`); - } - return true; } } diff --git a/src/lib/services/cloud-sync.ts b/src/lib/services/cloud-sync.ts index a0f1672..9ecf7d8 100644 --- a/src/lib/services/cloud-sync.ts +++ b/src/lib/services/cloud-sync.ts @@ -29,7 +29,7 @@ import type { IStorageService, StashItem, Context, CloudConfig, Settings, StashPosition } from '../types'; import { listen, type UnlistenFn } from '@tauri-apps/api/event'; import { attachmentSync } from '../stores/attachment-sync.svelte'; -import { errorText } from "$lib/errors"; +import { errorCode, errorText } from "$lib/errors"; import { fromEpochMs, nowIso, nowMs, toEpochMs } from "$lib/utils/time"; import { log } from '$lib/utils/log'; @@ -797,6 +797,17 @@ export class CloudSyncService { return true; } catch (error) { const message = errorText(error); + if (errorCode(error) === 'cloud.subscription_required') { + // The server no longer counts this account as entitled - a subscription + // that lapsed while the device stayed linked. Re-read the tier so + // `shouldSync()` stops the cycle and Settings shows the upgrade option, + // rather than failing the same way every few minutes. + log.warn('[CloudSync] Cloud storage is not part of this account any more'); + await this.refreshEntitlement(); + if (this.settings) this.updateSettings(this.settings); + this.setStatus('error', message); + return false; + } log.error('[CloudSync] Sync failed:', message); this.setStatus(this.isAuthError(message) ? 'auth-error' : 'error', message); return false; diff --git a/src/lib/services/desktop-adapter.ts b/src/lib/services/desktop-adapter.ts index 3a774b0..c34af9e 100644 --- a/src/lib/services/desktop-adapter.ts +++ b/src/lib/services/desktop-adapter.ts @@ -13,7 +13,7 @@ import { invoke } from '@tauri-apps/api/core'; import type { LogLevel } from '../utils/log'; -import type { IStorageService, StashItem, AppContext, Settings, FilePreviewData, Context, Attachment, CloudConfig, ExportSummary, ImportPreview, CloudUsage, StashPosition, LocalKeyStatus, E2eeStatus, E2eeEnableResult, E2eeConversionProgress, CreatedAccessKey, AttachmentConversion } from '../types'; +import type { IStorageService, StashItem, AppContext, Settings, FilePreviewData, Context, Attachment, CloudConfig, ExportSummary, ImportPreview, CloudUsage, StashPosition, LocalKeyStatus, E2eeStatus, E2eeEnableResult, E2eeConversionProgress, CreatedAccessKey, AttachmentConversion, FileFilter } from '../types'; import { log } from '$lib/utils/log'; /** Called after any local write so cloud sync can be scheduled. */ @@ -330,6 +330,31 @@ export class DesktopStorageAdapter implements IStorageService { return invoke('apple_intelligence_enhance', { content, systemPrompt }); } + async aiEnhance(systemPrompt: string, userContent: string): Promise { + return invoke('ai_enhance', { systemPrompt, userContent }); + } + + async aiTestConnection(test: { endpoint: string; model: string; apiKey: string }): Promise { + await invoke('ai_test_connection', { test }); + } + + async pickFiles(title: string, multiple: boolean, filters?: FileFilter[]): Promise { + return await invoke('pick_files', { title, multiple, filters: filters ?? null }); + } + + async pickSavePath(title: string, defaultName: string, filters?: FileFilter[]): Promise { + return await invoke('pick_save_path', { title, defaultName, filters: filters ?? null }); + } + + async readHandedOverFile(path: string): Promise> { + const bytes = await invoke('read_handed_over_file', { path }); + return new Uint8Array(bytes); + } + + async fileSize(path: string): Promise { + return await invoke('file_size', { path }); + } + async getSystemPrompt(): Promise { return await invoke('get_system_prompt'); } diff --git a/src/lib/types.ts b/src/lib/types.ts index 7ad7905..4b809a6 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -82,6 +82,9 @@ export interface AIConfig { model: string; /** Which preset was used, if any */ presetId?: string; + /** Whether a key is saved. The backend never sends the key itself: it makes the + * provider requests, so `apiKey` only ever holds what was just typed. */ + hasApiKey?: boolean; } /** Configuration for Stashpad Cloud sync */ @@ -159,6 +162,12 @@ export interface AttachmentConversion { unrecoverable: number; } +/** A file type a dialog offers. */ +export interface FileFilter { + name: string; + extensions: string[]; +} + export interface IStorageService { saveStash(stash: StashItem, options?: { invertPosition?: boolean }): Promise; saveStashes(stashes: StashItem[]): Promise; @@ -280,6 +289,18 @@ export interface IStorageService { // Apple Intelligence checkAppleIntelligenceAvailable(): Promise; appleIntelligenceEnhance(content: string, systemPrompt: string): Promise; + /** Ask the saved AI provider; the backend holds the endpoint, model and key. */ + aiEnhance(systemPrompt: string, userContent: string): Promise; + /** Test the provider the settings form shows. An empty key means the saved one, which + * the backend only uses for the saved endpoint. */ + aiTestConnection(test: { endpoint: string; model: string; apiKey: string }): Promise; + // Files the user hands over. The backend only reads or writes outside paths that came + // from a drop or from these dialogs - see handover.rs. + pickFiles(title: string, multiple: boolean, filters?: FileFilter[]): Promise; + pickSavePath(title: string, defaultName: string, filters?: FileFilter[]): Promise; + readHandedOverFile(path: string): Promise>; + /** Size of a handed-over file or one in the attachment cache; null for anything else. */ + fileSize(path: string): Promise; // AI System Prompt management getSystemPrompt(): Promise; getSystemPromptPath(): Promise; diff --git a/src/lib/utils/__tests__/markdown.test.ts b/src/lib/utils/__tests__/markdown.test.ts index de90651..ba34514 100644 --- a/src/lib/utils/__tests__/markdown.test.ts +++ b/src/lib/utils/__tests__/markdown.test.ts @@ -146,5 +146,22 @@ describe('markdown utilities', () => { const result = safeParse('file#utils and foo#bar'); expect(result).not.toContain('class="ai-tag"'); }); + + it('should never turn a link title into markup', () => { + // Badges are added after sanitizing. Finding text by splitting the HTML on + // `<[^>]*>` broke on a `>` inside an attribute: the badge closed the title and + // the rest of it came out as live elements. + const result = safeParse('[x](https://a "q> #foo INJ")'); + const doc = new DOMParser().parseFromString(result, 'text/html'); + expect(doc.querySelector('img')).toBeNull(); + expect(doc.querySelector('b')).toBeNull(); + expect(doc.querySelector('a')?.getAttribute('title')).toContain('#foo'); + }); + + it('should still badge a tag inside link text', () => { + const result = safeParse('[see #docs](https://example.com)'); + const doc = new DOMParser().parseFromString(result, 'text/html'); + expect(doc.querySelector('a .ai-tag')?.textContent).toBe('docs'); + }); }); }); diff --git a/src/lib/utils/__tests__/stash-refs.test.ts b/src/lib/utils/__tests__/stash-refs.test.ts index 3ff314e..d216fd4 100644 --- a/src/lib/utils/__tests__/stash-refs.test.ts +++ b/src/lib/utils/__tests__/stash-refs.test.ts @@ -66,7 +66,7 @@ describe('refLabel / makeRefLink', () => { it('truncates long lines', () => { const label = refLabel('x'.repeat(200)); - expect(label.length).toBeLessThanOrEqual(60); + expect(label.length).toBeLessThanOrEqual(42); expect(label.endsWith('…')).toBe(true); }); diff --git a/src/lib/utils/__tests__/stash-search.test.ts b/src/lib/utils/__tests__/stash-search.test.ts new file mode 100644 index 0000000..8844d5e --- /dev/null +++ b/src/lib/utils/__tests__/stash-search.test.ts @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Copyright (C) 2026 Nico Wiedemann +// +// This file is part of Stashpad. +// Stashpad is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License, version 3, +// as published by the Free Software Foundation. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +// See the GNU Affero General Public License for more details. + +import { describe, it, expect } from 'vitest'; +import type { StashItem } from '$lib/types'; +import { buildSearchIndex, searchStashes, segments, snippets, highlight } from '../stash-search'; + +function stash(id: string, content: string, extra: Partial = {}): StashItem { + return { + id, + content, + contextId: 'default', + completed: false, + createdAt: '2026-10-11T00:00:00Z', + attachments: [], + ...extra, + } as StashItem; +} + +const stashes = [ + stash('a', 'Fix the parser crash on empty input'), + stash('b', 'Deploy the website', { completed: true }), + stash('c', 'Notes', { enhancedContent: 'Investigate the memory leak in sync' }), + stash('d', 'Screenshot', { + attachments: [{ id: 'x', fileName: 'invoice-october.pdf' } as StashItem['attachments'][number]], + }), + stash('e', 'Gone parser', { deleted: true }), + stash('f', 'See [the parser one](stash:00000000-0000-4000-8000-000000000001)'), +]; + +const ids = (query: string) => [...searchStashes(buildSearchIndex(stashes), query).keys()]; + +describe('searchStashes', () => { + it('finds words anywhere, completed stashes included, deleted ones not', () => { + expect(ids('website')).toEqual(['b']); + expect(ids('parser').sort()).toEqual(['a', 'f']); + }); + + it('forgives a typo in a longer word, and finds a word while it is typed', () => { + expect(ids('parsor')).toContain('a'); + expect(ids('depolyment')).toEqual([]); + expect(ids('wbesite')).toEqual([]); + expect(ids('octobr')).toEqual(['d']); + expect(ids('webs')).toEqual(['b']); + }); + + it('requires every word', () => { + expect(ids('parser crash')).toEqual(['a']); + expect(ids('parser website')).toEqual([]); + }); + + it('looks in the enhanced text and in attachment names', () => { + expect(ids('leak')).toEqual(['c']); + expect(ids('invoice')).toEqual(['d']); + }); + + it('leaves out a sealed attachment name that is still waiting for its file', () => { + const sealed = stash('s', 'Report', { + attachments: [{ id: 'y', fileName: 'SPE1.abc.secretname' } as StashItem['attachments'][number]], + }); + expect([...searchStashes(buildSearchIndex([sealed]), 'secretname').keys()]).toEqual([]); + expect([...searchStashes(buildSearchIndex([sealed]), 'report').keys()]).toEqual(['s']); + }); + + it('does not match the id behind a stash link', () => { + expect(ids('000000000001')).toEqual([]); + }); + + it('reports the words that matched, for highlighting', () => { + const hits = searchStashes(buildSearchIndex(stashes), 'pars'); + expect(hits.get('a')).toEqual(['parser']); + }); + + it('finds nothing for an empty query', () => { + expect(ids(' ')).toEqual([]); + }); +}); + +describe('segments and snippet', () => { + it('splits out whole matched words, ignoring case', () => { + expect(segments('Parser, parsers and PARSER', ['parser'])).toEqual([ + { text: 'Parser', hit: true }, + { text: ', parsers and ', hit: false }, + { text: 'PARSER', hit: true }, + ]); + }); + + it('gives each match one line, sharing a line when matches are close', () => { + const text = 'lorem '.repeat(60) + 'needle needle ' + 'ipsum '.repeat(60) + 'needle'; + const lines = snippets(text, ['needle'], 60); + expect(lines).toHaveLength(2); + const hitCount = lines.flat().filter((p) => p.hit).length; + expect(hitCount).toBe(3); + expect(lines[0].map((p) => p.text).join('').startsWith('…')).toBe(true); + }); + + it('falls back to the opening when the text itself has no match', () => { + const lines = snippets('Screenshot of the bug', ['invoice']); + expect(lines).toEqual([[{ text: 'Screenshot of the bug', hit: false }]]); + }); +}); + +describe('highlight', () => { + it('marks matched words in text only, and undoes an earlier search', () => { + const root = document.createElement('div'); + root.innerHTML = '

Fix the parser crash

'; + highlight(root, ['parser']); + expect(root.innerHTML).toBe('

Fix the parser crash

'); + + highlight(root, ['crash']); + expect(root.innerHTML).toBe('

Fix the parser crash

'); + + highlight(root, []); + expect(root.innerHTML).toBe('

Fix the parser crash

'); + }); + + it('never turns text into markup', () => { + const root = document.createElement('div'); + root.textContent = ' parser'; + highlight(root, ['parser']); + expect(root.querySelector('img')).toBeNull(); + expect(root.querySelector('mark')?.textContent).toBe('parser'); + }); +}); diff --git a/src/lib/utils/markdown.ts b/src/lib/utils/markdown.ts index c28a9ca..f30e0d8 100644 --- a/src/lib/utils/markdown.ts +++ b/src/lib/utils/markdown.ts @@ -275,7 +275,7 @@ export function sanitizeHtml(html: string): string { // Table attributes 'align', 'valign', 'colspan', 'rowspan', // Misc - 'id', 'name', 'open', + 'open', ], // Allow data: URIs for base64 images but not javascript: ALLOW_DATA_ATTR: false, @@ -283,55 +283,81 @@ export function sanitizeHtml(html: string): string { }); } +const TAG_PATTERN = /(^|[^a-zA-Z0-9_])(#[\w-]+)/g; + +/** + * The badge markup for one `#tag` or `#hex`. `fullTag` only ever matches `#[\w-]+`, so it + * cannot carry markup of its own; the rest is constant. + */ +function badgeHtml(fullTag: string): string { + if (isHexColor(fullTag)) { + return ( + `` + + `` + + `${fullTag}` + + `` + ); + } + + const label = fullTag.slice(1); + const h = getTagHue(fullTag); + const style = [ + `--tag-bg: hsla(${h}, 75%, 45%, 0.1)`, + `--tag-bg-dark: hsla(${h}, 80%, 70%, 0.1)`, + `--tag-border: hsla(${h}, 75%, 45%, 0.2)`, + `--tag-border-dark: hsla(${h}, 80%, 70%, 0.2)`, + `--tag-text: hsl(${h}, 75%, 45%)`, + `--tag-text-dark: hsl(${h}, 80%, 70%)`, + ].join('; '); + + return `${HASH_ICON_SVG}${label}`; +} + /** * Replace #tag and #hex occurrences in sanitized HTML with badges. - * Ensures we don't match inside HTML tags (like href anchors). + * + * This runs after DOMPurify on purpose: the badge carries an SVG icon and inline CSS + * variables that the sanitizer would strip. It used to find text by splitting the + * serialized HTML on `<[^>]*>`, which assumes `>` never appears inside an attribute - and + * a link title can hold one. The split then landed mid-attribute, the inserted badge + * closed it, and whatever followed in the title became live markup. So it now parses the + * sanitized HTML and touches text nodes only, which by construction never sit inside a tag. + * Text inside `
` and `` is left alone, as before.
  */
 function injectBadges(html: string): string {
-    // 1. Split by blocks that we MUST NOT touch (pre, code)
-    const blocks = html.split(/(|)/gi);
+    const template = document.createElement('template');
+    template.innerHTML = html;
 
-    return blocks.map((block, i) => {
-        if (i % 2 === 1) return block; // It's pre/code, return as is
-
-        // 2. Split the remaining HTML by any HTML tag to avoid matching in attributes
-        const segments = block.split(/(<[^>]*>)/g);
-        return segments.map((segment, j) => {
-            if (j % 2 === 1) return segment; // It's an HTML tag like 
+    const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_TEXT);
+    const textNodes: Text[] = [];
+    for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+        if (!(node as Text).parentElement?.closest('pre, code')) {
+            textNodes.push(node as Text);
+        }
+    }
 
-            // 3. Process text nodes
-            return segment.replace(/(^|[^a-zA-Z0-9_])(#[\w-]+)/g, (match, prefix, fullTag) => {
-                if (isHexColor(fullTag)) {
-                    // Return ColorBadge HTML
-                    return (
-                        prefix +
-                        `` +
-                        `` +
-                        `${fullTag}` +
-                        ``
-                    );
-                }
+    for (const node of textNodes) {
+        const text = node.data;
+        TAG_PATTERN.lastIndex = 0;
+        if (!TAG_PATTERN.test(text)) continue;
+        TAG_PATTERN.lastIndex = 0;
 
-                const label = fullTag.slice(1);
-                const h = getTagHue(fullTag);
-                const style = [
-                    `--tag-bg: hsla(${h}, 75%, 45%, 0.1)`,
-                    `--tag-bg-dark: hsla(${h}, 80%, 70%, 0.1)`,
-                    `--tag-border: hsla(${h}, 75%, 45%, 0.2)`,
-                    `--tag-border-dark: hsla(${h}, 80%, 70%, 0.2)`,
-                    `--tag-text: hsl(${h}, 75%, 45%)`,
-                    `--tag-text-dark: hsl(${h}, 80%, 70%)`,
-                ].join('; ');
+        const fragment = document.createDocumentFragment();
+        let last = 0;
+        for (const match of text.matchAll(TAG_PATTERN)) {
+            const [, prefix, fullTag] = match;
+            const tagStart = (match.index ?? 0) + prefix.length;
+            fragment.append(text.slice(last, tagStart));
+            const badge = document.createElement('template');
+            badge.innerHTML = badgeHtml(fullTag);
+            fragment.append(badge.content);
+            last = tagStart + fullTag.length;
+        }
+        fragment.append(text.slice(last));
+        node.replaceWith(fragment);
+    }
 
-                return (
-                    prefix +
-                    `` +
-                    `${HASH_ICON_SVG}${label}` +
-                    ``
-                );
-            });
-        }).join('');
-    }).join('');
+    return template.innerHTML;
 }
 
 /**
diff --git a/src/lib/utils/stash-refs.ts b/src/lib/utils/stash-refs.ts
index 1ed73e8..f706a4f 100644
--- a/src/lib/utils/stash-refs.ts
+++ b/src/lib/utils/stash-refs.ts
@@ -32,7 +32,7 @@ export const STASH_REF_PATTERN =
     /\[([^\]\n]*)\]\(stash:([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\)/g;
 
 /** Longest label written into a new link. */
-const LABEL_MAX = 60;
+const LABEL_MAX = 42;
 
 /**
  * Where a reference points, from the point of view of the stash holding it.
diff --git a/src/lib/utils/stash-search.ts b/src/lib/utils/stash-search.ts
new file mode 100644
index 0000000..04667fc
--- /dev/null
+++ b/src/lib/utils/stash-search.ts
@@ -0,0 +1,197 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+
+// Copyright (C) 2026 Nico Wiedemann
+//
+// This file is part of Stashpad.
+// Stashpad is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License, version 3,
+// as published by the Free Software Foundation.
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+// See the GNU Affero General Public License for more details.
+
+import MiniSearch from "minisearch";
+import type { StashItem } from "$lib/types";
+import { STASH_REF_PATTERN } from "./stash-refs";
+import { liveAttachments } from "./stash-filters";
+
+/**
+ * Search over stashes.
+ *
+ * The webview's find-in-page could not do this: it only sees what is rendered, and a
+ * queue hides most of its text - completed stashes are collapsed away and long cards are
+ * clamped. This searches the stashes themselves: their text, the AI-enhanced version and
+ * the names of their attachments, with typos and unfinished words forgiven.
+ */
+
+interface SearchDoc {
+    id: string;
+    content: string;
+    enhanced: string;
+    files: string;
+}
+
+/** Matches, best first: each stash id with the words in it that matched. */
+export type SearchHits = Map;
+
+/**
+ * An attachment synced to an encrypted account keeps its sealed details in the name
+ * until its file is downloaded, which is when the real name is written back. That
+ * envelope is not a name anyone searches for. See `is_envelope` in envelope.rs.
+ */
+const SEALED_PREFIX = "SPE1.";
+
+/** How words are split, for the index and for highlighting alike. */
+const WORD = /[\p{L}\p{N}_]+/gu;
+
+function tokenize(text: string): string[] {
+    return text.match(WORD) ?? [];
+}
+
+/** A link reads as its label: the id behind it is not something anyone searches for. */
+function readable(text: string | undefined): string {
+    return (text ?? "").replace(STASH_REF_PATTERN, "$1");
+}
+
+export function buildSearchIndex(stashes: StashItem[]): MiniSearch {
+    const index = new MiniSearch({
+        fields: ["content", "enhanced", "files"],
+        tokenize,
+        searchOptions: {
+            tokenize,
+            // Every word has to be found, so each one narrows the result.
+            combineWith: "AND",
+            // "pars" finds "parser" while it is being typed.
+            prefix: true,
+            // A typo in a word of five letters, two from eight - a swapped pair of
+            // letters counts as two. Shorter words have to be exact, or they match
+            // everything.
+            fuzzy: (term) => (term.length >= 8 ? 2 : term.length >= 5 ? 1 : false),
+            boost: { content: 2 },
+        },
+    });
+    index.addAll(
+        stashes
+            .filter((s) => !s.deleted && !s.isDndShadowItem)
+            .map((s) => ({
+                id: s.id,
+                content: readable(s.content),
+                enhanced: readable(s.enhancedContent),
+                files: liveAttachments(s)
+                    .map((a) => a.fileName)
+                    .filter((name) => !name.startsWith(SEALED_PREFIX))
+                    .join(" "),
+            })),
+    );
+    return index;
+}
+
+export function searchStashes(index: MiniSearch, query: string): SearchHits {
+    const hits: SearchHits = new Map();
+    if (!query.trim()) return hits;
+    for (const result of index.search(query)) {
+        hits.set(String(result.id), result.terms);
+    }
+    return hits;
+}
+
+/** A piece of text, and whether it is one of the words that matched. */
+export interface Segment {
+    text: string;
+    hit: boolean;
+}
+
+/** Split text into matched words and the rest between them. */
+export function segments(text: string, terms: string[]): Segment[] {
+    const wanted = new Set(terms.map((t) => t.toLowerCase()));
+    const out: Segment[] = [];
+    let last = 0;
+    for (const match of text.matchAll(WORD)) {
+        if (!wanted.has(match[0].toLowerCase())) continue;
+        const at = match.index ?? 0;
+        if (at > last) out.push({ text: text.slice(last, at), hit: false });
+        out.push({ text: match[0], hit: true });
+        last = at + match[0].length;
+    }
+    if (last < text.length) out.push({ text: text.slice(last), hit: false });
+    return out;
+}
+
+/**
+ * Lines of context around every matched word, for a result list: one line per stretch of
+ * text, so several matches close together share a line. Each match shows up exactly once,
+ * which keeps the count of a result the same as in its card. When nothing in the text
+ * matched - the match was in an attachment name, say - the opening of the text instead.
+ */
+export function snippets(text: string, terms: string[], length = 120): Segment[][] {
+    const flat = readable(text).replace(/\s+/g, " ").trim();
+    const wanted = new Set(terms.map((t) => t.toLowerCase()));
+    const hits = [...flat.matchAll(WORD)]
+        .filter((m) => wanted.has(m[0].toLowerCase()))
+        .map((m) => ({ at: m.index ?? 0, end: (m.index ?? 0) + m[0].length }));
+
+    const cut = (start: number, end: number) =>
+        segments(
+            (start > 0 ? "…" : "") + flat.slice(start, end) + (end < flat.length ? "…" : ""),
+            terms,
+        );
+    if (hits.length === 0) return [cut(0, Math.min(flat.length, length))];
+
+    const lines: Segment[][] = [];
+    let i = 0;
+    while (i < hits.length) {
+        let start = Math.max(0, hits[i].at - Math.floor(length / 3));
+        if (start > 0) {
+            // Start on a word, not in the middle of one.
+            const space = flat.indexOf(" ", start);
+            start = space >= 0 && space < hits[i].at ? space + 1 : start;
+        }
+        let end = Math.min(flat.length, start + length);
+        // Every match that fits wholly on this line belongs to it; the line is stretched
+        // to the end of the last one rather than cutting a word in half.
+        let j = i;
+        while (j + 1 < hits.length && hits[j + 1].end <= end) j++;
+        end = Math.max(end, hits[j].end);
+        lines.push(cut(start, end));
+        i = j + 1;
+    }
+    return lines;
+}
+
+const MARK_CLASS = "search-hit";
+
+/**
+ * Mark the matched words in rendered content, after taking out the marks a previous
+ * search left. Text only - code, links and badges keep their structure, and nothing is
+ * parsed, so content cannot be turned into markup this way.
+ */
+export function highlight(root: HTMLElement, terms: string[]): void {
+    for (const mark of Array.from(root.querySelectorAll(`mark.${MARK_CLASS}`))) {
+        mark.replaceWith(document.createTextNode(mark.textContent ?? ""));
+    }
+    root.normalize();
+    if (terms.length === 0) return;
+
+    const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+    const nodes: Text[] = [];
+    for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+        nodes.push(node as Text);
+    }
+    for (const node of nodes) {
+        const parts = segments(node.data, terms);
+        if (!parts.some((p) => p.hit)) continue;
+        const fragment = document.createDocumentFragment();
+        for (const part of parts) {
+            if (part.hit) {
+                const mark = document.createElement("mark");
+                mark.className = MARK_CLASS;
+                mark.textContent = part.text;
+                fragment.append(mark);
+            } else {
+                fragment.append(part.text);
+            }
+        }
+        node.replaceWith(fragment);
+    }
+}
diff --git a/vite.config.ts b/vite.config.ts
index e8e0483..68ac2b8 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -36,7 +36,6 @@ export default defineConfig({
                     'vendor-tauri': [
                         '@tauri-apps/api',
                         '@tauri-apps/plugin-dialog',
-                        '@tauri-apps/plugin-fs',
                         '@tauri-apps/plugin-autostart',
                     ],
                     // Internationalization