diff --git a/.dockerignore b/.dockerignore index 04e509cd3..b6764a50f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,5 +14,16 @@ TODO.md !README.md # Sibling projects / test harness - not part of the webmail image examples/ +# Unit tests: `next build` type-checks every .ts file, and some tests import +# routes the Dockerfile deletes (app/api/dev-jmap). The Dockerfile deletes the +# tests as well, since a remote Git context skips this file. +**/__tests__ +**/*.test.ts +**/*.test.tsx integration/ +repos/ +# Runtime state of a checkout that has been run (admin password hash, +# plugin signing key, audit log, synced settings) - never part of an image +data/ +local-data/ **/node_modules diff --git a/.env.example b/.env.example index 649e542de..2f6739e3a 100644 --- a/.env.example +++ b/.env.example @@ -28,7 +28,9 @@ JMAP_SERVER_URL=https://your-jmap-server.com # Offer several JMAP servers on the login form. JSON array; each entry needs # id, label, and url. "domains" and a per-server "oauth" block are optional. # Prefer configuring this from the admin dashboard - the env form exists for -# stateless deployments. +# stateless deployments. An "oauth" block with both "clientId" and +# "buttonLabel" gives that server its own sign-in button on the login page, +# even while OAuth is off globally. # JMAP_SERVERS=[{"id":"eu","label":"Europe","url":"https://eu.example.com","domains":["example.com"]},{"id":"us","label":"US","url":"https://us.example.com","oauth":{"clientId":"webmail-us"}}] # Pick the server automatically from the domain of the address the user types, @@ -88,7 +90,9 @@ JMAP_SERVER_URL=https://your-jmap-server.com # OAUTH_POST_LOGOUT_REDIRECT_URI=https://mail.example.com/en/login # Replace the scopes requested at authorization. Space-separated. Leave unset -# to use the defaults the client already asks for. +# to use the defaults: openid email profile. offline_access is not among them; +# add it if your IdP (e.g. Authelia) only issues refresh tokens for it, +# otherwise sessions end when the access token expires. # OAUTH_SCOPES=openid email profile offline_access # Append scopes instead of replacing them. Use this when your IdP needs one @@ -148,6 +152,12 @@ JMAP_SERVER_URL=https://your-jmap-server.com # error than a mid-request EROFS). Pair with `:ro` on the config-volume mount. # ADMIN_CONFIG_READONLY=true # +# Optional existing PEM PKCS#8 Ed25519 private key used to sign managed plugin +# bundles. Bulwark reads this exact path without modifying it. Use a runtime +# secret mount such as a systemd credential, Docker secret, or Kubernetes Secret. +# When unset, Bulwark loads or creates ADMIN_CONFIG_DIR/plugin-signing.key. +# PLUGIN_SIGNING_KEY_FILE=/run/secrets/plugin-signing-key +# # Legacy: a single dir containing both config and state. Honoured if neither # of the split variables is set. New installs should use the split vars. # ADMIN_DATA_DIR=./data/admin @@ -292,6 +302,12 @@ LOGIN_COMPANY_NAME=Bulwark Webmail # URL for the company website link on the login page. LOGIN_WEBSITE_URL=https://bulwarkmail.org +# Where users get the source code of this build, linked from Settings > +# About. Bulwark is AGPL-3.0-only: if you run a modified build, set this to +# the source of exactly what you deploy (your fork, at the deployed commit). +# Unset links to the upstream repository. Only http(s) URLs are used. +# SOURCE_CODE_URL=https://git.example.com/acme/webmail/tree/v1.2.3 + # Cap the login logo's rendered size. Any CSS length ("120px", "8rem"). # Unset means the logo renders at its natural size. # LOGIN_LOGO_MAX_HEIGHT=96px @@ -306,6 +322,11 @@ LOGIN_WEBSITE_URL=https://bulwarkmail.org # still shows it regardless of this setting. # LOGIN_SHOW_TOTP=false # +# Offer "Sign in with an access token" (default false). For JMAP servers +# that authenticate API tokens as Bearer tokens instead of passwords, such +# as Fastmail (JMAP_SERVER_URL=https://api.fastmail.com). +# LOGIN_SHOW_TOKEN_LOGIN=true +# # Hide the version number, so it isn't disclosed to unauthenticated visitors. # LOGIN_SHOW_VERSION=false @@ -370,6 +391,10 @@ LOGIN_WEBSITE_URL=https://bulwarkmail.org # How many trusted reverse proxies sit in front of the app. The client IP is # taken that many entries from the right of X-Forwarded-For, so an attacker # can't spoof it by prepending values. Default: 1. +# Without any reverse proxy the header is whatever the client sends, so +# per-IP limits and audit-log addresses can be forged; admin sign-in then +# still stops at 50 attempts per 15 minutes across all clients. Put the +# app behind a proxy that appends X-Forwarded-For. # TRUSTED_PROXY_DEPTH=2 # Allow search engines to index the app (robots.txt / noindex). Default: false. @@ -450,6 +475,11 @@ LOGIN_WEBSITE_URL=https://bulwarkmail.org # them unset keeps the feature fully off. Treat the secret and the master # password as you would a root credential. # +# The master password never leaves the server: each handoff uses it once to +# create an app password on the target mailbox, valid for 8 hours and +# revoked on sign-out. The target account's role therefore needs the +# app-password permissions (Stalwart's default user role has them). +# # BULWARK_JWT_AUTH_SECRET= # required, >= 32 characters # BULWARK_STALWART_MASTER_USER= # required, e.g. master@example.com # BULWARK_STALWART_MASTER_PASSWORD= # required diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..827c40e31 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,21 @@ +## What and why + + + +## Related issues + + + +## Checklist + +- [ ] The change fits [What fits in Bulwark](https://bulwarkmail.org/docs/development/contributing#what-fits-in-bulwark) (core, not plugin material) +- [ ] It needed no issue first, or the approach was agreed in the linked issue (over ~500 lines excluding locales and tests, a new runtime dependency, or security-sensitive code: [details](https://bulwarkmail.org/docs/development/contributing#before-you-write-code)) +- [ ] `npm run typecheck && npm run lint && npx vitest run` pass, and new logic has tests +- [ ] New user-facing text goes through translations +- [ ] Works in Bulwark Lite, or is hidden there +- [ ] UI changes checked at phone width and in the light and dark theme +- [ ] Documentation updated in the [website repository](https://github.com/bulwarkmail/website/tree/main/docs), or not needed + +## Screenshots + + diff --git a/.github/workflows/deploy-demo.yml b/.github/workflows/deploy-demo.yml index c72f6dcf4..2d9f41de0 100644 --- a/.github/workflows/deploy-demo.yml +++ b/.github/workflows/deploy-demo.yml @@ -1,4 +1,4 @@ -name: Deploy demo +name: "Deploy: Demo" # Keeps https://demo.bulwarkmail.org on the published release image. It used to # follow ghcr.io/bulwarkmail/webmail:latest through Watchtower; now the deploy @@ -18,7 +18,7 @@ name: Deploy demo on: workflow_run: - workflows: ["Publish Docker Image on Release"] + workflows: ["Docker: Release image"] types: [completed] workflow_dispatch: inputs: diff --git a/.github/workflows/docker-publish-lite.yml b/.github/workflows/docker-publish-lite.yml index a3e762892..9b48d627b 100644 --- a/.github/workflows/docker-publish-lite.yml +++ b/.github/workflows/docker-publish-lite.yml @@ -1,12 +1,14 @@ -name: Publish Lite Docker Image +name: "Lite: Docker image" # Bulwark Lite as a container (Dockerfile.lite): the static export behind an # unprivileged nginx. Every run first builds a demo image and drives it with -# the Lite smoke suite, so the nginx routing and headers are tested, not only +# the Lite E2E suite, so the nginx routing and headers are tested, not only # the files. Then: # - release: ghcr.io/-lite (semver tags, latest unless prerelease) # - push to main: ghcr.io/-lite-beta (latest + sha) -# - pull request: smoke test only +# - pull request: E2E test only +# Published images get a signed build provenance attestation, pushed to GHCR +# next to them: `gh attestation verify oci://: --owner bulwarkmail`. on: release: @@ -34,7 +36,8 @@ on: workflow_dispatch: jobs: - smoke: + e2e: + name: E2E (container) runs-on: ubuntu-latest timeout-minutes: 30 permissions: @@ -52,13 +55,13 @@ jobs: context: . file: Dockerfile.lite load: true - tags: bulwark-lite:smoke + tags: bulwark-lite:e2e build-args: | GIT_COMMIT=${{ github.sha }} LITE_DEMO_MODE=true LITE_LOCALES=en,de - cache-from: type=gha,scope=lite-smoke - cache-to: type=gha,mode=max,scope=lite-smoke + cache-from: type=gha,scope=lite-e2e + cache-to: type=gha,mode=max,scope=lite-e2e # Read-only root, like a hardened Kubernetes pod: nginx only needs /tmp # and the directory the entrypoint renders its config into. @@ -67,7 +70,7 @@ jobs: docker run -d --name lite -p 4173:8080 \ --read-only --tmpfs /tmp --tmpfs /etc/nginx/conf.d:uid=101,gid=101 \ -e LITE_CSP_CONNECT_SRC=https://mail.example.com \ - bulwark-lite:smoke + bulwark-lite:e2e for i in $(seq 1 30); do curl -fsS http://localhost:4173/lite-build.json && exit 0 sleep 1 @@ -80,7 +83,7 @@ jobs: echo '{"appName":"Mounted","demoMode":true}' > "$RUNNER_TEMP/config.json" docker run -d --name lite-mounted -p 4174:8080 \ -v "$RUNNER_TEMP/config.json:/usr/share/nginx/html/config.json:ro" \ - bulwark-lite:smoke + bulwark-lite:e2e for i in $(seq 1 30); do curl -fsS http://localhost:4174/config.json | grep -q '"Mounted"' && break [ "$i" = 30 ] && { docker logs lite-mounted; exit 1; } @@ -100,7 +103,7 @@ jobs: - name: Install Playwright browser run: npx playwright install --with-deps chromium - - name: Run smoke test against the container + - name: Run E2E test against the container env: LITE_SMOKE_BASE_URL: http://localhost:4173 LITE_SMOKE_EXPECT_CONNECT_SRC: https://mail.example.com @@ -114,18 +117,21 @@ jobs: if: failure() uses: actions/upload-artifact@v4 with: - name: lite-container-smoke-report + name: lite-container-e2e-report path: playwright-report retention-days: 7 publish: - needs: smoke + name: Publish + needs: e2e if: github.event_name != 'pull_request' runs-on: ubuntu-latest timeout-minutes: 30 permissions: contents: read packages: write + id-token: write + attestations: write env: IMAGE_NAME: ghcr.io/${{ github.repository }}-lite${{ github.event_name != 'release' && '-beta' || '' }} steps: @@ -161,6 +167,7 @@ jobs: # builder to $BUILDPLATFORM) and the final stage only COPYs, so both # platforms come out of one job without QEMU. - name: Build and push + id: build uses: docker/build-push-action@v6 with: context: . @@ -176,3 +183,11 @@ jobs: - name: Inspect image run: docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} + + - name: Attest build provenance + uses: actions/attest@v4 + with: + subject-name: ${{ env.IMAGE_NAME }} + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + create-storage-record: false diff --git a/.github/workflows/docker-publish-releases.yml b/.github/workflows/docker-publish-releases.yml index 292246802..fb9117dca 100644 --- a/.github/workflows/docker-publish-releases.yml +++ b/.github/workflows/docker-publish-releases.yml @@ -1,5 +1,11 @@ -name: Publish Docker Image on Release +name: "Docker: Release image" +# `latest` moves only for a published stable release, or for a manual run +# dispatched on a stable release tag (to rebuild one). A dispatch on a +# branch builds nothing that the demo deploy or Watchtower users follow. +# +# Every manifest list gets a signed build provenance attestation, pushed to +# GHCR next to it: `gh attestation verify oci://: --owner bulwarkmail`. on: release: types: [published] @@ -10,6 +16,7 @@ env: jobs: build: + name: Build (${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}) strategy: fail-fast: false matrix: @@ -71,11 +78,14 @@ jobs: retention-days: 1 merge: + name: Merge manifest runs-on: ubuntu-latest needs: build permissions: contents: read packages: write + id-token: write + attestations: write steps: - name: Download digests @@ -101,7 +111,7 @@ jobs: with: images: ${{ env.IMAGE_NAME }} tags: | - type=raw,value=latest,enable=${{ github.event_name != 'release' || !github.event.release.prerelease }} + type=raw,value=latest,enable=${{ (github.event_name == 'release' && !github.event.release.prerelease) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v') && !contains(github.ref_name, '-')) }} type=semver,pattern=v{{version}} type=semver,pattern={{version}} type=semver,pattern=v{{major}}.{{minor}} @@ -116,10 +126,22 @@ jobs: $(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *) - name: Inspect image + id: inspect run: | docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} + digest=$(docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} --format '{{json .Manifest}}' | jq -r .digest) + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + - name: Attest build provenance + uses: actions/attest@v4 + with: + subject-name: ${{ env.IMAGE_NAME }} + subject-digest: ${{ steps.inspect.outputs.digest }} + push-to-registry: true + create-storage-record: false build-always: + name: Build locale-prefixed (${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}) strategy: fail-fast: false matrix: @@ -181,11 +203,14 @@ jobs: retention-days: 1 merge-always: + name: Merge locale-prefixed manifest runs-on: ubuntu-latest needs: build-always permissions: contents: read packages: write + id-token: write + attestations: write steps: - name: Download digests uses: actions/download-artifact@v4 @@ -212,7 +237,7 @@ jobs: flavor: | suffix=-always,onlatest=true tags: | - type=raw,value=latest,enable=${{ github.event_name != 'release' || !github.event.release.prerelease }} + type=raw,value=latest,enable=${{ (github.event_name == 'release' && !github.event.release.prerelease) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v') && !contains(github.ref_name, '-')) }} type=semver,pattern=v{{version}} type=semver,pattern={{version}} type=semver,pattern=v{{major}}.{{minor}} @@ -227,5 +252,16 @@ jobs: $(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *) - name: Inspect image + id: inspect run: | docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} + digest=$(docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} --format '{{json .Manifest}}' | jq -r .digest) + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + - name: Attest build provenance + uses: actions/attest@v4 + with: + subject-name: ${{ env.IMAGE_NAME }} + subject-digest: ${{ steps.inspect.outputs.digest }} + push-to-registry: true + create-storage-record: false diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 6a718fbbf..a7bae41ac 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -1,4 +1,4 @@ -name: Publish Docker Image +name: "Docker: Branch image" on: push: @@ -23,20 +23,25 @@ on: jobs: prepare: + name: Prepare runs-on: ubuntu-latest outputs: image_name: ${{ steps.set.outputs.image_name }} steps: - name: Set image name id: set + env: + REF_NAME: ${{ github.ref_name }} + REPOSITORY: ${{ github.repository }} run: | - if [ "${{ github.ref_name }}" = "main" ]; then - echo "image_name=ghcr.io/${{ github.repository }}-beta" >> $GITHUB_OUTPUT + if [ "$REF_NAME" = "main" ]; then + echo "image_name=ghcr.io/${REPOSITORY}-beta" >> "$GITHUB_OUTPUT" else - echo "image_name=ghcr.io/${{ github.repository }}-${{ github.ref_name }}" >> $GITHUB_OUTPUT + echo "image_name=ghcr.io/${REPOSITORY}-${REF_NAME}" >> "$GITHUB_OUTPUT" fi build: + name: Build (${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}) needs: prepare strategy: fail-fast: false @@ -99,11 +104,14 @@ jobs: retention-days: 1 merge: + name: Merge manifest runs-on: ubuntu-latest needs: [prepare, build] permissions: contents: read packages: write + id-token: write + attestations: write steps: - name: Download digests @@ -139,5 +147,18 @@ jobs: $(printf '${{ needs.prepare.outputs.image_name }}@sha256:%s ' *) - name: Inspect image + id: inspect run: | docker buildx imagetools inspect ${{ needs.prepare.outputs.image_name }}:${{ steps.meta.outputs.version }} + digest=$(docker buildx imagetools inspect ${{ needs.prepare.outputs.image_name }}:${{ steps.meta.outputs.version }} --format '{{json .Manifest}}' | jq -r .digest) + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + # Signed build provenance, pushed to GHCR next to the image: + # `gh attestation verify oci://: --owner bulwarkmail`. + - name: Attest build provenance + uses: actions/attest@v4 + with: + subject-name: ${{ needs.prepare.outputs.image_name }} + subject-digest: ${{ steps.inspect.outputs.digest }} + push-to-registry: true + create-storage-record: false diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml new file mode 100644 index 000000000..040daffc6 --- /dev/null +++ b/.github/workflows/integration.yml @@ -0,0 +1,73 @@ +name: "CI: Integration tests" + +# Runs the dockerised webmail + Stalwart Playwright suite in integration/ +# (see integration/README.md). It takes several minutes, so unlike the vitest +# job in tests.yml it does not run on every push. It runs: +# +# - every night on main, +# - on a pull request that carries the "integration" label (and again on +# each push to it while the label stays on), +# - on demand: gh workflow run integration.yml +# +# A fresh runner means a fresh Stalwart volume, so the declarative account +# bootstrap always applies. Specs pinned with test.fail for known server bugs +# count as passed when they fail as expected; only an unexpected result fails +# the job. + +on: + schedule: + - cron: "17 2 * * *" + workflow_dispatch: + pull_request: + types: [opened, reopened, synchronize, labeled] + +permissions: + contents: read + +jobs: + playwright: + name: Playwright + # On pull requests, run only when the "integration" label is on. A labeled + # event for some other label must not start (or cancel) a run. + if: >- + github.event_name != 'pull_request' || + (github.event.action == 'labeled' && github.event.label.name == 'integration') || + (github.event.action != 'labeled' && contains(github.event.pull_request.labels.*.name, 'integration')) + runs-on: ubuntu-latest + timeout-minutes: 60 + # Job-level, so a skipped run never cancels a real one. + concurrency: + group: integration-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + + - name: Install dependencies + # The Playwright container runs the suite from this checkout, so it + # needs @playwright/test in node_modules. + run: npm ci + + - name: Run integration suite + run: bash integration/run-tests.sh + + - name: Show container logs + if: failure() + working-directory: integration + run: docker compose logs --no-color --timestamps + + - name: Upload Playwright report + if: failure() + uses: actions/upload-artifact@v4 + with: + name: integration-report + path: | + integration/playwright-report/ + integration/test-results/ + retention-days: 14 diff --git a/.github/workflows/standalone-release.yml b/.github/workflows/standalone-release.yml index 1c5c540c0..c3aa5f0c4 100644 --- a/.github/workflows/standalone-release.yml +++ b/.github/workflows/standalone-release.yml @@ -1,15 +1,22 @@ -name: Publish Standalone Tarball on Release +name: "Standalone: Release tarball" + +# The tarballs build without a write token. The release job, which runs no +# checked-out code, publishes each one with a `.sha256` next to it and a +# signed build provenance attestation: +# `gh attestation verify --repo bulwarkmail/webmail`. on: release: + name: Attach to release types: [published] workflow_dispatch: permissions: - contents: write + contents: read jobs: build: + name: Build (${{ matrix.arch }}) strategy: fail-fast: false matrix: @@ -52,17 +59,44 @@ jobs: tar -czf "$TARBALL" bulwark-standalone/ echo "TARBALL=$TARBALL" >> "$GITHUB_ENV" - - name: Upload release asset - if: github.event_name == 'release' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAG_NAME: ${{ github.event.release.tag_name }} - run: gh release upload "$TAG_NAME" "$TARBALL" --clobber - - - name: Upload artifact (workflow_dispatch) - if: github.event_name == 'workflow_dispatch' + - name: Upload artifact uses: actions/upload-artifact@v4 with: name: standalone-${{ matrix.arch }} path: ${{ env.TARBALL }} + if-no-files-found: error retention-days: 7 + + release: + name: Attach to release + needs: build + if: github.event_name == 'release' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + id-token: write + attestations: write + steps: + - name: Download tarballs + uses: actions/download-artifact@v4 + with: + pattern: standalone-* + path: tarballs + merge-multiple: true + + - name: Checksum tarballs + working-directory: tarballs + run: for tarball in *.tar.gz; do sha256sum "$tarball" > "$tarball.sha256"; done + + - name: Attest build provenance + uses: actions/attest@v4 + with: + subject-path: tarballs/*.tar.gz + + - name: Upload release assets + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG_NAME: ${{ github.event.release.tag_name }} + run: gh release upload "$TAG_NAME" tarballs/*.tar.gz tarballs/*.tar.gz.sha256 --clobber diff --git a/.github/workflows/static-lite.yml b/.github/workflows/static-lite.yml index 256da7a5d..149e12036 100644 --- a/.github/workflows/static-lite.yml +++ b/.github/workflows/static-lite.yml @@ -1,4 +1,4 @@ -name: Build Static Lite +name: "Lite: Static bundle" # Bulwark Lite: the static export of the webmail (see docs in README.md, # "Static Lite build"). Runs the build on every push as a regression check, @@ -7,16 +7,18 @@ name: Build Static Lite # # Two targets are built side by side: # - static: bulwark-lite-.zip for any static web host; -# - stalwart: bulwark-lite-stalwart.zip, a Stalwart `Application` bundle. Its -# release asset name carries no version, so -# releases/latest/download/bulwark-lite-stalwart.zip is a stable -# resourceUrl that follows new releases. +# - stalwart: bulwark-lite-stalwart.zip, a Stalwart `Application` bundle. +# Its LITE-README points `resourceUrl` at the tagged release. +# +# Each zip is published with a `.sha256` next to it and a signed build +# provenance attestation: `gh attestation verify --repo bulwarkmail/webmail`. # # scripts/lite/prepare.mjs deletes the server-only trees in place; that is # safe here because the Actions checkout is disposable (CI=true is the guard). on: release: + name: Attach to release types: [published] push: branches: [main] @@ -42,10 +44,11 @@ on: default: false permissions: - contents: write + contents: read jobs: build: + name: Build (${{ matrix.target }}) runs-on: ubuntu-latest timeout-minutes: 30 strategy: @@ -98,22 +101,50 @@ jobs: echo "ZIP=${ZIP}" >> "$GITHUB_ENV" ls -la "${ZIP}" - - name: Upload release asset - if: github.event_name == 'release' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAG_NAME: ${{ github.event.release.tag_name }} - run: gh release upload "$TAG_NAME" "$ZIP" --clobber - - name: Upload artifact - if: github.event_name != 'release' uses: actions/upload-artifact@v4 with: name: bulwark-lite-${{ matrix.target }} path: ${{ env.ZIP }} retention-days: 7 - smoke: + release: + name: Attach to release + # The only job with a write token, and it runs no checked-out code. + needs: build + if: github.event_name == 'release' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + id-token: write + attestations: write + steps: + - name: Download zips + uses: actions/download-artifact@v4 + with: + pattern: bulwark-lite-* + path: zips + merge-multiple: true + + - name: Checksum zips + working-directory: zips + run: for zip in *.zip; do sha256sum "$zip" > "$zip.sha256"; done + + - name: Attest build provenance + uses: actions/attest@v4 + with: + subject-path: zips/*.zip + + - name: Upload release assets + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG_NAME: ${{ github.event.release.tag_name }} + run: gh release upload "$TAG_NAME" zips/*.zip zips/*.zip.sha256 --clobber + + e2e: + name: E2E (static) # Boots the demo export on a plain static server and drives it with # Playwright: login, open a thread, switch surfaces, reload a deep link. # No JMAP server involved, so it is cheap and deterministic. @@ -136,7 +167,7 @@ jobs: - name: Install Playwright browser run: npx playwright install --with-deps chromium - # prepare.mjs prunes every test tree in the checkout; the smoke suite + # prepare.mjs prunes every test tree in the checkout; the E2E suite # lives under scripts/lite/smoke, which it leaves alone. - name: Build demo export env: @@ -146,18 +177,19 @@ jobs: LITE_LOCALES: "en,de" run: npm run build:lite - - name: Run smoke test + - name: Run E2E test run: npm run test:lite-smoke - name: Upload Playwright report if: failure() uses: actions/upload-artifact@v4 with: - name: lite-smoke-report + name: lite-e2e-report path: playwright-report retention-days: 7 - smoke-stalwart: + e2e-stalwart: + name: E2E (Stalwart) # The Stalwart Application bundle, served by scripts/lite/serve.mjs # --stalwart (an emulation of how Stalwart serves Applications) from the # zip itself, under two prefixes. @@ -189,13 +221,13 @@ jobs: LITE_LOCALES: "en,de" run: npm run build:lite - - name: Run smoke test + - name: Run E2E test run: npm run test:lite-smoke:stalwart - name: Upload Playwright report if: failure() uses: actions/upload-artifact@v4 with: - name: lite-smoke-stalwart-report + name: lite-e2e-stalwart-report path: playwright-report retention-days: 7 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 40b9e5bd8..43a7acac3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,4 +1,4 @@ -name: Tests +name: "CI: Unit tests" on: push: @@ -6,7 +6,7 @@ on: jobs: vitest: - name: vitest + name: Vitest runs-on: ubuntu-latest timeout-minutes: 30 steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index afeda7ec2..ca622ed2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,476 @@ # Changelog +## 1.14.1 (2026-10-11) + +1.14.1 fixes plain-text and unstyled messages showing on a gray background in dark mode after the 1.14.0 dark mode rewrite. + +Thank you for your donations: + +- _You? [Become a sponsor!](https://github.com/sponsors/bulwarkmail)_ + +**One-time** + +- Anonymous +- Anonymous +- Anonymous + +**Monthly** + +- [@naokton](https://github.com/naokton) +- [@yerTools](https://github.com/yerTools) +- [@jsaathof](https://github.com/jsaathof) +- [@berkersal](https://github.com/berkersal) +- [@NABarnes](https://github.com/NABarnes) +- [@felixzieger](https://github.com/felixzieger) +- [@pr0ton11](https://github.com/pr0ton11) +- [@fpauser](https://github.com/fpauser) +- [@proxforge](https://github.com/proxforge) +- [@spss20](https://github.com/spss20) +- [@elgringoYan](https://github.com/elgringoYan) +- [@pauladams8](https://github.com/pauladams8) +- [@djpriest](https://github.com/djpriest) +- [@umakers](https://github.com/umakers) +- [@zplizzi](https://github.com/zplizzi) +- [@jeremiah](https://github.com/jeremiah) +- [@Theoretisch1337](https://github.com/Theoretisch1337) +- [@svandive](https://github.com/svandive) +- [@HiltMundell](https://github.com/HiltMundell) + +### Fixes + +- **Mail**: In dark mode, plain-text and unstyled messages use the app's background again instead of a gray box + +## 1.14.0 (2026-10-11) + +1.14.0 adds Mountain View, an optional layout with a top bar and a wide search field, and gives the Files app and the calendar a new layout. Dark mode now recolours messages instead of inverting them, so brand colours stay as sent. Push can be turned on for several accounts at once, and the account list can be backed up encrypted and restored on another device. The composer got a long round of send fixes. With several accounts open, batch actions no longer hit another account's message that happens to share an id with the selected one. + +Thank you for your donations: + +- _You? [Become a sponsor!](https://github.com/sponsors/bulwarkmail)_ + +**One-time** + +- Anonymous +- Anonymous +- Anonymous + +**Monthly** + +- [@naokton](https://github.com/naokton) +- [@yerTools](https://github.com/yerTools) +- [@jsaathof](https://github.com/jsaathof) +- [@berkersal](https://github.com/berkersal) +- [@NABarnes](https://github.com/NABarnes) +- [@felixzieger](https://github.com/felixzieger) +- [@pr0ton11](https://github.com/pr0ton11) +- [@fpauser](https://github.com/fpauser) +- [@proxforge](https://github.com/proxforge) +- [@spss20](https://github.com/spss20) +- [@elgringoYan](https://github.com/elgringoYan) +- [@pauladams8](https://github.com/pauladams8) +- [@djpriest](https://github.com/djpriest) +- [@umakers](https://github.com/umakers) +- [@zplizzi](https://github.com/zplizzi) +- [@jeremiah](https://github.com/jeremiah) +- [@Theoretisch1337](https://github.com/Theoretisch1337) +- [@svandive](https://github.com/svandive) +- [@HiltMundell](https://github.com/HiltMundell) + +### Features + +- **UI**: Mountain View is an optional layout, chosen under Settings > Layout > Interface layout. On desktop it has a top bar with a wide search field, an apps grid and the account avatar in place of the left rail, a Compose pill, a docked compose window, an account popover with unread counts per account, and j/k, x and g shortcuts. Calendar, Contacts, Files and Settings use the same top bar. The default layout is unchanged (#1168, thanks @lucamzanon) +- **Files**: The Files app is laid out like Contacts and Calendar: a sidebar with a New menu, the folder tree, Starred, Recent and Shared with me, a header with breadcrumbs, search, sort and a list/grid switch, a details panel, right-click menus in the sidebar and arrow-key navigation. On touch, a tap opens and a long press selects. Folders in the tree can be renamed and deleted, recent files open in their folder, and the view, sort and hidden-files settings now apply +- **Files**: Image previews in Files and in attachments zoom with the wheel or a pinch, pan by dragging or with the arrow keys, switch between fit and full size on double-click, and close on a click beside the image +- **Files**: Uploads show as a toast with their progress and a Cancel button. The large file warning is gone +- **Calendar**: On wide screens, clicking or dragging over empty time opens a quick editor next to the slot, and clicking an event opens a card with edit, delete and more actions. Busy month cells show "+N more", the agenda lists each day as a row with the date beside its events, and the dates in the week header open that day. Calendar lists in the sidebar fold away and show their options on hover. Phones keep the full editor +- **Push**: The notification settings list every connected account and turn push on or off for several of them at once, with a single browser permission prompt (#1054, thanks @lucamzanon) +- **Accounts**: Users with several accounts can save their account list on the webmail server, encrypted in the browser with a password they choose, and restore it on another device. No mailbox passwords are stored. Admins turn it on with "Account List Backup" under Admin > Policy (#1201, thanks @lucamzanon) +- **Filters**: The folder context menu runs a saved rule on the messages already in that folder (#1166) +- **Composer**: Schedule send offers tomorrow at 8:00, tomorrow at 13:00 and next Monday at 8:00 as one-click times +- **Settings**: The language picker has a search field and flags, and every date format and region option shows a live sample +- **Plugins**: A plugin can run a message-list search with a JMAP Email filter (#1024) +- **Plugins**: Calendar event actions get the event's uid and attendees, and the form-save hook now fires and can change the meeting link that is saved with the event (#1202, thanks @siennathesane) + +### Changes + +- **Mail**: Dark mode recolours messages instead of inverting them. Light backgrounds are darkened in their own hue, brand colours and dark fills stay as sent, and text only changes when it lacks contrast. A message's own dark mode styles follow the app theme instead of the system's +- **Mail**: A folder opened before shows its messages at once and refreshes them in the background. A failed load leaves them on screen (#1195, thanks @lucamzanon) +- **Composer**: On a phone, the formatting toolbar folds away behind a Formatting button and its buttons are larger. The send options sit together in one menu +- **Files**: File sizes are rounded the way people read them, like 67 KB or 2.1 MB + +### Fixes + +- **Mail**: In views that merge several accounts, selecting a message no longer also selects a message with the same id in another account. Batch delete, move, archive, copy, mark read, tag and spam act only on the ticked messages, each through its own account. Before, a permanent delete could remove the other account's message (#1061, thanks @lucamzanon) +- **Mail**: A message with two spaces in a row in its subject no longer freezes the tab (#1193, thanks @dealerweb) +- **Mail**: Blocking remote content no longer drops a message's style sheets, so messages keep their layout before images are loaded +- **Mail**: The list shows no paperclip on a message that only has inline images +- **Mail**: The "via" badge is hidden when it repeats the sender's name, and a draft shows one Edit button +- **Send**: Signed and encrypted messages reach Bcc recipients (#1206) +- **Send**: After a plugin send, such as S/MIME, the composer closes, and a failed plugin send keeps the draft (#1207) +- **Send**: A failed send removes its unsent copy from Drafts and explains the failure in plain words. A send while offline says so and keeps the message +- **Send**: Typed addresses are split on commas, and a message with an invalid address is not sent. The address field marks which ones to fix +- **Send**: Undo send disappears once the delay is over and says so when an undo fails +- **Send**: Discard deletes the draft, also one reopened from Scheduled, and closing an autosaved draft no longer asks about unsaved changes +- **Send**: The missing subject warning comes once per message, and the scheduled time shows its date, rounded to the minute +- **Composer**: Tabbing into a reply or forward keeps the quoted message, and tabbing into a new message starts at the top of the body +- **Composer**: A reply opens with the caret in the body, and the composer is titled Reply, Reply All or Forward instead of New Message +- **Composer**: A reopened draft takes its text from the message body only. An attached .csv or .txt no longer turns up as the message text (#1213, thanks @shukiv) +- **Composer**: A long attachment list scrolls instead of pushing the Send button out of view (#1212, thanks @shukiv) +- **Composer**: The plain-text part of sent mail marks quotes and list items, and the signature has one separator +- **Composer**: Enter adds the highlighted suggestion instead of the typed text, and the suggestions close once the address is added and line up with the typed text. On a phone they span the whole row and show the name above the address +- **Composer**: Body text no longer shows through the pinned formatting toolbar (#1200, thanks @lucamzanon) +- **Composer**: On a phone, sending a new message returns to the message list, and the Continue draft banner no longer flashes after a send +- **Composer**: Bitwarden no longer offers logins in the recipient fields, the mail search box or the event participant field +- **Login**: A remembered sign-in survives a server timeout or an origin switch during restore instead of signing out (#1167) +- **Login**: Signing out of one account keeps the other accounts, and a reload with only accounts awaiting sign-in shows the login page instead of a connection error (#1201, thanks @lucamzanon) +- **Login**: A reload without "Remember me" no longer reports an expired session +- **Unified**: Switching to another account keeps the unified mailbox on (#1144, thanks @lucamzanon) +- **Push**: Push is renewed for every connected account, not only the active one, so accounts no longer stop notifying after seven days. The all-accounts panel shows each account's real state and why an account failed (#1054, thanks @lucamzanon) +- **Filters**: Forward is hidden in filter rules when the server allows no redirects (#1208) +- **Calendar**: Save is blocked while a plugin's form-save hook runs, so a double press no longer creates the event twice (#1202, thanks @siennathesane) +- **Calendar**: Participant suggestions are no longer cut off by the event form +- **Files**: Canceling an upload stops the file in flight and says the upload was canceled instead of counting every file as done +- **Files**: A drag selection keeps its items after letting go, and Files shows a loading state instead of "No files yet" before the first listing +- **Files**: Read-only documents open in ONLYOFFICE without the -103 warning (#1187) +- **Contacts**: The contact popover shows the sender's name when the saved contact has none, and Contacts shows placeholders instead of "No contacts yet" while loading +- **UI**: The close and back buttons in the composer and conversation view have names for screen readers, and the composer toolbar buttons are labelled +- **UI**: Reply All stays on one line in the conversation view, and the welcome banner gives touch tips on a phone +- **Translations**: The new composer, send, Files and filter strings are translated + +## 1.13.0 (2026-10-07) + +1.13.0 turns the vacation settings into an Out of Office page that can also forward mail, lets filter rules run only for a date range, and copies messages into another connected account. Files from the Files app can be attached in the composer, tags can be set on many messages at once and folders moved in bulk. Messages whose sender can't be verified now carry a warning. It also stops one account's settings and templates from carrying over to the next account signed in on the same browser. + +Thank you for your donations: + +- _You? [Become a sponsor!](https://github.com/sponsors/bulwarkmail)_ + +**One-time** + +- Anonymous +- Anonymous +- Anonymous + +**Monthly** + +- [@naokton](https://github.com/naokton) +- [@yerTools](https://github.com/yerTools) +- [@jsaathof](https://github.com/jsaathof) +- [@berkersal](https://github.com/berkersal) +- [@NABarnes](https://github.com/NABarnes) +- [@felixzieger](https://github.com/felixzieger) +- [@pr0ton11](https://github.com/pr0ton11) +- [@fpauser](https://github.com/fpauser) +- [@proxforge](https://github.com/proxforge) +- [@spss20](https://github.com/spss20) +- [@elgringoYan](https://github.com/elgringoYan) +- [@pauladams8](https://github.com/pauladams8) +- [@djpriest](https://github.com/djpriest) +- [@umakers](https://github.com/umakers) +- [@zplizzi](https://github.com/zplizzi) +- [@jeremiah](https://github.com/jeremiah) +- [@Theoretisch1337](https://github.com/Theoretisch1337) +- [@svandive](https://github.com/svandive) +- [@HiltMundell](https://github.com/HiltMundell) + +### Security + +- **Settings**: Signing out and then signing in with another account in the same browser no longer shows the previous account's settings, tags and templates, and no longer saves them to the new account's synced settings (#1185) + +### Features + +- **Mail**: A message whose sender fails the From domain's checks, or that passes neither SPF nor DKIM, shows a warning above the message and a badge next to the sender. "Always trust this sender" is not offered for it +- **Mail**: "Copy to account..." in the message menu files a copy in a folder of another connected account and leaves the original where it is. Copies keep their original date (#1150, thanks @lucamzanon) +- **Mail**: The selection toolbar and the right-click menu put a tag on, or take it off, every selected message at once (#1077) +- **Out of office**: The vacation settings are now an Out of Office page: the period on top, then the automatic reply and forwarding, each with its own switch. Forwarding works with or without the reply, never forwards spam and can keep a copy in the inbox. The reply can go to all senders, internal senders only or external senders only (#1152, thanks @dealerweb) +- **Filters**: A rule can be limited to a period, and the rule list shows whether it is scheduled, active or expired (#1152, thanks @dealerweb) +- **Filters**: The new "All messages" condition matches every message (#1154, thanks @dealerweb) +- **Composer**: "Attach from Files" attaches files from the Files app, including files shared with you, without downloading and uploading them again (#1179) +- **Composer**: Typing @ in the message body offers the To and Cc recipients and inserts the chosen one's first name. Bcc recipients are never offered. "Mention recipients with @" in the composer settings turns it off (#1134, thanks @dealerweb) +- **Folders**: The folder settings can select several folders, with Shift+click for a range, and move them together under another folder or to the top level (#1173) +- **Calendar**: The day and week views can be limited to working hours, and the week view can leave out non-working days. Events outside the visible hours are counted at the top and bottom of each day and open from there, and a button in the view shows all hours (#1164) +- **Login**: `LOGIN_SHOW_TOKEN_LOGIN=true` offers "Sign in with an access token", for JMAP servers that take API tokens instead of passwords, such as Fastmail +- **Login**: A server in `JMAP_SERVERS` whose `oauth` block has both a `clientId` and a `buttonLabel` gets its own sign-in button on the login page, even while OAuth is off globally. This allows a "Sign in with Google" button for a Gmail bridge next to servers that use passwords (#1135, thanks @lucamzanon) +- **UI**: The browser tab title names the active account, as in "Inbox - alice@example.com - Webmail", and Settings, Calendar, Contacts and Files set their own title. Turning off "Subject in Tab Title" under Admin > Policy keeps message subjects out of the title, and with it out of the browser history (#1186, thanks @oguzyilmaznet) +- **Unified**: While logins reconnect after a page load, the "All accounts" header shows how many are already counted, such as "4/10" (#1140, thanks @lucamzanon) +- **Push**: A message that reaches several of your accounts rings once. For 30 seconds after an alert, notifications from your other accounts arrive silently (#1141, thanks @lucamzanon) +- **Server**: `SOURCE_CODE_URL` points the source code link in Settings > About at the code of a modified build, as AGPL section 13 asks of anyone running one (#1161) + +### Changes + +- **Calendar**: The day and week views show 08:00 to 20:00 by default. "Limit visible hours" in the calendar settings changes the range or turns it off (#1164) +- **Tags**: Tag views and their counts leave out messages in Trash and Spam (#1156) +- **Mail**: In a shared mailbox, the Move menus list that mailbox's folders first and your own folders after them, under your account name (#1149) +- **Dependencies**: sharp 0.35.5 and source-map-js 1.2.2 (npm audit) +- **Docs**: CONTRIBUTING.md explains what belongs in core and what in a plugin, and which changes need an agreed issue before a pull request + +### Fixes + +- **Mail**: Attachments, inline images and .eml downloads of messages in shared folders are fetched from the account that owns them. On Cyrus they failed with "failed to find blob by id" (#1188, thanks @VasilisNtovolos) +- **Mail**: Archive creates an Archive folder when the account has none, instead of only reporting that it is missing (#1176, thanks @cybersmurf) +- **Mail**: Opening the webmail starts in the inbox instead of a folder from an earlier visit, such as Trash +- **Mail**: Opening another folder, tag, account or search starts the message list at the top instead of where the last one was scrolled to (#1138, thanks @dealerweb) +- **Mail**: Previews no longer start with a style sheet ("@media screen and ...") in the message list and in push notifications (#1136, thanks @lucamzanon) +- **Search**: Searching from the unified All mail view finds sent mail too +- **Send**: A draft saved without a subject reopens with an empty subject, so Send warns about it again instead of sending "(No Subject)" (#1189) +- **Send**: When the server does not confirm that a message was sent, the draft is kept and the composer asks you to check Sent before sending again (#1019, thanks @lucamzanon) +- **Send**: A message the server refuses shows the server's reason instead of "Invalid reference to non-existing object" +- **Send**: A forward sent from another account's address no longer fails with `blobNotFound`. Its attachments and inline images are copied to the sending account first (#1142, thanks @lucamzanon) +- **Push**: Push turns itself back on when the browser lost its subscription, retrying at most every 15 minutes (#1147, thanks @lucamzanon) +- **Push**: The notification settings check push again when you come back to the tab, so push turned off in the browser or another tab no longer shows as on (#1148, thanks @lucamzanon) +- **Push**: When the new message cannot be read, the notification no longer announces another unread message from the Inbox in its place, and a failed lookup shows a generic notification instead of none (#1041, thanks @lucamzanon) +- **Filters**: "Stop processing further rules" also stops after "Delete silently" and "Reject", so later rules no longer file the message. Rules whose name contains double spaces, a tab or a trailing space no longer gain a copy on every save, and the copies earlier saves left are removed (#1153, thanks @dealerweb) +- **Filters**: The forwarding limit counts the forwards one message can collect, instead of adding up every enabled rule, and warns when the rule order lets one message go over it (#1155, thanks @dealerweb) +- **Filters**: A condition with several values wraps inside its card in the expanded rule view (#1139, thanks @dealerweb) +- **Filters**: An open rule dialog or Sieve editor, and what was typed in it, survives a filter change from another tab or device (#1162, thanks @dealerweb) +- **Templates**: A tab or device that had not reloaded no longer deletes templates created elsewhere when it saves its settings +- **Calendar**: Duplicating an event keeps its meeting link (#1170) +- **Calendar**: The Calendar Agenda plugin shows events from shared and group calendars (#1175, thanks @cybersmurf) +- **Files**: Folders shared with you can be opened, and your own folders shared, in both folder layouts (#1181) +- **Files**: Office editing works behind a reverse proxy where the editor and the browser reach the webmail at different addresses. The WOPI client URL may be an internal address (#1130) +- **Login**: When Stalwart accepts a password and TOTP code but refuses to issue tokens, the login page points at the OAuth client settings instead of opening the browser's own sign-in dialog and reporting a wrong code +- **Branding**: With `APP_NAME` set, the authenticator app entry for two-factor sign-in, the About card and the Files preview use the configured name and logo (#1177, thanks @cybersmurf) +- **UI**: Text fields in dialogs keep the focus when the page behind updates, which happened every 30 seconds and on new mail (#1162, thanks @dealerweb) +- **UI**: Buttons, menu items, tabs and other controls show the pointer cursor again (#1184, thanks @gwku) +- **UI**: The account group labels in the From dropdown are readable in dark themes (#1157, thanks @dealerweb) +- **Translations**: Czech is fully translated (#1174, thanks @cybersmurf), and missing placeholders are restored in Persian, Hebrew, Hungarian, Mongolian and Slovak (#1165, thanks @owgreen-dev) + +## 1.12.0 (2026-09-30) + +1.12.0 lets you create filter rules straight from a message, offers the code from sign-in mail for one-click copying, and gives a phone linked with "Link Mobile App" a sign-in of its own, for every kind of account. Search now leaves Spam and Trash out by default, and emptying an ordinary folder moves its mail to the Trash. Browsers with many logins start up much faster. It also contains three security fixes, so please update. + +Thank you for your donations: + +- _You? [Become a sponsor!](https://github.com/sponsors/bulwarkmail)_ + +**One-time** + +- Anonymous + +**Monthly** + +- [@yerTools](https://github.com/yerTools) +- [@jsaathof](https://github.com/jsaathof) +- [@berkersal](https://github.com/berkersal) +- [@NABarnes](https://github.com/NABarnes) +- [@felixzieger](https://github.com/felixzieger) +- [@pr0ton11](https://github.com/pr0ton11) +- [@fpauser](https://github.com/fpauser) +- [@proxforge](https://github.com/proxforge) +- [@spss20](https://github.com/spss20) +- [@elgringoYan](https://github.com/elgringoYan) +- [@pauladams8](https://github.com/pauladams8) +- [@djpriest](https://github.com/djpriest) +- [@umakers](https://github.com/umakers) +- [@zplizzi](https://github.com/zplizzi) +- [@jeremiah](https://github.com/jeremiah) +- [@Theoretisch1337](https://github.com/Theoretisch1337) +- [@svandive](https://github.com/svandive) +- [@HiltMundell](https://github.com/HiltMundell) + +### Security + +- **Auth**: The password+TOTP login no longer sends the webmail's OAuth client secret to a mail server the user chose when custom JMAP endpoints are allowed. Only admin-configured servers get it +- **Auth**: The identity provider round trip for "Link Mobile App" can no longer sign the browser in as whichever account answered it, and a re-authentication the provider answered from an existing session instead of a fresh login is refused +- **Mail**: Opening a previewed SVG attachment in a new tab no longer runs the sender's script in the webmail origin + +### Features + +- **Mail**: A "Rules" entry in the message right-click menu creates filter rules from the message: always move mail from its sender, domain or mailing list, mark it read, tag it, or block the sender. A new rule can also run on the messages already in the folder, and it can be undone from the toast +- **Filters**: The rule editor suggests conditions from the message it was opened from (subject, recipients, List-Id, sender domain), and the new "is the address" and "has the domain" conditions match an address exactly +- **Mail**: Codes from sign-in and confirmation mail show as a copy chip in the message, and in the list for a day. "Show Verification Codes" in settings turns it off +- **Mail**: In the unified view, rows can be tinted with their account's color instead of showing the account dot, and tags this browser has no definition for, such as ones set by a server-side filter, get a color of their own instead of grey (#1052, thanks @lucamzanon) +- **Search**: The folder dropdown shows subfolders indented under their parents +- **Composer**: Pasted plain-text lines that start with "- ", "* ", "• ", "1. " or "1) " become real lists +- **Calendar**: The event popover finds the join link of Teams, Zoom, Meet, Webex, Jitsi, Whereby and GoTo meetings in the location or description, and the location opens in maps, with a copy button next to it (#1095, thanks @lucletoffe) +- **Server**: `LIBRETRANSLATE_API_KEY_FILE`, `BULWARK_JWT_AUTH_SECRET_FILE`, `BULWARK_STALWART_MASTER_USER_FILE` and `BULWARK_STALWART_MASTER_PASSWORD_FILE` read these secrets from files, and the admin config accepts `oauthClientSecretFile` and `sessionSecretFile` (#897, thanks @Cameo007) +- **Plugins**: `PLUGIN_SIGNING_KEY_FILE` points at an existing Ed25519 key for signing managed plugin bundles, for read-only secret mounts (#996, thanks @mulatta) +- **Releases**: Container images and release files come with a signed build provenance attestation, and the standalone tarballs get a `.sha256`. The README explains how to check them with `gh attestation verify` + +### Changes + +- **Search**: Search leaves out Spam and Trash unless "All folders" is picked in the folder dropdown. A search started in Spam or Trash searches that folder +- **Mail**: Emptying a folder other than Trash or Junk moves its mail to the Trash, unless deleted mail is set to be removed permanently +- **Mobile app**: "Link Mobile App" is offered for every account. Password and password+TOTP accounts confirm their password (and code) in the dialog. The phone gets a sign-in of its own, so signing out in the browser no longer signs it out, and a sign-in link to copy sits next to the QR code. Failed password attempts are limited per account +- **Calendar**: Events are drawn as solid blocks of their calendar's color; declined and cancelled events are outlined +- **UI**: Success and info toasts are plain cards; only errors and warnings are colored +- **Performance**: With many logins, the browser restores them four at a time and no longer reloads every login's folders, identities and push connections each time one of them connects (#1132, thanks @lucamzanon) +- **License**: An additional permission under section 7 of the AGPL allows distributing apps built from this code through app stores. It is provisional until every earlier contributor has agreed ([consent request](https://github.com/orgs/bulwarkmail/discussions/1113)) and applies in full to contributions made since 30 September 2026 +- **Docs**: Guidelines for AI-assisted contributions in the README and CONTRIBUTING.md + +### Fixes + +- **Mail**: Clicking a folder's unread count lists only that folder's unread mail, not unread mail from every folder of every account +- **Mail**: In "unread first" lists, a message you open stays in place until you open another +- **Mail**: The message list no longer flashes a reload right after the page opens +- **Mail**: On tablets, the message list comes back when the reading pane empties, for example after the open message is deleted or moved +- **Mail**: Dividers between rows no longer disappear at 125% or 150% display scaling +- **Mail**: The unread dot is centred on the sender avatar +- **Mail**: Attachments declared with a type the browser cannot show, such as `application/x-as400attachment` from IBM i systems, `application/x-pdf` or a catch-all type, preview according to their file name (#1127, thanks @dealerweb) +- **Send**: Recipients the server refuses at send are reported. When it refuses all of them, the message stays open as not sent; otherwise a warning names the refused ones (#1123) +- **Composer**: The message body stays reachable in short reading panes, such as the bottom reading pane on a laptop (#1114) +- **Composer**: Pasted plain text keeps its blank lines +- **Push**: A notification link waits for a login that is still reconnecting instead of reporting the account as signed out, opens the folder of the right account, and no longer pulls you away from something you opened in the meantime (#1131, thanks @lucamzanon) +- **Push**: A browser subscribed with another VAPID key resubscribes on its own, and Firefox can turn push on again when it cannot read its old subscription (#1121, thanks @shukiv) +- **Calendar**: Dragged events no longer disappear: all-day events moved in the month view keep their start, and occurrences of recurring events with a UTC start, as in Google Calendar exports, no longer shift by the time-zone offset (#1119) +- **Calendar**: A failed calendar fetch no longer hides every calendar or leaves only the birthday calendar selected +- **Calendar**: The all-day area of the week view is sized from the visible week, stacks each day's tasks under its all-day events, and collapses to three rows with a toggle (#1122, thanks @sanitz) +- **Calendar**: The Save button shows while an event is saving, and a save refused for its length says so (#921, thanks @texchi2) +- **Calendar**: Invitations no longer carry blank participant names or an empty description (#748, thanks @lucletoffe) +- **Files**: Files shared with you open and save in the office editor (#1094) +- **Files**: Office editing works behind a reverse proxy at a sub-path (`NEXT_PUBLIC_BASE_PATH`) (#1101, thanks @dealerweb) +- **Accounts**: Adding a sixth account through server-side SSO no longer overwrites the first account's sign-in +- **Mobile app**: The app's "Sign in via webmail" keeps working past the first token expiry when the webmail uses a confidential OAuth client or an identity provider on another host +- **Admin**: Admin sign-in works over plain HTTP. The admin cookie's Secure flag follows the request, or `COOKIE_SECURE` when it is set (#1063, thanks @lucamzanon) +- **Admin**: The OAuth scope fields show the actual default scopes, which do not include `offline_access` (#1126) +- **Lite**: SSO sessions survive a page reload with identity providers such as Rauthy that refuse an early token refresh (#552) +- **UI**: The app retries loading its configuration after a timeout or a failed request instead of staying broken (#1112, thanks @theLucius7) +- **Docker**: The image builds from a remote Git context (#1118) + +## 1.11.2 (2026-09-26) + +1.11.2 fixes the Docker image and the standalone tarballs of 1.11.1, which did not start. It contains all the security fixes from 1.11.1, so please update. + +Thank you for your donations: + +- _You? [Become a sponsor!](https://github.com/sponsors/bulwarkmail)_ + +**One-time** + +- Anonymous +- [@windsource](https://github.com/windsource) + +**Monthly** + +- [@jsaathof](https://github.com/jsaathof) +- [@berkersal](https://github.com/berkersal) +- [@NABarnes](https://github.com/NABarnes) +- [@felixzieger](https://github.com/felixzieger) +- [@pr0ton11](https://github.com/pr0ton11) +- [@zeddD1abl0](https://github.com/zeddD1abl0) +- [@fpauser](https://github.com/fpauser) +- [@proxforge](https://github.com/proxforge) +- [@spss20](https://github.com/spss20) +- [@elgringoYan](https://github.com/elgringoYan) +- [@pauladams8](https://github.com/pauladams8) +- [@djpriest](https://github.com/djpriest) +- [@umakers](https://github.com/umakers) +- [@zplizzi](https://github.com/zplizzi) +- [@jeremiah](https://github.com/jeremiah) +- [@Theoretisch1337](https://github.com/Theoretisch1337) +- [@svandive](https://github.com/svandive) +- [@HiltMundell](https://github.com/HiltMundell) + +### Fixes + +- **Docker**: The server starts again. 1.11.1 excluded `data/` from the standalone build with a pattern that also dropped Next.js's own metadata modules, so the Docker image and the `bulwark-standalone-*` tarballs failed on startup. `npm start` and Bulwark Lite were not affected + +## 1.11.1 (2026-09-26) + +1.11.1 is a security and bug-fix release. It fixes four reported vulnerabilities, two of them critical, and the findings of a security audit. Please update. + +Thank you for your donations: + +- _You? [Become a sponsor!](https://github.com/sponsors/bulwarkmail)_ + +**One-time** + +- Anonymous +- [@windsource](https://github.com/windsource) + +**Monthly** + +- [@jsaathof](https://github.com/jsaathof) +- [@berkersal](https://github.com/berkersal) +- [@NABarnes](https://github.com/NABarnes) +- [@felixzieger](https://github.com/felixzieger) +- [@pr0ton11](https://github.com/pr0ton11) +- [@zeddD1abl0](https://github.com/zeddD1abl0) +- [@fpauser](https://github.com/fpauser) +- [@proxforge](https://github.com/proxforge) +- [@spss20](https://github.com/spss20) +- [@elgringoYan](https://github.com/elgringoYan) +- [@pauladams8](https://github.com/pauladams8) +- [@djpriest](https://github.com/djpriest) +- [@umakers](https://github.com/umakers) +- [@zplizzi](https://github.com/zplizzi) +- [@jeremiah](https://github.com/jeremiah) +- [@Theoretisch1337](https://github.com/Theoretisch1337) +- [@svandive](https://github.com/svandive) +- [@HiltMundell](https://github.com/HiltMundell) + +### Security + +- **Admin**: Only a Stalwart superuser gets into the admin dashboard. The admin probe accepted Stalwart's default tenant-admin role, so the administrator of a single tenant was signed into a dashboard that configures the whole instance (GHSA-v6hr-cmxm-pv73, thanks @douwezijlstra-frl) +- **Admin**: Admin status is only taken from an admin-configured server. A context cookie minted while custom JMAP endpoints were allowed let a user-chosen server keep answering the admin probe after the switch was turned off (GHSA-j867-89p4-v8hm, thanks @Vip3r-MC) +- **API**: Cross-origin writes are refused on the JMAP passthrough and every other cookie-authenticated `/api/` route, not only `/api/auth/*`. A page on a same-site sibling origin could run arbitrary JMAP as the signed-in user. The gate also decides on the decoded path, so `/api/%61uth/...` no longer skips it (GHSA-9mvj-98f5-9q6g, thanks @kah-ja) +- **Admin**: Admin sign-in attempts are also capped at 50 per 15 minutes across all clients, because a forged `X-Forwarded-For` got a fresh per-IP budget when no reverse proxy is in front (GHSA-7pj2-232x-6698, thanks @richardweinberger) +- **Admin**: Impersonation no longer puts the Stalwart master password into the session cookie. The webmail creates an app password on the target mailbox that expires after 8 hours and is revoked on sign-out, and a used impersonation link is refused after a restart or on another replica +- **Mail**: A sender can no longer fake a DMARC or DKIM pass in the security badges, with a crafted envelope address or an `Authentication-Results` header of their own +- **Mail**: Opening an SVG attachment's thumbnail on its own no longer runs the sender's script in the webmail origin +- **Mail**: Remote content stays blocked in the mobile conversation view, the `.eml` attachment preview, the quoted original of a reply or forward, the print view, and for URL spellings the filter missed (backslashes, CSS escapes, `image-set()`) +- **Mail**: Links in image maps (``) no longer keep `window.opener` +- **Mail**: A `mailto:` unsubscribe goes to the single address in the link, and the confirmation shows recipient, subject and body before sending +- **Mail**: A crafted `winmail.dat` no longer freezes the tab +- **Composer**: A sender name containing a quote can no longer add a recipient to a draft +- **Filters**: Rule names, header names and sizes are escaped, so rules from plugins or imported filter sets cannot add commands such as `redirect` to the Sieve script +- **Plugins**: Hooks and slots need a declared permission, like the host API does. `http.post` can no longer reach the JMAP passthrough, `/api/admin/*`, `/api/settings` or other credentialed routes, and plugin storage is kept per account and deleted on sign-out +- **Themes**: The theme CSS sanitizer no longer lets remote resources through (`url(//host)`, CSS escapes, `image-set()`, `@font-face` sources), and theme CSS can only target `:root` and `.dark`, also when a plugin transforms it +- **Files**: WOPI file downloads are always served as inert attachments, so a blob typed `text/html` cannot run script in the webmail origin +- **Server**: The SSRF guard also blocks loopback beyond `127.0.0.1`, CGNAT, benchmark, multicast and reserved ranges, and NAT64, 6to4 and Teredo addresses that wrap an internal IPv4 address. Telemetry targets are checked at connect time, and OAuth token and revocation requests never follow redirects +- **Auth**: Synced settings are keyed on the account a bearer token belongs to, so on a multi-domain server `john@b.example` can no longer read the settings of `john@a.example` +- **Auth**: Wrong passwords tried through the login pre-check are limited, so the route can no longer be used as a password oracle or trip Stalwart's ban against the webmail itself +- **Auth**: Signing out ends office editor sessions opened in that browser, and a full sign-out clears search history, open tabs, Files recents, staged plugin uploads and the other accounts' leftovers, also in other open tabs +- **Auth**: Signing out when another account's restore had failed no longer leaves that account resumable +- **Auth**: The failed TOTP login no longer passes on a user-chosen server's error body +- **Server**: Visitors who are not signed in no longer get detailed health data, the pending advisory text, the plugin list, the full admin policy or every server's domain list +- **Server**: The setup token is passed in the URL fragment, so it stays out of access logs, referers and history +- **Server**: Not-found pages outside the app tree cannot be framed, `ALLOWED_FRAME_ANCESTORS` never applies to the admin dashboard or setup, and sibling subdomains can no longer widen the sidebar-app `frame-src` +- **Server**: Favicons are only served as raster images +- **Docker**: Runtime state and secrets (`data/`, `local-data/`, `.env`) stay out of the standalone build and the image, and the mock JMAP server can no longer be switched on in a release build +- **Lite**: Sign-out revokes the refresh token, and a failed token login no longer keeps the password in `sessionStorage` +- **Lite**: Every static page gets a CSP that allows only its own inline scripts, the Stalwart bundle refuses to run inside a foreign frame, and the Stalwart install instructions use a tagged release with a published `.sha256` instead of `releases/latest` + +### Features + +- **Calendar**: Tasks with a due date show in the month view (#1107) + +### Changes + +- **Plugins**: Hooks that change outgoing mail need `email:send`, and display takeovers need `email:render-takeover`. Plugins that don't declare them lose those hooks +- **Themes**: Theme CSS keeps only `:root` and `.dark` rules plus `@font-face`, `@keyframes`, `@media` and `@supports`. Every `url()` except a `#fragment` is removed +- **Admin**: Impersonated sessions end after 8 hours, and sessions minted by earlier versions are signed out +- **Server**: `/api/health?detailed=true` needs a session + +### Fixes + +- **Mail**: The inbox keeps rendering when a message has an unparsable date (#1099) +- **Mail**: A folder no longer switches back to the unified inbox while it loads (#1102, thanks @guisea) +- **Mail**: Replies in the unified inbox come from the identity of the account that received the mail (#1104) +- **Mail**: Mail deleted during a list refresh no longer reappears (#966) +- **Mail**: The message list no longer jumps while attachment chips load +- **Mail**: Scrolling the unified inbox, cross-account views, tag views and "All folders" search no longer skips messages +- **Mail**: A failed message-list read keeps the list on screen instead of showing an empty folder +- **Mail**: Marking read, starring, tagging, emptying a folder and cancelling a scheduled send report it when the server refuses them +- **Mail**: Tagging and pinning write only the keywords that change, so they no longer mark mail unread that was read on another device +- **Mail**: New mail and folder changes keep arriving for users with seven or more shared accounts +- **Send**: A dropped connection can no longer send a message twice +- **Send**: Undo and edit of a message sent from a group identity act in the group's own account +- **Composer**: A reply draft stays in its thread when it is re-opened or undone +- **Composer**: An open draft stays on its own account across an account switch +- **Accounts**: Quick account switches no longer mix up identities, so replies go out with the right From address +- **Accounts**: Folders, filters and the account security page no longer show the previous account's data after a switch +- **Accounts**: Settings sync turns back on after signing out of one of several accounts +- **Push**: A notification opens its message in the account it came from +- **Calendar**: Events you declined show struck through (#1110) +- **Calendar**: Daily recurring events keep going past a DST gap +- **Calendar**: iCal subscriptions stay with the login that created them, so refreshing or removing one no longer touches a calendar of another login +- **Auth**: SSO sign-in behind nginx no longer fails with a 502 when the cookies would overflow its header buffer (#1096) +- **Auth**: Sign-in and addresses work on internationalized domains (#1100) +- **Lite**: A rate-limited token endpoint no longer signs you out +- **i18n**: The dark/light mode titles and the "Themes" settings tab are translated in every language (#1105, #1106, thanks @dulinux), and so is the themes settings panel +- **i18n**: Updated Portuguese (Brazil) translation (#1106, thanks @dulinux) + ## 1.11.0 (2026-09-23) 1.11.0 introduces **Bulwark Lite**, a static build of the webmail that runs without a Node server, and fixes many places where Bulwark and Stalwart disagreed about mail, filters, calendars, contacts and files. It contains everything from the three 1.11.0 betas. The `latest` Docker tag moves to this release. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bc9c71a15..ff3c3fb6a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,6 +4,18 @@ Bug reports, feature requests, translations and patches are all welcome. The full guide is in the documentation under [Contributing](https://bulwarkmail.org/docs/development/contributing). It covers the development setup, the test suites, translations and right-to-left layouts, code style, and how pull requests are reviewed. +## What fits + +Read [What fits in Bulwark](https://bulwarkmail.org/docs/development/contributing#what-fits-in-bulwark) before you start on a feature. In short: + +- Bulwark is built for Stalwart. Changes for other JMAP servers are welcome if they cost Stalwart users nothing. +- Core is for what most people expect from a mail, calendar, contacts and files client. Niche workflows and integrations with other services belong in plugins. +- Not in core: IMAP or other non-JMAP backends, integrations with other services, Stalwart server administration, and changes to the look that go beyond themes. +- New behaviour gets one good default. If deployments really need different behaviour, add an admin setting, not a per-user toggle. +- Features must work in Bulwark Lite, or be hidden there, and UI changes must work at phone width. + +Open an issue and agree on the approach before you write a change that is larger than about 500 lines (not counting locales and tests), adds a runtime dependency, or touches sign-in, sessions, the HTML sanitizer, the plugin sandbox, outgoing-request guards or admin routes. Deliver large features as a series of pull requests that can each be reviewed on their own. Pull requests with review feedback unanswered for 30 days are closed. + To get a development server running: ```bash @@ -16,7 +28,9 @@ npm run dev Before you open a pull request, run `npm run typecheck && npm run lint && npx vitest run`. Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:` and so on). -By contributing, you agree that your contributions are licensed under the terms in [LICENSE](LICENSE): AGPL-3.0-only, with the additional permission for app store distribution. +You can use AI tools for your contributions. The guide's [AI-assisted contributions](https://bulwarkmail.org/docs/development/contributing#ai-assisted-contributions) section explains what we expect. + +By contributing, you agree that your contributions are licensed under the terms in [LICENSE](LICENSE): AGPL-3.0-only, with the additional permission for app store distribution. The permission is still provisional for older code, but it applies in full to contributions made since 30 September 2026. - Questions: ask on [Discord](https://discord.gg/tYCujymGrT). - Documentation fixes: the docs are Markdown files in the [website repository](https://github.com/bulwarkmail/website/tree/main/docs). diff --git a/Dockerfile b/Dockerfile index cd12db324..c9efc1cfa 100644 --- a/Dockerfile +++ b/Dockerfile @@ -21,7 +21,16 @@ ENV NEXT_PUBLIC_DEFAULT_LOCALE=$NEXT_PUBLIC_DEFAULT_LOCALE # `git rev-parse` inside the build can't find it - CI must pass it in. ARG GIT_COMMIT=unknown ENV GIT_COMMIT=$GIT_COMMIT -RUN npx next build --webpack +# The mock JMAP server (DEV_MOCK_JMAP) accepts any password and is for +# `npm run dev` only; images ship without it. +# `next build` type-checks every .ts file, and some unit tests import the +# deleted route, so the tests go too. .dockerignore already drops them from a +# local context, but a remote Git context never applies .dockerignore (#1118). +RUN rm -rf "app/api/dev-jmap" && \ + find . -path ./node_modules -prune -o \ + \( -name __tests__ -o -name "*.test.ts" -o -name "*.test.tsx" \) \ + -prune -exec rm -rf {} \; && \ + npx next build --webpack FROM node:24-alpine AS runner diff --git a/LICENSE b/LICENSE index 305becf11..d6e0a9a05 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,8 @@ Copyright (C) 2025-2026 Bulwark Project Authors This project is licensed under the GNU Affero General Public License, version 3 only, with the additional permission for app store -distribution below. +distribution below. That permission is provisional; see the +reservation at its end. This repository includes material derived from earlier MIT-licensed work. The original attribution notice preserved for the fork lineage is available @@ -41,6 +42,26 @@ holders license under this License; it does not extend to parts licensed under other terms. As section 7 of this License allows, you may remove this permission from copies you convey and from your modified versions. +Reservation + +This additional permission has not been finalized. The contributors of +earlier parts of this Program have been asked whether they agree to it: +https://github.com/orgs/bulwarkmail/discussions/1113 + +Until that request is settled, the permission is granted subject to this +reservation: + + - It applies to all contributions made on or after 30 September 2026. + These contributions are accepted under this License together with + this permission. + + - It applies to parts of this Program written before that date only + where their copyright holders have agreed to it. Parts whose + copyright holders do not agree will be rewritten or removed. + +This reservation will be removed once every earlier contributor has +agreed or their parts have been replaced. + GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 diff --git a/NOTICE b/NOTICE index ad2b31317..284947e7e 100644 --- a/NOTICE +++ b/NOTICE @@ -32,3 +32,10 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Third-party artwork: + +- Flag icons in components/ui/flag-icons.tsx are from Twemoji + (https://github.com/jdecked/twemoji), Copyright 2019 Twitter, Inc and + other contributors, licensed under CC-BY 4.0 + (https://creativecommons.org/licenses/by/4.0/). diff --git a/README.md b/README.md index fa1ada8a8..930072229 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ latest release  docker: ghcr.io/bulwarkmail/webmail  license: AGPL v3  - Discord members online + Discord members

@@ -32,6 +32,7 @@ Bulwark Webmail is a self-hosted webmail client for [Stalwart Mail Server](https - [Configuration](#configuration) - [Documentation](#documentation) - [Development](#development) +- [Use of AI](#use-of-ai) - [Community and support](#community-and-support) - [License](#license) @@ -83,6 +84,8 @@ Then open `http://localhost:3000`. A setup wizard asks for your Stalwart server [Updating](https://bulwarkmail.org/docs/deployment/updating) explains how to move to a new version. +Container images and release files from 1.12.0 on come with a signed build provenance attestation. To check that one was built by this repository's workflows, run `gh attestation verify oci://ghcr.io/bulwarkmail/webmail: --owner bulwarkmail` for an image, or `gh attestation verify --repo bulwarkmail/webmail` for a downloaded file. Release files also have a `.sha256` next to them. + ## Configuration Most installs are set up in the wizard on first launch and changed later in the [admin dashboard](https://bulwarkmail.org/docs/guides/admin). You can also use environment variables, which fit read-only or immutable deployments better. When both set the same key, the value saved in the admin config wins, so an environment variable only fills in what the admin config leaves unset. @@ -135,6 +138,14 @@ The [contributing guide](https://bulwarkmail.org/docs/development/contributing) The stack: [Next.js 16](https://nextjs.org/) and React 19, TypeScript, [Tailwind CSS v4](https://tailwindcss.com/), [Zustand](https://zustand-demo.pmnd.rs/), [Tiptap](https://tiptap.dev/), [next-intl](https://next-intl-docs.vercel.app/), [Tabler Icons](https://tabler.io/icons), and our own JMAP client (RFC 8620). Tests run on [Vitest](https://vitest.dev/) and [Playwright](https://playwright.dev/). +## Use of AI + +AI tools are part of how Bulwark is developed. A change is held to the same standard whether a person or a tool wrote it: it has to be understood, reviewed and pass the checks and tests before it is merged. + +Bulwark itself has no AI features and doesn't send your mail, contacts, calendar or files to an AI service. If your Stalwart server classifies spam with an LLM, Bulwark shows the verdict, but the classification happens on your server. + +Contributors can use AI tools too, as long as they use capable, current models and not small or outdated ones. The [contributing guide](https://bulwarkmail.org/docs/development/contributing#ai-assisted-contributions) explains what we expect. + ## Community and support - Questions: check [Troubleshooting](https://bulwarkmail.org/docs/guides/troubleshooting), then ask on [Discord](https://discord.gg/tYCujymGrT). @@ -144,7 +155,7 @@ The stack: [Next.js 16](https://nextjs.org/) and React 19, TypeScript, [Tailwind ## License -[GNU AGPL v3 only](LICENSE), with an additional permission to distribute apps built from this code through app stores such as the Apple App Store and Google Play. This repository preserves the original MIT attribution for the fork lineage in [NOTICE](NOTICE). +[GNU AGPL v3 only](LICENSE), with an additional permission to distribute apps built from this code through app stores such as the Apple App Store and Google Play. The permission is provisional until every earlier contributor has agreed to it ([consent request](https://github.com/orgs/bulwarkmail/discussions/1113)); contributions made since 30 September 2026 are already covered. This repository preserves the original MIT attribution for the fork lineage in [NOTICE](NOTICE). ## Acknowledgments diff --git a/VERSION b/VERSION index 1cac385c6..63e799cf4 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.0 +1.14.1 diff --git a/app/(main)/[locale]/auth/callback/page.tsx b/app/(main)/[locale]/auth/callback/page.tsx index 3a51a93af..380ac321d 100644 --- a/app/(main)/[locale]/auth/callback/page.tsx +++ b/app/(main)/[locale]/auth/callback/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { Suspense, useEffect, useState } from "react"; +import { Suspense, useEffect, useRef, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { useTranslations } from "next-intl"; import { useAuthStore } from "@/stores/auth-store"; @@ -18,8 +18,14 @@ function OAuthCallbackInner() { const t = useTranslations("login"); const { loginWithOAuth, loginWithServerSso } = useAuthStore(); const [error, setError] = useState(null); + // The authorization code is single-use. React's development double effect + // ran this twice: the second pass no longer saw the pairing re-auth flag + // (the first had removed it) and spent the code on the login flow instead. + const handledRef = useRef(false); useEffect(() => { + if (handledRef.current) return; + handledRef.current = true; const code = searchParams.get("code"); const state = searchParams.get("state"); const errorParam = searchParams.get("error"); @@ -38,9 +44,13 @@ function OAuthCallbackInner() { // via prompt=login. Don't create a login session — just confirm the fresh // auth (sets the short-lived pairing proof cookie) and bounce back to the // Security settings, where the QR generation auto-resumes. + // The flag holds the state the step-up started with; one left behind by an + // abandoned round trip is dropped here instead of capturing this login. let pairReauthResume = false; try { - pairReauthResume = sessionStorage.getItem("pair_reauth_resume") === "1"; + const resumeState = sessionStorage.getItem("pair_reauth_resume"); + pairReauthResume = !!state && resumeState === state; + if (resumeState !== null && !pairReauthResume) sessionStorage.removeItem("pair_reauth_resume"); } catch { /* sessionStorage unavailable */ } if (pairReauthResume && state) { try { sessionStorage.removeItem("pair_reauth_resume"); } catch { /* ignore */ } diff --git a/app/(main)/[locale]/layout.tsx b/app/(main)/[locale]/layout.tsx index ce7e7a1db..5e6f64cac 100644 --- a/app/(main)/[locale]/layout.tsx +++ b/app/(main)/[locale]/layout.tsx @@ -9,6 +9,7 @@ import { ProtocolLaunchHandlerProvider } from "@/components/protocol/protocol-la import { ProInterfaceRedirect } from "@/components/pro/pro-interface-redirect"; import { ImpersonationReconciler } from "@/components/impersonation/impersonation-reconciler"; import { PluginDialogHost } from "@/components/plugins/plugin-dialog-host"; +import { QuickRuleHost } from "@/components/filters/quick-rule-host"; import { PluginConsentDialog } from "@/components/plugins/plugin-consent-dialog"; import { PluginOAuthCallbackListener } from "@/components/providers/plugin-oauth-callback-listener"; import { PWAInstallPrompt } from "@/components/pwa-install-prompt"; @@ -55,6 +56,7 @@ export default async function LocaleLayout({ {children} + diff --git a/app/(main)/[locale]/login/page.tsx b/app/(main)/[locale]/login/page.tsx index 810e46e4c..413ab869a 100644 --- a/app/(main)/[locale]/login/page.tsx +++ b/app/(main)/[locale]/login/page.tsx @@ -14,11 +14,12 @@ import { useConfig } from "@/hooks/use-config"; import { useMenuNavigation } from "@/hooks/use-menu-navigation"; import { apiFetch, getPathPrefix, toRouterPath, withBasePath } from "@/lib/browser-navigation"; import { cn } from "@/lib/utils"; -import { AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play, Copy } from "@/components/icons"; +import { AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play, Copy, KeyRound } from "@/components/icons"; import { type OAuthMetadata } from "@/lib/oauth/discovery"; import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce"; +import { DEFAULT_OAUTH_SCOPES } from "@/lib/oauth/scopes"; import { useUpdateStore, selectBanner } from "@/stores/update-store"; -import type { PublicJmapServerEntry } from "@/lib/admin/jmap-servers"; +import { offersOwnOAuth, type PublicJmapServerEntry } from "@/lib/admin/jmap-servers"; import { IS_LITE, getLiteInjectedClientId } from "@/lib/lite"; import { getLiteClientId, probeLiteTokenLogin } from "@/lib/auth/lite-tokens"; import { @@ -154,9 +155,9 @@ function LoginPageContent() { : ""; const mobileState = mobileRedirectUri ? rawMobileState : ""; const isMobileHandoff = Boolean(mobileRedirectUri); - const { login, loginDemo, isLoading, error, clearError, isAuthenticated } = useAuthStore(); + const { login, loginWithToken, loginDemo, isLoading, error, clearError, isAuthenticated } = useAuthStore(); const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme }))); - const { appName, jmapServerUrl: configuredServerUrl, oauthEnabled, oauthOnly, oauthClientId: globalOauthClientId, oauthIssuerUrl: globalOauthIssuerUrl, oauthScopes, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, loginLogoMaxHeight, loginLogoMaxWidth, loginShowHeading, loginShowSubtitle, loginShowTotp, loginShowVersion, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode, allowCustomJmapEndpoint, jmapServers, jmapServerAutoPickByDomain } = useConfig(); + const { appName, jmapServerUrl: configuredServerUrl, oauthEnabled, oauthOnly, oauthClientId: globalOauthClientId, oauthIssuerUrl: globalOauthIssuerUrl, oauthScopes, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, loginLogoMaxHeight, loginLogoMaxWidth, loginShowHeading, loginShowSubtitle, loginShowTotp, loginShowTokenLogin, loginShowVersion, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode, allowCustomJmapEndpoint, jmapServers, jmapServerAutoPickByDomain } = useConfig(); const resolvedTheme = useThemeStore((s) => s.resolvedTheme); // Login logo sizing: when a max height/width is configured, drop the fixed @@ -167,7 +168,8 @@ function LoginPageContent() { : undefined; const [formData, setFormData] = useState({ - username: "", + // An account restored from the list backup opens this form with its address. + username: isAddAccountMode ? searchParams.get("username") ?? "" : "", password: "", }); const [jmapEndpoint, setJmapEndpoint] = useState(""); @@ -187,8 +189,17 @@ function LoginPageContent() { const effectiveOauthIssuerUrl = selectedServer ? selectedServer.oauth?.issuerUrl || selectedServer.url : globalOauthIssuerUrl; + // A server entry that names its own OAuth client and button label signs in + // with OAuth even while OAuth is off globally: a Gmail bridge next to a + // password server. + const serverOauthEnabled = oauthEnabled || offersOwnOAuth(selectedServer); const [totpCode, setTotpCode] = useState(""); const [showTotpField, setShowTotpField] = useState(false); + // Access-token sign-in (Bearer auth) in place of username and password. + // The mobile hand-off passes a password on to the app, so it has none. + const [tokenMode, setTokenMode] = useState(false); + const [accessToken, setAccessToken] = useState(""); + const signInWithToken = tokenMode && loginShowTokenLogin && !isMobileHandoff; const [rememberMe, setRememberMe] = useState(false); // Lite (no server session): "remember me" needs Stalwart's token login on the // target server. Probe it once per URL and hide the box when it is missing; @@ -212,6 +223,7 @@ function LoginPageContent() { const inputRef = useRef(null); const justSelectedSuggestion = useRef(false); const totpInputRef = useRef(null); + const tokenInputRef = useRef(null); const prevError = useRef(null); const themeMenuRef = useRef(null); const themeButtonRef = useRef(null); @@ -256,7 +268,7 @@ function LoginPageContent() { // (the endpoint is rate limited). const [liteOAuthByDomain, setLiteOAuthByDomain] = useState<{ domain: string; discovery: LiteOAuthDiscovery | null } | null>(null); const [liteOAuthFailed, setLiteOAuthFailed] = useState(false); - const liteDomain = LITE_OAUTH_AVAILABLE ? completeAddressDomain(formData.username) : ""; + const liteDomain = LITE_OAUTH_AVAILABLE && !signInWithToken ? completeAddressDomain(formData.username) : ""; const liteAccount = liteDomain ? formData.username.trim() : ""; useEffect(() => { if (!liteAccount || !probeTarget) return; @@ -417,7 +429,7 @@ function LoginPageContent() { }, [serverUrl]); useEffect(() => { - if (!oauthEnabled || !serverUrl) return; + if (!serverOauthEnabled || !serverUrl) return; setOauthDiscoveryDone(false); setOauthMetadata(null); const controller = new AbortController(); @@ -440,7 +452,7 @@ function LoginPageContent() { setOauthDiscoveryDone(true); }); return () => controller.abort(); - }, [oauthEnabled, serverUrl, effectiveOauthIssuerUrl, selectedServer?.id]); + }, [serverOauthEnabled, serverUrl, effectiveOauthIssuerUrl, selectedServer?.id]); // Auto-SSO: when enabled with OAUTH_ONLY, skip the login page entirely const ssoError = searchParams.get("sso_error"); @@ -685,6 +697,7 @@ function LoginPageContent() { clientId, redirectUri, persistent: rememberMeEnabled && rememberMe, + revocationEndpoint: discovery.metadata.revocation_endpoint, }); const authUrl = new URL(discovery.metadata.authorization_endpoint); @@ -703,12 +716,36 @@ function LoginPageContent() { window.location.href = authUrl.toString(); }; - const handleOAuthLogin = async () => { - if (LITE_OAUTH_AVAILABLE) { + /** + * Starts OAuth for the selected server, or for `target`: a server in the + * list with its own OAuth client (a Gmail bridge, say), offered on the page + * whichever server is selected so that "Sign in with Google" is one tap. + */ + const handleOAuthLogin = async (target?: PublicJmapServerEntry) => { + if (LITE_OAUTH_AVAILABLE && !target) { await startLiteOAuth(probeTarget); return; } - if (!oauthMetadata || !effectiveOauthClientId) return; + const server = target ?? selectedServer; + const clientId = target ? target.oauth?.clientId : effectiveOauthClientId; + let metadata = target ? null : oauthMetadata; + if (target) { + setOauthLoading(true); + setSelectedServerId(target.id); + try { + const res = await apiFetch(`/api/auth/oauth/metadata?server_id=${encodeURIComponent(target.id)}`); + metadata = res.ok ? ((await res.json()) as OAuthMetadata) : null; + } catch { + metadata = null; + } + if (!metadata) { + // The target is now the selected server: its discovery runs again and + // the page shows the usual "discovery failed" notice. + setOauthLoading(false); + return; + } + } + if (!metadata || !clientId) return; // In mobile-handoff mode the client-side PKCE flow doesn't help us: // tokens would land in sessionStorage on the webmail origin and the // mobile app couldn't read them. Route through the server-side SSO @@ -728,14 +765,14 @@ function LoginPageContent() { // Resolve the JMAP URL to send to the callback. Server-list entries win // over the custom-endpoint input, which wins over the global server URL. - const oauthServerUrl = selectedServer?.url + const oauthServerUrl = server?.url || (allowCustomJmapEndpoint ? jmapEndpoint : configuredServerUrl); sessionStorage.setItem("oauth_code_verifier", verifier); sessionStorage.setItem("oauth_state", state); sessionStorage.setItem("oauth_server_url", oauthServerUrl!); - if (selectedServer?.id) { - sessionStorage.setItem("oauth_server_id", selectedServer.id); + if (server?.id) { + sessionStorage.setItem("oauth_server_id", server.id); } else { sessionStorage.removeItem("oauth_server_id"); } @@ -753,11 +790,11 @@ function LoginPageContent() { const nextSlot = useAccountStore.getState().getNextCookieSlot(); sessionStorage.setItem("oauth_cookie_slot", nextSlot.toString()); - const authUrl = new URL(oauthMetadata.authorization_endpoint); + const authUrl = new URL(metadata.authorization_endpoint); authUrl.searchParams.set("response_type", "code"); - authUrl.searchParams.set("client_id", effectiveOauthClientId); + authUrl.searchParams.set("client_id", clientId); authUrl.searchParams.set("redirect_uri", redirectUri); - authUrl.searchParams.set("scope", oauthScopes || "openid email profile"); + authUrl.searchParams.set("scope", oauthScopes || DEFAULT_OAUTH_SCOPES); authUrl.searchParams.set("state", state); authUrl.searchParams.set("code_challenge", challenge); authUrl.searchParams.set("code_challenge_method", "S256"); @@ -775,6 +812,12 @@ function LoginPageContent() { // when the admin hasn't configured a server list. const effectiveServerUrl = selectedServer?.url || (allowCustomJmapEndpoint ? jmapEndpoint : serverUrl); + if (signInWithToken) { + if (await loginWithToken(effectiveServerUrl, accessToken, rememberMeEnabled && rememberMe)) { + router.push('/'); + } + return; + } // Lite on Stalwart: an account whose domain signs in at an external // provider has no password Stalwart could check. Asked again here (cached) // because Enter can beat the debounced lookup; a name without a domain is @@ -808,7 +851,9 @@ function LoginPageContent() { ); if (success) { - saveUsername(formData.username); + // Suggested again on this browser only when the user did not decline + // being remembered: on a shared computer the next person sees the list. + if (!rememberMeEnabled || rememberMe) saveUsername(formData.username); if (isMobileHandoff) { // The isAuthenticated effect handles the redirect; nothing else to // do here. Don't push to / - that would race the deep link. @@ -880,6 +925,27 @@ function LoginPageContent() { ) : null; + // Other servers in the list that sign in with their own OAuth client get a + // button of their own, so signing in with Google does not first mean finding + // the bridge in the server menu. Not in mobile handoff, which signs in + // server-side against the selected server. + const otherOauthServers = isMobileHandoff + ? [] + : jmapServers.filter((s) => offersOwnOAuth(s) && s.id !== selectedServer?.id); + const otherOauthButtons = otherOauthServers.map((s) => ( + + )); + // Demo-only mode: show only a large demo login button if (demoMode && !isAddAccountMode) { return ( @@ -1196,7 +1262,7 @@ function LoginPageContent() { @@ -1254,8 +1320,9 @@ function LoginPageContent() { )} - {/* Username field */} -

+ {/* Username field. The access token names the account, so + token sign-in has none. */} +
@@ -1270,7 +1337,7 @@ function LoginPageContent() { onKeyDown={handleKeyDown} className="h-11 px-3.5 bg-muted/40 border-border/60 rounded-xl focus:bg-background focus:border-primary/50 transition-all duration-200" placeholder={t("username_placeholder")} - required + required={!signInWithToken} autoComplete="off" data-form-type="other" data-lpignore="true" @@ -1311,7 +1378,7 @@ function LoginPageContent() { {/* Password field. Hidden for an account that signs in at an external provider (Lite on Stalwart): the submit button is the SSO button then. */} -
+
@@ -1323,7 +1390,7 @@ function LoginPageContent() { onChange={(e) => setFormData({ ...formData, password: e.target.value })} className="h-11 px-3.5 pe-11 bg-muted/40 border-border/60 rounded-xl focus:bg-background focus:border-primary/50 transition-all duration-200" placeholder={t("password_placeholder")} - required={!liteSsoRequired} + required={!liteSsoRequired && !signInWithToken} autoComplete="current-password" />
+ {signInWithToken && ( +
+ + setAccessToken(e.target.value)} + className="h-11 px-3.5 bg-muted/40 border-border/60 rounded-xl focus:bg-background focus:border-primary/50 transition-all duration-200 font-mono" + placeholder={t("token_placeholder")} + required + autoComplete="off" + spellCheck={false} + data-lpignore="true" + /> +

+ {t("token_hint")} +

+
+ )} + {/* 2FA toggle / field. The manual toggle can be hidden via LOGIN_SHOW_TOTP (loginShowTotp) for deployments whose mail server has no per-account TOTP (auth delegated to an external directory); server-required TOTP still shows. */} - {liteSsoRequired ? null : !showTotpField ? ( + {liteSsoRequired || signInWithToken ? null : !showTotpField ? ( loginShowTotp ? ( + )} + {/* Remember me */} {showRememberMe && (
diff --git a/app/(main)/admin/_tabs/auth.tsx b/app/(main)/admin/_tabs/auth.tsx index 7034407a1..2b3b977b1 100644 --- a/app/(main)/admin/_tabs/auth.tsx +++ b/app/(main)/admin/_tabs/auth.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react'; import { Save, Loader2, RotateCcw, Sparkles } from '@/components/icons'; import { apiFetch } from '@/lib/browser-navigation'; +import { DEFAULT_OAUTH_SCOPES } from '@/lib/oauth/scopes'; interface ConfigEntry { // Sensitive keys (sessionSecret, oauthClientSecret) come back with @@ -274,8 +275,8 @@ export function AuthTab() { - - + +
diff --git a/app/(main)/admin/_tabs/policy.tsx b/app/(main)/admin/_tabs/policy.tsx index 29c1a6a56..b7cdfa667 100644 --- a/app/(main)/admin/_tabs/policy.tsx +++ b/app/(main)/admin/_tabs/policy.tsx @@ -32,16 +32,19 @@ const FEATURE_GATE_LABELS: Partial + @@ -162,10 +163,10 @@ export function SettingsTab() { - +

- Point the client URL at a WOPI-compatible office suite (Collabora Online, OnlyOffice, EuroOffice, …) to let users edit documents in Files. The host override is only needed when the editor reaches this webmail under a different address than the browser does (e.g. Docker networks). The editor must also allow this webmail as a WOPI host. + Point the client URL at a WOPI-compatible office suite (Collabora Online, OnlyOffice, EuroOffice, …) to let users edit documents in Files. The client URL may be an internal address: the browser loads the editor from the address its discovery advertises. The host override is only needed when the editor reaches this webmail under a different address than the browser does (e.g. Docker networks); give the address alone, the webmail's base path is added to it. The editor must also allow this webmail as a WOPI host.

diff --git a/app/(main)/setup/page.tsx b/app/(main)/setup/page.tsx index befc56f74..af8de969c 100644 --- a/app/(main)/setup/page.tsx +++ b/app/(main)/setup/page.tsx @@ -1,9 +1,10 @@ 'use client'; import { useEffect, useState, type FormEvent, type ReactNode } from 'react'; -import { useRouter, useSearchParams } from 'next/navigation'; +import { useRouter } from 'next/navigation'; import { CheckCircle2, AlertTriangle, AlertCircle, Server, ShieldCheck, KeyRound, FileText, Palette, Lock, ShieldAlert } from '@/components/icons'; import { apiFetch, getPathPrefix, withBasePath } from '@/lib/browser-navigation'; +import { takeSetupTokenFromUrl } from '@/lib/setup/url-token'; type State = 'bootstrap' | 'configured' | 'env-managed'; @@ -93,7 +94,7 @@ const STEPS = [ export default function SetupWizardPage() { const router = useRouter(); - const searchParams = useSearchParams(); + const [tokenFromUrl, setTokenFromUrl] = useState(''); const [bootstrapping, setBootstrapping] = useState(true); const [error, setError] = useState(null); @@ -110,6 +111,7 @@ export default function SetupWizardPage() { const [insecureAcknowledged, setInsecureAcknowledged] = useState(false); useEffect(() => { setInsecureContext(detectInsecureContext()); + setTokenFromUrl(takeSetupTokenFromUrl(window.location, window.history)); }, []); // ─── Initial status load ──────────────────────────────────────────────── @@ -222,7 +224,7 @@ export default function SetupWizardPage() { {!authenticated ? ( { try { await submitToken(t); @@ -500,6 +502,7 @@ function WelcomeStep({ tokenFromUrl, onSubmit }: { tokenFromUrl: string; onSubmi // Auto-submit if token came in via URL. useEffect(() => { if (tokenFromUrl && !submitting) { + setToken(tokenFromUrl); setSubmitting(true); onSubmit(tokenFromUrl).finally(() => setSubmitting(false)); } diff --git a/app/api/account-archive/route.ts b/app/api/account-archive/route.ts new file mode 100644 index 000000000..c17b67e18 --- /dev/null +++ b/app/api/account-archive/route.ts @@ -0,0 +1,87 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { cookies } from 'next/headers'; +import { configManager } from '@/lib/admin/config-manager'; +import { hasSessionSecret } from '@/lib/auth/session-secret'; +import { readStalwartAuthContextFromStore } from '@/lib/stalwart/auth-context'; +import { assertBasicAuthMatchesUsername, verifyJmapAuth } from '@/lib/auth/verify-jmap-auth'; +import { parseJmapServers, resolveTrustedJmapUrl } from '@/lib/admin/jmap-servers'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; +import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; +import { archiveIdentity, parseArchiveEnvelope, ARCHIVE_MAX_BYTES, type ArchiveOwner } from '@/lib/account-archive'; +import { deleteArchive, loadArchive, saveArchive } from '@/lib/account-archive-storage'; + +export const runtime = 'nodejs'; + +const reply = (data: unknown, status = 200) => NextResponse.json(data, { + status, headers: { 'Cache-Control': 'no-store' }, +}); + +/** + * The owner whose archive this request may touch, or the response refusing it. + * + * A session cookie alone is not enough: cookies for admin-configured servers + * can outlive the credential inside them. So the credential in the matching + * slot is checked against the mail server on every call, and listing is held + * to the same rule as writing, since the ciphertext is what an offline + * password guess would need. + */ +async function verifiedOwner(request: NextRequest): Promise { + await configManager.ensureLoaded(); + if (!configManager.getPolicy().features.accountArchiveEnabled || !hasSessionSecret()) return reply({ error: 'disabled' }, 404); + const denied = reply({ error: 'owner_signin_required' }, 403); + let claimed: string; + try { + claimed = archiveIdentity({ + username: request.headers.get('x-archive-username') ?? '', + serverUrl: request.headers.get('x-archive-server') ?? '', + }); + } catch { return denied; } + const store = await cookies(); + for (let slot = 0; slot < MAX_ACCOUNT_SLOTS; slot++) { + const ctx = readStalwartAuthContextFromStore(store, slot); + if (!ctx) continue; + try { if (archiveIdentity(ctx) !== claimed) continue; } catch { continue; } + try { + // The cookie's own username, not the header's: the two may differ in case. + assertBasicAuthMatchesUsername(ctx.authHeader, ctx.username); + const trusted = resolveTrustedJmapUrl(ctx.serverUrl, + configManager.get('jmapServerUrl', ''), + parseJmapServers(configManager.get('jmapServers', []))); + await verifyJmapAuth(ctx.serverUrl, ctx.authHeader, { trusted: !!trusted }); + } catch { return denied; } + return { username: ctx.accountName ?? ctx.username, serverUrl: ctx.serverUrl }; + } + return denied; +} + +export async function GET(request: NextRequest) { + const owner = await verifiedOwner(request); + if (owner instanceof NextResponse) return owner; + try { return reply({ envelope: await loadArchive(owner) }); } + catch { return reply({ error: 'storage_failed' }, 500); } +} + +export async function PUT(request: NextRequest) { + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; + const owner = await verifiedOwner(request); + if (owner instanceof NextResponse) return owner; + if (Number(request.headers.get('content-length') ?? 0) > ARCHIVE_MAX_BYTES) return reply({ error: 'too_large' }, 413); + let envelope; + try { + const text = await request.text(); + if (text.length > ARCHIVE_MAX_BYTES) return reply({ error: 'too_large' }, 413); + envelope = parseArchiveEnvelope((JSON.parse(text) as { envelope?: unknown })?.envelope); + } catch { return reply({ error: 'invalid_archive' }, 400); } + try { await saveArchive(owner, envelope); return reply({ ok: true }); } + catch { return reply({ error: 'storage_failed' }, 500); } +} + +export async function DELETE(request: NextRequest) { + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; + const owner = await verifiedOwner(request); + if (owner instanceof NextResponse) return owner; + try { await deleteArchive(owner); return reply({ ok: true }); } + catch { return reply({ error: 'storage_failed' }, 500); } +} diff --git a/app/api/account/stalwart/jmap/route.ts b/app/api/account/stalwart/jmap/route.ts index 0fa2bc340..eee53e22f 100644 --- a/app/api/account/stalwart/jmap/route.ts +++ b/app/api/account/stalwart/jmap/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; import { logger } from '@/lib/logger'; import { configManager } from '@/lib/admin/config-manager'; import { getStalwartCredentials } from '@/lib/stalwart/credentials'; @@ -18,6 +19,10 @@ import { DisallowedUrlError } from '@/lib/security/url-guard'; * methods under the `x:` namespace on the same endpoint. */ export async function POST(request: NextRequest) { + // CSRF gate (GHSA-9mvj-98f5-9q6g): this handler acts with the caller's + // session cookie, which SameSite=Lax still sends from a same-site page. + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; // Registered unconditionally by Next, so the switch lives here: when the // passthrough (or Stalwart features as a whole) is disabled the route // does not exist as far as callers are concerned. Checked before the diff --git a/app/api/admin/auth/route.ts b/app/api/admin/auth/route.ts index 537d9e888..baaf584b8 100644 Binary files a/app/api/admin/auth/route.ts and b/app/api/admin/auth/route.ts differ diff --git a/app/api/admin/marketplace/route.ts b/app/api/admin/marketplace/route.ts index 914d88b46..b218c4ea3 100644 --- a/app/api/admin/marketplace/route.ts +++ b/app/api/admin/marketplace/route.ts @@ -20,7 +20,7 @@ import { } from '@/lib/admin/csp-frame-origins'; import JSZip from 'jszip'; import { MAX_PLUGIN_SIZE, MAX_THEME_SIZE, ALL_PERMISSIONS } from '@/lib/plugin-types'; -import { sanitizeThemeCSS, validateThemeCSSSafety } from '@/lib/theme-loader'; +import { sanitizeThemeCSS } from '@/lib/theme-loader'; import { configManager } from '@/lib/admin/config-manager'; async function getDirectoryUrl(): Promise { @@ -202,14 +202,12 @@ export async function POST(request: NextRequest) { let css = await cssFile.async('string'); - // Validate and sanitize CSS + // Sanitize unconditionally: the safety check is advisory, and the + // sanitizer is also what drops rules outside :root and .dark. const warnings: string[] = []; - const safety = validateThemeCSSSafety(css); - if (!safety.valid) { - const sanitized = sanitizeThemeCSS(css); - css = sanitized.css; - warnings.push(...sanitized.warnings); - } + const sanitized = sanitizeThemeCSS(css); + css = sanitized.css; + warnings.push(...sanitized.warnings); const existingTheme = await getTheme(resolvedId); const isUpdate = existingTheme !== null; diff --git a/app/api/admin/policy/route.ts b/app/api/admin/policy/route.ts index a858cf79d..56b3b8910 100644 --- a/app/api/admin/policy/route.ts +++ b/app/api/admin/policy/route.ts @@ -3,15 +3,34 @@ import { configManager } from '@/lib/admin/config-manager'; import { requireAdminAuth, getClientIP } from '@/lib/admin/session'; import { auditLog } from '@/lib/admin/audit'; import { logger } from '@/lib/logger'; -import type { SettingsPolicy } from '@/lib/admin/types'; +import { POLICY_SCOPE_HEADER, type SettingsPolicy } from '@/lib/admin/types'; +import { canSeeInstanceDetails } from '@/lib/auth/instance-details'; /** - * GET /api/admin/policy - Get settings policy (NOT admin-protected - users read this) + * GET /api/admin/policy - Get settings policy (NOT admin-protected - users read this; + * visitors who are not signed in get the subset the login page needs) */ -export async function GET() { +export async function GET(request: NextRequest) { try { await configManager.ensureLoaded(); const policy = configManager.getPolicy(); + if (!(await canSeeInstanceDetails(request))) { + // The login page needs the theme policy and gates; the plugin lists, + // push relays and sidebar app URLs map the deployment and are only + // used after signing in, when the client fetches the policy again. + return NextResponse.json( + { + ...policy, + forceEnabledPlugins: [], + approvedPlugins: [], + pushRelays: [], + pushRelayUrl: '', + pushRelayUrlLocked: false, + defaultSidebarApps: [], + }, + { headers: { 'Cache-Control': 'no-store', [POLICY_SCOPE_HEADER]: 'public' } }, + ); + } return NextResponse.json(policy, { headers: { 'Cache-Control': 'no-store' }, }); diff --git a/app/api/admin/themes/route.ts b/app/api/admin/themes/route.ts index 74bb9ea1b..f600d09b6 100644 --- a/app/api/admin/themes/route.ts +++ b/app/api/admin/themes/route.ts @@ -11,7 +11,7 @@ import { import JSZip from 'jszip'; import { MAX_THEME_SIZE } from '@/lib/plugin-types'; -import { sanitizeThemeCSS, validateThemeCSSSafety } from '@/lib/theme-loader'; +import { sanitizeThemeCSS } from '@/lib/theme-loader'; /** * GET /api/admin/themes - List all admin-managed themes @@ -118,14 +118,12 @@ export async function POST(request: NextRequest) { let css = await cssFile.async('string'); - // Validate and sanitize CSS + // Sanitize unconditionally: the safety check is advisory, and the + // sanitizer is also what drops rules outside :root and .dark. const warnings: string[] = []; - const safety = validateThemeCSSSafety(css); - if (!safety.valid) { - const sanitized = sanitizeThemeCSS(css); - css = sanitized.css; - warnings.push(...sanitized.warnings); - } + const sanitized = sanitizeThemeCSS(css); + css = sanitized.css; + warnings.push(...sanitized.warnings); const now = new Date().toISOString(); const theme: ServerTheme = { diff --git a/app/api/auth/impersonate/route.ts b/app/api/auth/impersonate/route.ts index 858ccb8ef..6690be6ff 100644 --- a/app/api/auth/impersonate/route.ts +++ b/app/api/auth/impersonate/route.ts @@ -7,15 +7,14 @@ import { getCookieOptions } from '@/lib/oauth/cookie-config'; import { normalizeJmapServerUrl } from '@/lib/auth/verify-jmap-auth'; import { setStalwartAuthContextInStore } from '@/lib/stalwart/auth-context'; import { recordLogin } from '@/lib/telemetry/login-tracker'; -import { - ImpersonationJwtError, - impersonationReplayCache, - verifyImpersonationJwt, -} from '@/lib/impersonation/jwt'; +import { ImpersonationJwtError, verifyImpersonationJwt } from '@/lib/impersonation/jwt'; +import { consumeImpersonationJti } from '@/lib/impersonation/replay-store'; import { readImpersonationConfig, resolveImpersonationServerUrl, } from '@/lib/impersonation/master-config'; +import { mintImpersonationCredential } from '@/lib/impersonation/app-password'; +import { IMPERSONATION_GRANT_COOKIE, sealImpersonationGrant } from '@/lib/impersonation/grant-cookie'; export const runtime = 'nodejs'; @@ -40,8 +39,13 @@ function impersonationCookieOptions() { * mailbox; Bulwark verifies the signature, resolves the configured Stalwart * master credentials from env, then mints the same session cookies the * password-login path produces. The browser is redirected to "/?impersonated=1" (see - * ImpersonationReconciler, GH #646) and the - * SPA hydrates as if the user had just logged in with master@target%master. + * ImpersonationReconciler, GH #646) and the SPA hydrates as if the user had + * just logged in to the target mailbox. + * + * The master credential is used here, server-side, only to create an + * expiring app password on the target mailbox. The session cookies carry + * that app password: the browser reads its session back through + * PUT /api/auth/session, and the master password would open every mailbox. * * Returns 404 when the feature is not configured so an unconfigured * deployment does not advertise the endpoint. @@ -74,7 +78,7 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } - if (!impersonationReplayCache.consume(claims.jti, claims.exp)) { + if (!(await consumeImpersonationJti(claims.jti, claims.exp))) { logger.warn('Impersonation JWT replay rejected', { jti: claims.jti }); return NextResponse.json({ error: 'Token already used' }, { status: 401 }); } @@ -92,26 +96,44 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: 'Invalid JMAP server URL' }, { status: 500 }); } - // Stalwart master-user impersonation: username = "%", - // password = . Per Stalwart docs: + // Stalwart master-user login ("%", master password) opens + // the target mailbox; use it once to mint the target's own app password. // https://stalw.art/docs/auth/authorization/administrator/ - const impersonatedUsername = `${claims.mailbox}%${config.masterUser}`; - const authHeader = `Basic ${Buffer.from( - `${impersonatedUsername}:${config.masterPassword}`, - ).toString('base64')}`; + let credential; + try { + credential = await mintImpersonationCredential({ + serverUrl: normalizedServerUrl, + mailbox: claims.mailbox, + masterUser: config.masterUser, + masterPassword: config.masterPassword, + description: `Support session ${claims.jti}`.slice(0, 100), + }); + } catch (err) { + logger.error('Impersonation credential could not be created', { + jti: claims.jti, + mailbox: claims.mailbox, + error: err instanceof Error ? err.message : 'Unknown', + }); + return NextResponse.json({ error: 'Could not open the mailbox' }, { status: 502 }); + } const cookieStore = await cookies(); - const sessionToken = encryptSession( - normalizedServerUrl, - impersonatedUsername, - config.masterPassword, - ); + const sessionToken = encryptSession(normalizedServerUrl, claims.mailbox, credential.secret); cookieStore.set(sessionCookieName(IMPERSONATION_SLOT), sessionToken, impersonationCookieOptions()); setStalwartAuthContextInStore(cookieStore, IMPERSONATION_SLOT, { serverUrl: normalizedServerUrl, - username: impersonatedUsername, - authHeader, + username: claims.mailbox, + authHeader: `Basic ${Buffer.from(`${claims.mailbox}:${credential.secret}`).toString('base64')}`, }); + cookieStore.set( + IMPERSONATION_GRANT_COOKIE, + sealImpersonationGrant({ + serverUrl: normalizedServerUrl, + mailbox: claims.mailbox, + credentialId: credential.id, + }), + impersonationCookieOptions(), + ); // Structured audit log - operators rely on this for security review. logger.info('Impersonation session granted', { @@ -121,6 +143,7 @@ export async function GET(request: NextRequest) { tenant_id: claims.tenant_id, actor_user_id: claims.actor_user_id, iss: claims.iss, + expires_at: credential.expiresAt, ip: request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || request.headers.get('x-real-ip') || @@ -129,7 +152,7 @@ export async function GET(request: NextRequest) { user_agent: request.headers.get('user-agent'), }); - void recordLogin(impersonatedUsername, normalizedServerUrl); + void recordLogin(claims.mailbox, normalizedServerUrl); // Use a relative Location header so the browser resolves it against the // public request URL. NextResponse.redirect(new URL('/', request.url)) diff --git a/app/api/auth/pair/create/route.ts b/app/api/auth/pair/create/route.ts index df591d112..f7d85eff4 100644 --- a/app/api/auth/pair/create/route.ts +++ b/app/api/auth/pair/create/route.ts @@ -1,99 +1,175 @@ import { NextRequest, NextResponse } from 'next/server'; import { cookies } from 'next/headers'; import { logger } from '@/lib/logger'; -import { refreshTokenCookieName, refreshTokenServerCookieName } from '@/lib/oauth/tokens'; -import { buildOAuthParams, getRequiredConfig, getTokenEndpoint } from '@/lib/oauth/token-exchange'; -import { getCookieOptions } from '@/lib/oauth/cookie-config'; -import { createPairing } from '@/lib/auth/pairing-store'; -import { hasValidPairReauth } from '@/lib/auth/pair-reauth'; +import { createPairingCode, isGrantAvailable, stashGrant } from '@/lib/auth/pairing-store'; +import { pairingOwner, readPairReauthFromStore, setPairReauthInStore } from '@/lib/auth/pair-reauth'; +import { mintGrantWithPassword } from '@/lib/auth/pair-grant'; +import { appAcceptsServerUrl } from '@/lib/auth/pair-bundle'; +import { beginPairStepUp, pairAttemptKey, settlePairStepUp } from '@/lib/auth/pair-attempts'; +import { hasSessionSecret } from '@/lib/auth/session-secret'; +import { readStalwartAuthContextFromStore } from '@/lib/stalwart/auth-context'; +import { isTrustedJmapServerUrl } from '@/lib/stalwart/server-fetch'; +import { configManager } from '@/lib/admin/config-manager'; +import { findServerByUrl, parseJmapServers } from '@/lib/admin/jmap-servers'; +import { IMPERSONATION_GRANT_COOKIE, openImpersonationGrant } from '@/lib/impersonation/grant-cookie'; import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; -// Desktop side of the cross-device QR login. The caller must be a signed-in -// webmail session (its refresh token lives in the httpOnly jmap_rt cookie). We -// refresh that token to (a) prove the session is live and (b) obtain a fresh -// access token to hand the phone, then stash the bundle under a one-time -// pairing code. The desktop renders the returned code as a QR; the phone -// redeems it at /api/auth/pair/redeem. +// Desktop side of "Link mobile app". Returns a one-time pairing code for the +// QR; the phone redeems it at /api/auth/pair/redeem. // -// Token sharing note: the phone receives the SAME refresh token as the desktop. -// That is correct for OAuth servers (such as Stalwart in its default config) -// that do not rotate refresh tokens on use. If the server rotates refresh -// tokens, the two devices would fight over the latest token — such deployments -// should disable rotation for this client or use a token-exchange grant. +// Linking provisions a new long-lived login on another device, so it needs a +// step-up first, and the step-up itself produces what the phone receives: +// - with `password` (and `totp`): the current password is checked against +// the mail server and used once to mint the phone's own sign-in (see +// lib/auth/pair-grant.ts); +// - after a fresh IdP login (/api/auth/sso/start purpose=reauth, completed by +// /api/auth/reauth/sso/complete): that login's own tokens. +// Either way the phone never shares the desktop's session, so signing out +// here does not sign the phone out. Within the step-up window a new code can +// be shown without asking again, until one of them is redeemed. +// +// The account is the slot's verified session context: its server URL and user +// never come from the request body. + +function parseSlot(raw: unknown): number { + return typeof raw === 'number' && Number.isInteger(raw) && raw >= 0 && raw < MAX_ACCOUNT_SLOTS ? raw : 0; +} + +/** + * The webmail's public base (origin + mount path) the desktop shows in the + * QR. Only accepted for the origin this request came from; the phone sends + * its refresh requests there when it needs the token proxy. + */ +function resolveWebmailBase(raw: unknown, request: NextRequest): string | null { + if (typeof raw !== 'string' || !raw || raw.length > 2048) return null; + let url: URL; + try { + url = new URL(raw); + } catch { + return null; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; + if (url.username || url.password || url.search || url.hash) return null; + const origin = request.headers.get('origin'); + if (origin) { + if (url.origin !== origin) return null; + } else { + const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host'); + if (!host || url.host !== host) return null; + } + return `${url.origin}${url.pathname.replace(/\/+$/, '')}`; +} + +/** The desktop's OAuth callback, for servers that insist on a registered redirect. */ +function resolveRedirectUri(raw: unknown, webmailBase: string): string | undefined { + if (typeof raw !== 'string' || !raw || raw.length > 2048) return undefined; + try { + const url = new URL(raw); + if (url.origin !== new URL(webmailBase).origin || url.search || url.hash) return undefined; + return url.toString(); + } catch { + return undefined; + } +} + +const STEP_UP_ERRORS = { + invalid_credentials: 401, + totp_required: 401, + server_unreachable: 502, + pairing_unavailable: 502, +} as const; + export async function POST(request: NextRequest) { // CSRF gate (GHSA-qvr9-m8cq-7wvg): cookies written here are SameSite=Lax, // so a cross-site top-level POST would otherwise reach this handler. const crossOrigin = rejectCrossOriginRequest(request); if (crossOrigin) return crossOrigin; - const cookieStore = await cookies(); try { - // Step-up gate: minting a pairing code grants new-device access, so it - // requires a recent fresh IdP re-authentication (see the reauth SSO flow). - // The client turns this 401 into a re-auth redirect, then retries. - if (!(await hasValidPairReauth())) { - return NextResponse.json({ error: 'reauth_required' }, { status: 401 }); + // The step-up proof, the session context and the phone's sealed refresh + // token are all encrypted under SESSION_SECRET. + if (!hasSessionSecret()) { + return NextResponse.json({ error: 'session_secret_required' }, { status: 500 }); } const body = await request.json().catch(() => ({})); - const slot = - typeof body.slot === 'number' && body.slot >= 0 && body.slot < MAX_ACCOUNT_SLOTS - ? body.slot - : 0; - - const cookieName = refreshTokenCookieName(slot); - const refreshToken = cookieStore.get(cookieName)?.value; - if (!refreshToken) { - return NextResponse.json({ error: 'Not signed in' }, { status: 401 }); - } - const serverId = cookieStore.get(refreshTokenServerCookieName(slot))?.value || null; - - const tokenEndpoint = await getTokenEndpoint(serverId); - const params = buildOAuthParams({ grant_type: 'refresh_token', refresh_token: refreshToken }, serverId); - - const tokenResponse = await fetch(tokenEndpoint, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: params.toString(), - }); - - if (!tokenResponse.ok) { - const errorText = await tokenResponse.text(); - logger.warn('Pair create: refresh failed', { status: tokenResponse.status, error: errorText }); - // Stale session — clear the dead cookie so the user is prompted to log - // back in, mirroring the token route's behaviour. - cookieStore.delete(cookieName); - cookieStore.delete(refreshTokenServerCookieName(slot)); - return NextResponse.json({ error: 'Session expired' }, { status: 401 }); + const slot = parseSlot(body?.slot); + const webmailBase = resolveWebmailBase(body?.webmail_base, request); + if (!webmailBase) { + return NextResponse.json({ error: 'invalid_request' }, { status: 400 }); } - const tokens = await tokenResponse.json(); - if (!tokens.access_token) { - logger.error('Pair create: refresh response missing access_token'); - return NextResponse.json({ error: 'Invalid token response' }, { status: 502 }); + const cookieStore = await cookies(); + + // A support session opens the mailbox with a short-lived app password; it + // must not be able to hand out a lasting login for it. + if (slot === 0 && openImpersonationGrant(cookieStore.get(IMPERSONATION_GRANT_COOKIE)?.value)) { + return NextResponse.json({ error: 'impersonation' }, { status: 403 }); } - // If the server rotated the refresh token, persist the new one back to the - // desktop's cookie so this very session keeps working. The phone will get - // the same (new) token below. - const effectiveRefreshToken = tokens.refresh_token || refreshToken; - if (tokens.refresh_token) { - cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions()); + const context = readStalwartAuthContextFromStore(cookieStore, slot); + if (!context) { + return NextResponse.json({ error: 'not_signed_in' }, { status: 401 }); + } + const owner = pairingOwner(slot, context.username); + + // The app refuses a mail server over plain http. Say so here, before a + // password attempt is spent and before the desktop would report a phone + // that could never connect as signed in. + if (!appAcceptsServerUrl(context.serverUrl)) { + return NextResponse.json({ error: 'insecure_server' }, { status: 400 }); } - const { clientId, serverUrl } = getRequiredConfig(serverId); + let grantId: string; + const password = typeof body?.password === 'string' ? body.password : ''; + if (password) { + const serverUrl = context.serverUrl.replace(/\/+$/, ''); + // The login name the credential belongs to, when the session context + // was written under an identity address. + const accountName = context.accountName ?? context.username; + const attemptKey = pairAttemptKey(serverUrl, accountName); + if (!beginPairStepUp(attemptKey)) { + return NextResponse.json({ error: 'too_many_attempts' }, { status: 429 }); + } + const totp = typeof body?.totp === 'string' && body.totp.trim() ? body.totp.trim() : undefined; + await configManager.ensureLoaded(); + const serverId = findServerByUrl(parseJmapServers(configManager.get('jmapServers', [])), serverUrl)?.id ?? null; - const { code, expiresIn } = createPairing({ - accessToken: tokens.access_token, - refreshToken: effectiveRefreshToken, - expiresIn: tokens.expires_in, - tokenEndpoint, - clientId, - serverUrl, - serverId, - }); + const result = await mintGrantWithPassword({ + serverUrl, + trusted: await isTrustedJmapServerUrl(serverUrl), + serverId, + username: accountName, + password, + totp, + webmailRedirectUri: resolveRedirectUri(body?.redirect_uri, webmailBase), + }); + if (!result.ok) { + const wrong = result.error === 'invalid_credentials' || (result.error === 'totp_required' && !!totp); + settlePairStepUp(attemptKey, wrong ? 'wrong_credential' : 'other'); + return NextResponse.json({ error: result.error }, { status: STEP_UP_ERRORS[result.error] }); + } + settlePairStepUp(attemptKey, 'success'); + grantId = stashGrant(result.grant, owner); + setPairReauthInStore(cookieStore, { grantId, owner }); + logger.info('Pair step-up succeeded', { flow: result.grant.flow, method: 'password' }); + } else { + const proof = readPairReauthFromStore(cookieStore); + if (!proof || proof.owner !== owner || !isGrantAvailable(proof.grantId, owner)) { + return NextResponse.json({ error: 'reauth_required' }, { status: 401 }); + } + grantId = proof.grantId; + } - return NextResponse.json({ pairing_code: code, server_url: serverUrl, expires_in: expiresIn }); + const pairing = createPairingCode(grantId, owner, webmailBase); + if (!pairing) { + return NextResponse.json({ error: 'reauth_required' }, { status: 401 }); + } + + return NextResponse.json( + { pairing_code: pairing.code, status_id: pairing.statusId, expires_in: pairing.expiresIn }, + { headers: { 'Cache-Control': 'no-store' } }, + ); } catch (error) { logger.error('Pair create error', { error: error instanceof Error ? error.message : 'Unknown error' }); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); diff --git a/app/api/auth/pair/redeem/route.ts b/app/api/auth/pair/redeem/route.ts index 065215916..6ec86cc01 100644 --- a/app/api/auth/pair/redeem/route.ts +++ b/app/api/auth/pair/redeem/route.ts @@ -1,41 +1,47 @@ import { NextRequest, NextResponse } from 'next/server'; import { logger } from '@/lib/logger'; -import { consumePairing } from '@/lib/auth/pairing-store'; +import { redeemPairingCode } from '@/lib/auth/pairing-store'; +import { PAIR_TOKEN_PROXY_PATH, buildRedeemBundle } from '@/lib/auth/pair-bundle'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; -// Phone side of the cross-device QR login. The app POSTs the pairing code it -// scanned; we hand back the OAuth token bundle the desktop stashed at -// /api/auth/pair/create. The code is the only credential required — it is -// high-entropy, single-use, and expires within ~2 minutes — so this route is -// intentionally unauthenticated (the scanning device has no webmail cookies). +// Phone side of "Link mobile app". The app POSTs the code it scanned and gets +// the sign-in the desktop's step-up minted for it (see /api/auth/pair/create): +// an OAuth bundle, or for servers without OAuth login a username + (app) +// password. The code is the only credential required - it carries 256 bits, +// works once and expires within two minutes - so this route is intentionally +// unauthenticated (the scanning device has no webmail cookies). +// +// Failures say what happened, so the app can tell the user what to do: +// 400 invalid_code (never issued), 410 expired_code, 410 used_code. + +const NO_STORE = { 'Cache-Control': 'no-store' }; + export async function POST(request: NextRequest) { // CSRF gate (GHSA-qvr9-m8cq-7wvg): cookies written here are SameSite=Lax, // so a cross-site top-level POST would otherwise reach this handler. const crossOrigin = rejectCrossOriginRequest(request); if (crossOrigin) return crossOrigin; try { - const { pairing_code: pairingCode } = await request.json().catch(() => ({})); - if (!pairingCode || typeof pairingCode !== 'string') { - return NextResponse.json({ error: 'Missing pairing code' }, { status: 400 }); + const body = await request.json().catch(() => ({})); + const pairingCode = body?.pairing_code; + if (typeof pairingCode !== 'string' || !/^[0-9a-f]{64}$/.test(pairingCode)) { + return NextResponse.json({ error: 'invalid_code' }, { status: 400, headers: NO_STORE }); } - const tokens = consumePairing(pairingCode); - if (!tokens) { - // Unknown, expired, or already redeemed — do not distinguish. - return NextResponse.json({ error: 'Invalid or expired pairing code' }, { status: 400 }); + const result = redeemPairingCode(pairingCode); + if (!result.ok) { + const status = result.reason === 'invalid' ? 400 : 410; + return NextResponse.json({ error: `${result.reason}_code` }, { status, headers: NO_STORE }); } - return NextResponse.json({ - flow: 'oauth', - server_url: tokens.serverUrl, - access_token: tokens.accessToken, - ...(tokens.refreshToken ? { refresh_token: tokens.refreshToken } : {}), - ...(typeof tokens.expiresIn === 'number' ? { expires_in: tokens.expiresIn } : {}), - token_endpoint: tokens.tokenEndpoint, - client_id: tokens.clientId, + const bundle = buildRedeemBundle(result.grant, result.webmailBase); + logger.info('Pair code redeemed', { + flow: bundle.flow, + proxied: bundle.flow === 'oauth' && bundle.token_endpoint.endsWith(PAIR_TOKEN_PROXY_PATH), }); + return NextResponse.json(bundle, { headers: NO_STORE }); } catch (error) { logger.error('Pair redeem error', { error: error instanceof Error ? error.message : 'Unknown error' }); - return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + return NextResponse.json({ error: 'Internal server error' }, { status: 500, headers: NO_STORE }); } } diff --git a/app/api/auth/pair/status/route.ts b/app/api/auth/pair/status/route.ts new file mode 100644 index 000000000..93864e9e6 --- /dev/null +++ b/app/api/auth/pair/status/route.ts @@ -0,0 +1,13 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { getPairingStatus } from '@/lib/auth/pairing-store'; + +// Lets the desktop replace its QR with "Signed in on your phone" once the +// code was redeemed. Polled with the separate status id pair/create returned, +// so the code itself is never repeated in URLs or access logs. A status id +// reveals nothing but whether its own code was used. + +export async function GET(request: NextRequest) { + const id = request.nextUrl.searchParams.get('id') ?? ''; + const status = /^[0-9a-f]{32}$/.test(id) ? getPairingStatus(id) : 'unknown'; + return NextResponse.json({ status }, { headers: { 'Cache-Control': 'no-store' } }); +} diff --git a/app/api/auth/pair/token/route.ts b/app/api/auth/pair/token/route.ts new file mode 100644 index 000000000..99a86c405 --- /dev/null +++ b/app/api/auth/pair/token/route.ts @@ -0,0 +1,125 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { logger } from '@/lib/logger'; +import { openPhoneRefreshToken, sealPhoneRefreshToken, type SealedRefresh } from '@/lib/auth/pair-bundle'; +import { DEFAULT_CLIENT_ID, getClientSecret, getTokenEndpoint } from '@/lib/oauth/token-exchange'; +import { isTrustedJmapServerUrl } from '@/lib/stalwart/server-fetch'; +import { fetchPublicUrl } from '@/lib/security/url-guard'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; + +// Token endpoint for paired phones whose grant the phone cannot renew itself: +// the client is confidential (its secret stays on this server), or the +// provider's host is one current app builds refuse to talk to. The app posts +// the standard refresh grant here; we renew at the provider that minted the +// grant, with the secret, and hand back a re-sealed refresh token. +// +// Only refresh tokens this webmail sealed for a phone are accepted (see +// lib/auth/pair-bundle.ts), so the route cannot be used to renew arbitrary +// tokens with our client secret. No cookies are involved. + +const UPSTREAM_TIMEOUT_MS = 10_000; +const NO_STORE = { 'Cache-Control': 'no-store', Pragma: 'no-cache' }; + +/** + * Whether the sealed endpoint is still one this webmail is configured for: + * the discovered token endpoint of its server entry (SSO grants), or the + * structured-login endpoint of an admin-configured JMAP server (password + * grants). + */ +async function stillTrusted(sealed: SealedRefresh): Promise { + try { + if (await getTokenEndpoint(sealed.serverId, { fallbackClientId: DEFAULT_CLIENT_ID }) === sealed.tokenEndpoint) { + return true; + } + } catch { + // No OAuth configured for it (any more): try the JMAP server below. + } + const base = sealed.tokenEndpoint.replace(/\/auth\/token$/, ''); + return base !== sealed.tokenEndpoint && await isTrustedJmapServerUrl(base); +} + +function oauthError(error: string, status: number) { + return NextResponse.json({ error }, { status, headers: NO_STORE }); +} + +export async function POST(request: NextRequest) { + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; + + let params: URLSearchParams; + try { + params = new URLSearchParams(await request.text()); + } catch { + return oauthError('invalid_request', 400); + } + if (params.get('grant_type') !== 'refresh_token') { + return oauthError('unsupported_grant_type', 400); + } + const sealed = openPhoneRefreshToken(params.get('refresh_token') ?? ''); + if (!sealed) { + return oauthError('invalid_grant', 400); + } + + const upstreamParams = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: sealed.refreshToken, + client_id: sealed.clientId, + }); + // The secret is the admin's, for the admin's servers only - as configured + // now, not when the token was sealed: a server removed or moved since then + // gets neither the secret nor the unguarded fetch. + const trusted = sealed.trusted && await stillTrusted(sealed); + const secret = trusted ? getClientSecret(sealed.serverId) : ''; + if (secret) upstreamParams.set('client_secret', secret); + + let upstream: Response; + try { + const init = { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, + body: upstreamParams.toString(), + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }; + // The body carries the refresh token and the client secret: never follow + // a redirect with it. A user-chosen server goes through the + // rebinding-safe fetch (which never follows redirects either). + upstream = trusted + ? await fetch(sealed.tokenEndpoint, { ...init, redirect: 'error' }) + : (await fetchPublicUrl(sealed.tokenEndpoint, init)) as unknown as Response; + } catch (error) { + logger.warn('Pair token proxy: provider unreachable', { + error: error instanceof Error ? error.message : 'Unknown error', + }); + return oauthError('temporarily_unavailable', 503); + } + + if (!upstream.ok) { + // 400/401/403: the grant is dead (expired, revoked, password changed) and + // the app signs the account out. Anything else is an outage it waits out. + const dead = upstream.status === 400 || upstream.status === 401 || upstream.status === 403; + logger.warn('Pair token proxy: refresh rejected', { status: upstream.status }); + return oauthError(dead ? 'invalid_grant' : 'temporarily_unavailable', dead ? 400 : 503); + } + + let tokens: { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; token_type?: unknown }; + try { + tokens = await upstream.json(); + } catch { + return oauthError('temporarily_unavailable', 503); + } + if (typeof tokens.access_token !== 'string' || !tokens.access_token) { + return oauthError('temporarily_unavailable', 503); + } + + const refreshToken = typeof tokens.refresh_token === 'string' && tokens.refresh_token + ? tokens.refresh_token + : sealed.refreshToken; + return NextResponse.json( + { + access_token: tokens.access_token, + token_type: typeof tokens.token_type === 'string' ? tokens.token_type : 'Bearer', + ...(typeof tokens.expires_in === 'number' ? { expires_in: tokens.expires_in } : {}), + refresh_token: sealPhoneRefreshToken({ ...sealed, refreshToken }), + }, + { headers: NO_STORE }, + ); +} diff --git a/app/api/auth/reauth/sso/complete/route.ts b/app/api/auth/reauth/sso/complete/route.ts index 2f222db6c..51e26fbad 100644 --- a/app/api/auth/reauth/sso/complete/route.ts +++ b/app/api/auth/reauth/sso/complete/route.ts @@ -2,20 +2,42 @@ import { NextRequest, NextResponse } from 'next/server'; import { cookies } from 'next/headers'; import { logger } from '@/lib/logger'; import { decryptPayload } from '@/lib/auth/crypto'; -import { exchangeCodeForTokens } from '@/lib/oauth/token-exchange'; -import { setPairReauth } from '@/lib/auth/pair-reauth'; +import { exchangeCodeForTokens, getRequiredConfig, getTokenEndpoint, hasClientSecret } from '@/lib/oauth/token-exchange'; +import { pairingOwner, setPairReauthInStore } from '@/lib/auth/pair-reauth'; +import { stashGrant } from '@/lib/auth/pairing-store'; +import { readStalwartAuthContextFromStore } from '@/lib/stalwart/auth-context'; +import { isTrustedJmapServerUrl } from '@/lib/stalwart/server-fetch'; +import { JmapAuthVerificationError, verifyJmapIdentity } from '@/lib/auth/verify-jmap-auth'; +import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; -// Completes the step-up re-authentication for device pairing. The user was sent -// to the IdP with prompt=login (see /api/auth/sso/start with purpose=reauth); -// here we verify the returned code against the pending state and exchange it to -// confirm a fresh login actually happened, then set the short-lived pairing -// re-auth proof cookie. We deliberately do NOT issue a login session or write -// any refresh-token cookies — the user is already signed in; this only proves -// recency for the pairing action. +// Completes the step-up re-authentication for device pairing. The user was +// sent to the IdP with prompt=login (see /api/auth/sso/start with +// purpose=reauth); here we verify the returned code against the pending state +// and exchange it. That fresh login becomes the paired phone's own grant: it +// is kept server-side (see pairing-store) until a code for it is redeemed, and +// the short-lived pairing proof cookie remembers which grant. We deliberately +// do NOT issue a login session or touch the desktop's refresh-token cookies - +// the user is already signed in, and the phone must not share that session. const SSO_PENDING_COOKIE = 'sso_pending'; const SSO_PENDING_MAX_AGE_MS = 5 * 60 * 1000; +/** Clock skew allowed between this server and the identity provider. */ +const AUTH_TIME_SKEW_MS = 2 * 60 * 1000; + +/** + * The `auth_time` claim of an ID token received straight from the token + * endpoint (so its signature need not be checked here), or null. + */ +function idTokenAuthTime(idToken: string | undefined): number | null { + if (!idToken) return null; + try { + const payload = JSON.parse(Buffer.from(idToken.split('.')[1] ?? '', 'base64url').toString('utf8')); + return typeof payload?.auth_time === 'number' ? payload.auth_time : null; + } catch { + return null; + } +} export async function POST(request: NextRequest) { // CSRF gate (GHSA-qvr9-m8cq-7wvg): cookies written here are SameSite=Lax, @@ -56,16 +78,68 @@ export async function POST(request: NextRequest) { const codeVerifier = pending.code_verifier as string; const redirectUri = pending.redirect_uri as string; const pendingServerId = typeof pending.server_id === 'string' ? pending.server_id : null; + const slot = typeof pending.slot === 'number' && Number.isInteger(pending.slot) + && pending.slot >= 0 && pending.slot < MAX_ACCOUNT_SLOTS ? pending.slot : 0; if (!codeVerifier || !redirectUri) { return NextResponse.json({ error: 'Invalid re-auth session data' }, { status: 400 }); } - // A successful exchange proves the user just authenticated at the IdP (the - // freshness is enforced by prompt=login on the authorize request). We don't - // keep the resulting tokens. - await exchangeCodeForTokens(code, codeVerifier, redirectUri, pendingServerId); + const context = readStalwartAuthContextFromStore(cookieStore, slot); + if (!context) { + return NextResponse.json({ error: 'not_signed_in' }, { status: 401 }); + } - await setPairReauth(); + // A successful exchange proves the user just authenticated at the IdP (the + // freshness is asked for with prompt=login on the authorize request). + const tokens = await exchangeCodeForTokens(code, codeVerifier, redirectUri, pendingServerId); + + // An IdP that ignores prompt=login answers from its existing session; + // when its ID token says the login is older than this step-up, it was + // no step-up at all. (No auth_time: nothing to check.) + const authTime = idTokenAuthTime(tokens.id_token); + if (authTime !== null && authTime * 1000 < createdAt - AUTH_TIME_SKEW_MS) { + logger.warn('Reauth complete: the provider did not ask for a fresh login'); + return NextResponse.json({ error: 'reauth_not_fresh' }, { status: 401 }); + } + + // ...but not as whom. The phone must get the account being paired, not + // whichever account the IdP prompt was answered with. + const serverUrl = context.serverUrl.replace(/\/+$/, ''); + try { + await verifyJmapIdentity(serverUrl, `Bearer ${tokens.access_token}`, context.username, { + trusted: await isTrustedJmapServerUrl(serverUrl), + }); + } catch (error) { + if (error instanceof JmapAuthVerificationError && (error.status === 401 || error.status === 403)) { + logger.warn('Reauth complete: fresh login is a different account'); + return NextResponse.json({ error: 'account_mismatch' }, { status: 403 }); + } + throw error; + } + + // Without a refresh token the phone would be signed out at the first + // access-token expiry; better to say so now. + if (!tokens.refresh_token) { + logger.warn('Reauth complete: provider issued no refresh token'); + return NextResponse.json({ error: 'no_refresh_token' }, { status: 502 }); + } + + const owner = pairingOwner(slot, context.username); + const grantId = stashGrant({ + flow: 'oauth', + serverUrl, + serverId: pendingServerId, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresIn: tokens.expires_in, + issuedAt: Date.now(), + tokenEndpoint: await getTokenEndpoint(pendingServerId), + clientId: getRequiredConfig(pendingServerId).clientId, + confidential: hasClientSecret(pendingServerId), + trusted: true, + }, owner); + setPairReauthInStore(cookieStore, { grantId, owner }); + logger.info('Pair step-up succeeded', { flow: 'oauth', method: 'sso' }); return NextResponse.json({ ok: true }); } catch (error) { cookieStore.delete(SSO_PENDING_COOKIE); diff --git a/app/api/auth/session/route.ts b/app/api/auth/session/route.ts index a2a8a3aec..276b09afe 100644 --- a/app/api/auth/session/route.ts +++ b/app/api/auth/session/route.ts @@ -1,7 +1,7 @@ import { NextRequest, NextResponse } from 'next/server'; import { cookies } from 'next/headers'; import { logger } from '@/lib/logger'; -import { encryptSession, decryptSession } from '@/lib/auth/crypto'; +import { encryptSession, decryptSession, sessionAuthHeader, type SessionCredentials } from '@/lib/auth/crypto'; import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie'; import { getCookieOptions } from '@/lib/oauth/cookie-config'; import { JmapAuthVerificationError, verifyJmapIdentity } from '@/lib/auth/verify-jmap-auth'; @@ -16,6 +16,11 @@ import { parseJmapServers, resolveTrustedJmapUrl } from '@/lib/admin/jmap-server import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; import { insecureCookieHint, verificationFailureBody } from '@/lib/auth/verification-failure'; +import { readImpersonationConfig } from '@/lib/impersonation/master-config'; +import { revokeImpersonationCredential } from '@/lib/impersonation/app-password'; +import { IMPERSONATION_GRANT_COOKIE, openImpersonationGrant } from '@/lib/impersonation/grant-cookie'; +import { revokeWopiTokens } from '@/lib/wopi/revocation'; +import { clearPairReauthInStore } from '@/lib/auth/pair-reauth'; function sessionCookieOptions() { return { @@ -24,6 +29,40 @@ function sessionCookieOptions() { }; } +/** + * A session sealed around the impersonation master password. Handoffs made + * before impersonation switched to per-mailbox app passwords stored it in + * the session cookie; it opens every mailbox, so it is never handed back to + * a browser, whichever path stored it. + */ +function holdsMasterPassword(credentials: SessionCredentials): boolean { + const config = readImpersonationConfig(); + return !!config && credentials.password === config.masterPassword; +} + +async function revokeImpersonationGrant( + cookieStore: Awaited>, +): Promise { + const grant = openImpersonationGrant(cookieStore.get(IMPERSONATION_GRANT_COOKIE)?.value); + cookieStore.delete(IMPERSONATION_GRANT_COOKIE); + const config = readImpersonationConfig(); + if (!grant || !config) return; + try { + await revokeImpersonationCredential({ + serverUrl: grant.serverUrl, + mailbox: grant.mailbox, + masterUser: config.masterUser, + masterPassword: config.masterPassword, + id: grant.credentialId, + }); + } catch (error) { + // The app password still expires on its own; sign-out must not fail. + logger.warn('Impersonation credential revocation failed', { + error: error instanceof Error ? error.message : 'Unknown error', + }); + } +} + function getSlot(request: NextRequest): number { const raw = request.nextUrl.searchParams.get('slot'); if (raw === null) return 0; @@ -46,8 +85,10 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: 'Basic authentication is disabled' }, { status: 403 }); } - const { serverUrl, username, password, slot: bodySlot } = await request.json(); - if (!serverUrl || !username || !password) { + // A password signs in with Basic auth, an access token (token login) with + // Bearer: exactly one of them. + const { serverUrl, username, password, token: accessToken, slot: bodySlot } = await request.json(); + if (!serverUrl || !username || typeof (password || accessToken) !== 'string' || !!password === !!accessToken) { return NextResponse.json({ error: 'Missing required fields' }, { status: 400 }); } @@ -81,7 +122,9 @@ export async function POST(request: NextRequest) { const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot < MAX_ACCOUNT_SLOTS ? bodySlot : getSlot(request); const cookieName = sessionCookieName(slot); - const authHeader = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; + const authHeader = accessToken + ? `Bearer ${accessToken}` + : `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; // Always verify the credential upstream (GHSA-wxcm-j4jc-9fxq). The cookies // written here are not only replayed as credentials (where a bogus // password would just 401 downstream): the encrypted auth context is also @@ -92,7 +135,7 @@ export async function POST(request: NextRequest) { const normalizedServerUrl = await verifyJmapIdentity(upstreamUrl, authHeader, username, { trusted: upstreamTrusted, }); - const token = encryptSession(normalizedServerUrl, username, password); + const token = encryptSession(normalizedServerUrl, username, accessToken ? { token: accessToken } : password); const cookieStore = await cookies(); cookieStore.set(cookieName, token, sessionCookieOptions()); setStalwartAuthContextInStore(cookieStore, slot, { @@ -140,7 +183,7 @@ export async function GET(request: NextRequest) { setStalwartAuthContextInStore(cookieStore, slot, { serverUrl: credentials.serverUrl, username: credentials.username, - authHeader: `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`, + authHeader: sessionAuthHeader(credentials), }); // Only return non-sensitive fields. Use PUT to retrieve full credentials. @@ -156,7 +199,7 @@ export async function GET(request: NextRequest) { } /** - * PUT - retrieve full credentials (including password) for session restoration. + * PUT - retrieve full credentials (password or access token) for session restoration. * Protected by multiple Sec-Fetch-* headers to ensure only same-origin * browser fetch() requests succeed. Non-browser clients cannot forge these. */ @@ -181,7 +224,7 @@ export async function PUT(request: NextRequest) { } const credentials = decryptSession(token); - if (!credentials) { + if (!credentials || holdsMasterPassword(credentials)) { cookieStore.delete(cookieName); clearStalwartAuthContextInStore(cookieStore, slot); return NextResponse.json({ error: 'Invalid session' }, { status: 401 }); @@ -190,7 +233,7 @@ export async function PUT(request: NextRequest) { setStalwartAuthContextInStore(cookieStore, slot, { serverUrl: credentials.serverUrl, username: credentials.username, - authHeader: `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`, + authHeader: sessionAuthHeader(credentials), }); return NextResponse.json(credentials, { @@ -210,6 +253,8 @@ export async function DELETE(request: NextRequest) { try { const cookieStore = await cookies(); const all = request.nextUrl.searchParams.get('all') === 'true'; + // Office editors opened from here stop working with the session. + await revokeWopiTokens(cookieStore, all ? 'all' : getSlot(request)); if (all) { // Delete all session cookies across every slot. @@ -217,10 +262,16 @@ export async function DELETE(request: NextRequest) { cookieStore.delete(sessionCookieName(i)); clearStalwartAuthContextInStore(cookieStore, i); } + await revokeImpersonationGrant(cookieStore); + // A phone that already paired keeps its own sign-in; a QR still on + // screen stops working. + clearPairReauthInStore(cookieStore); } else { const slot = getSlot(request); cookieStore.delete(sessionCookieName(slot)); clearStalwartAuthContextInStore(cookieStore, slot); + if (slot === 0) await revokeImpersonationGrant(cookieStore); + clearPairReauthInStore(cookieStore, slot); } return NextResponse.json({ ok: true }); diff --git a/app/api/auth/sso/complete/route.ts b/app/api/auth/sso/complete/route.ts index b26c73501..de4a8f8de 100644 --- a/app/api/auth/sso/complete/route.ts +++ b/app/api/auth/sso/complete/route.ts @@ -6,15 +6,32 @@ import { exchangeCodeForTokens, getRequiredConfig, getTokenEndpoint, + hasClientSecret, } from '@/lib/oauth/token-exchange'; +import { buildRedeemBundle } from '@/lib/auth/pair-bundle'; import { refreshTokenCookieName, refreshTokenServerCookieName } from '@/lib/oauth/tokens'; import { getCookieOptions } from '@/lib/oauth/cookie-config'; import { storeIdToken } from '@/lib/oauth/end-session'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; +import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; const SSO_PENDING_COOKIE = 'sso_pending'; const SSO_PENDING_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes +/** + * The webmail's public base (origin + mount path) from the callback URL the + * flow started with (`//auth/callback`, same-origin checked at + * /sso/start): where a phone renews through the token proxy. + */ +function webmailBaseFromCallback(redirectUri: string): string | null { + try { + const url = new URL(redirectUri); + return `${url.origin}${url.pathname.replace(/\/[^/]+\/auth\/callback\/?$/, '').replace(/\/+$/, '')}`; + } catch { + return null; + } +} + export async function POST(request: NextRequest) { // CSRF gate (GHSA-qvr9-m8cq-7wvg): cookies written here are SameSite=Lax, // so a cross-site top-level POST would otherwise reach this handler. @@ -32,8 +49,10 @@ export async function POST(request: NextRequest) { // Per-account refresh-token cookie slot. Without this the route hardcoded // slot 0, so the "+ Add Account" flow overwrote the first account's // refresh-token cookie. Default to 0 for back-compat with any caller that - // omits slot. Mirrors the validation in /api/auth/token POST. - const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : 0; + // omits slot. Mirrors the validation in /api/auth/token POST: slots run + // up to MAX_ACCOUNT_SLOTS, so a sixth account must not land on slot 0. + const slot = typeof bodySlot === 'number' && Number.isInteger(bodySlot) + && bodySlot >= 0 && bodySlot < MAX_ACCOUNT_SLOTS ? bodySlot : 0; // Read and decrypt the pending SSO cookie const pendingCookie = cookieStore.get(SSO_PENDING_COOKIE)?.value; @@ -63,6 +82,14 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: 'SSO session expired. Please try again.' }, { status: 400 }); } + // A step-up for device pairing completes at /api/auth/reauth/sso/complete + // only; here it would sign this browser in as whoever answered the prompt. + if (pending.purpose === 'reauth') { + logger.warn('SSO complete: refused a pairing re-auth session'); + cookieStore.delete(SSO_PENDING_COOKIE); + return NextResponse.json({ error: 'Not a login session' }, { status: 400 }); + } + const codeVerifier = pending.code_verifier as string; const redirectUri = pending.redirect_uri as string; const pendingServerId = typeof pending.server_id === 'string' ? pending.server_id : null; @@ -105,16 +132,32 @@ export async function POST(request: NextRequest) { // The mobile client needs the bits it can't re-derive: the refresh // token, the token endpoint it should hit to refresh later, and the // client_id the IdP expects on that refresh call. The server URL is - // returned so the app knows which JMAP host to connect to. + // returned so the app knows which JMAP host to connect to. A phone + // cannot renew with a confidential client's secret, and current app + // builds refuse a provider on another host, so those renew through + // this webmail - the same bundle a paired phone gets. const { clientId, serverUrl } = getRequiredConfig(pendingServerId); - const tokenEndpoint = await getTokenEndpoint(pendingServerId); + const bundle = buildRedeemBundle({ + flow: 'oauth', + serverUrl, + serverId: pendingServerId, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresIn: tokens.expires_in, + issuedAt: Date.now(), + tokenEndpoint: await getTokenEndpoint(pendingServerId), + clientId, + confidential: hasClientSecret(pendingServerId), + trusted: true, + }, webmailBaseFromCallback(redirectUri)); + if (bundle.flow !== 'oauth') throw new Error('unexpected bundle'); return NextResponse.json({ - access_token: tokens.access_token, - expires_in: tokens.expires_in, - refresh_token: tokens.refresh_token, - token_endpoint: tokenEndpoint, - client_id: clientId, - server_url: serverUrl, + access_token: bundle.access_token, + expires_in: bundle.expires_in, + refresh_token: bundle.refresh_token, + token_endpoint: bundle.token_endpoint, + client_id: bundle.client_id, + server_url: bundle.server_url, mobile_redirect_uri: mobileRedirectUri, mobile_state: mobileState, }); diff --git a/app/api/auth/sso/start/route.ts b/app/api/auth/sso/start/route.ts index 01a32d898..cc487e8c4 100644 --- a/app/api/auth/sso/start/route.ts +++ b/app/api/auth/sso/start/route.ts @@ -21,6 +21,19 @@ const SSO_PENDING_MAX_AGE = 300; // 5 minutes // caller-controlled URL the attacker chose. const MOBILE_REDIRECT_SCHEME = 'bulwarkmobile://'; +/** + * A re-auth mints the grant a paired phone keeps using. Providers such as + * Keycloak tie ordinary refresh tokens to the browser's login session, so + * signing out on the desktop (RP-initiated logout) would sign the phone out + * too; an `offline_access` token outlives that session. Only asked for when + * the provider advertises it, as an unknown scope can fail the request. + */ +function reauthScopes(scopes: string, isReauth: boolean, supported: string[] | undefined): string { + if (!isReauth || !supported?.includes('offline_access')) return scopes; + const list = scopes.split(/\s+/).filter(Boolean); + return list.includes('offline_access') ? scopes : [...list, 'offline_access'].join(' '); +} + export async function POST(request: NextRequest) { // CSRF gate (GHSA-qvr9-m8cq-7wvg): cookies written here are SameSite=Lax, // so a cross-site top-level POST would otherwise reach this handler. @@ -66,11 +79,11 @@ export async function POST(request: NextRequest) { // doesn't know that account's server id, so read it from the slot's // server cookie like pair/create does. Without it, deployments that only // configure OAuth per server (no global client/server) fail discovery. + const reauthSlot = + typeof rawSlot === 'number' && Number.isInteger(rawSlot) && rawSlot >= 0 && rawSlot < MAX_ACCOUNT_SLOTS ? rawSlot : 0; let serverId = typeof bodyServerId === 'string' && bodyServerId ? bodyServerId : null; if (!serverId && isReauth) { - const slot = - typeof rawSlot === 'number' && rawSlot >= 0 && rawSlot < MAX_ACCOUNT_SLOTS ? rawSlot : 0; - serverId = cookieStore.get(refreshTokenServerCookieName(slot))?.value || null; + serverId = cookieStore.get(refreshTokenServerCookieName(reauthSlot))?.value || null; } // Validate redirect_uri origin matches the request origin to prevent open redirects @@ -110,7 +123,8 @@ export async function POST(request: NextRequest) { ...(serverId ? { server_id: serverId } : {}), ...(mobileRedirectUri ? { mobile_redirect_uri: mobileRedirectUri } : {}), ...(mobileState ? { mobile_state: mobileState } : {}), - ...(isReauth ? { purpose: 'reauth' } : {}), + // The re-auth completes into a grant for the phone paired to this slot. + ...(isReauth ? { purpose: 'reauth', slot: reauthSlot } : {}), }; const encrypted = encryptPayload(pendingData, 'sso-pending'); @@ -129,7 +143,7 @@ export async function POST(request: NextRequest) { authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set('client_id', clientId); authUrl.searchParams.set('redirect_uri', redirect_uri); - authUrl.searchParams.set('scope', getOauthScopes()); + authUrl.searchParams.set('scope', reauthScopes(getOauthScopes(), isReauth, metadata.scopes_supported)); authUrl.searchParams.set('state', state); authUrl.searchParams.set('code_challenge', codeChallenge); authUrl.searchParams.set('code_challenge_method', 'S256'); diff --git a/app/api/auth/stalwart-context/route.ts b/app/api/auth/stalwart-context/route.ts index b79407b42..01a40a673 100644 --- a/app/api/auth/stalwart-context/route.ts +++ b/app/api/auth/stalwart-context/route.ts @@ -1,6 +1,6 @@ import { NextRequest, NextResponse } from 'next/server'; import { logger } from '@/lib/logger'; -import { JmapAuthVerificationError, verifyJmapIdentity } from '@/lib/auth/verify-jmap-auth'; +import { JmapAuthVerificationError, resolveJmapIdentity } from '@/lib/auth/verify-jmap-auth'; import { setStalwartAuthContext } from '@/lib/stalwart/auth-context'; import { configManager } from '@/lib/admin/config-manager'; import { isPublicHttpUrl } from '@/lib/security/url-guard'; @@ -71,7 +71,7 @@ export async function POST(request: NextRequest) { // any user's synced settings. Admin-configured servers are `trusted`, // which only relaxes the public-address requirement (they may live on a // private network) - never the credential check. - const normalizedServerUrl = await verifyJmapIdentity(upstreamUrl, authHeader, username, { + const { serverUrl: normalizedServerUrl, accountName } = await resolveJmapIdentity(upstreamUrl, authHeader, username, { trusted: upstreamTrusted, }); @@ -79,6 +79,7 @@ export async function POST(request: NextRequest) { serverUrl: normalizedServerUrl, username, authHeader, + ...(accountName !== username ? { accountName } : {}), }); void recordLogin(username, normalizedServerUrl); diff --git a/app/api/auth/token/route.ts b/app/api/auth/token/route.ts index 0a55ef72f..239739a54 100644 --- a/app/api/auth/token/route.ts +++ b/app/api/auth/token/route.ts @@ -52,11 +52,14 @@ async function revokeRefreshToken(token: string, serverId: string | null, metada }, serverId, { fallbackClientId: DEFAULT_CLIENT_ID }); try { + // Never follow a redirect with the refresh token and client secret in + // the body: the endpoint was validated, its redirect target was not. const revocationResponse = await fetch(metadata.revocation_endpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: params.toString(), signal: AbortSignal.timeout(REVOCATION_TIMEOUT_MS), + redirect: 'error', }); if (!revocationResponse.ok) { logger.warn('Token revocation returned error', { status: revocationResponse.status }); @@ -205,6 +208,8 @@ export async function PUT(request: NextRequest) { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: params.toString(), + // See revokeRefreshToken: the body holds the refresh token. + redirect: 'error', }); if (!tokenResponse.ok) { diff --git a/app/api/auth/totp-token-exchange/route.ts b/app/api/auth/totp-token-exchange/route.ts index 5afe0f5ab..0b6416c0c 100644 --- a/app/api/auth/totp-token-exchange/route.ts +++ b/app/api/auth/totp-token-exchange/route.ts @@ -5,45 +5,27 @@ import { refreshTokenCookieName, refreshTokenServerCookieName } from '@/lib/oaut import { getCookieOptions } from '@/lib/oauth/cookie-config'; import { readFileEnv } from '@/lib/read-file-env'; import { configManager } from '@/lib/admin/config-manager'; -import { DisallowedUrlError, fetchPublicUrl, isPublicHttpUrl } from '@/lib/security/url-guard'; +import { isPublicHttpUrl } from '@/lib/security/url-guard'; import { recordLogin } from '@/lib/telemetry/login-tracker'; import { parseJmapServers, findServerByUrl, findServerById } from '@/lib/admin/jmap-servers'; import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; -import { generateCodeVerifier, generateCodeChallenge } from '@/lib/oauth/pkce'; import { DEFAULT_CLIENT_ID } from '@/lib/oauth/token-exchange'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; +import { stalwartPasswordLogin } from '@/lib/auth/stalwart-password-login'; /** * Exchange a password + (optional) TOTP code for OAuth tokens. * - * Stalwart 0.16+ no longer accepts the legacy `password$totp` convention over - * HTTP Basic auth: its Basic decoder hardcodes `mfa_token: None` and never - * splits the secret on `$`, so any TOTP appended to the password is verified - * verbatim against the password hash and fails. The MFA token must instead be - * supplied as a distinct field through the structured login endpoint. - * - * This route drives that flow server-side (avoiding browser CORS against the - * mail server, same as OAuth discovery): - * 1. POST {serverUrl}/api/auth -> authenticate with a separate `mfaToken`, - * receiving a short-lived authorization `clientCode`. - * 2. POST {serverUrl}/auth/token (grant_type=authorization_code) -> exchange - * the code (with PKCE) for access/refresh tokens. + * Stalwart 0.16+ rejects TOTP over HTTP Basic, so a TOTP login goes through + * its structured login endpoint instead (see stalwartPasswordLogin). This + * route drives that flow server-side (avoiding browser CORS against the mail + * server, same as OAuth discovery) and keeps the refresh token in the slot's + * httpOnly cookie. * * Token-based auth also survives TOTP rotation, unlike basic auth which embeds * the (≈30s) code in every request. */ -interface LoginResult { - type?: string; - // The response keeps snake_case: only the LoginResponse variant *tags* are - // camelCased server-side, not the struct fields (the request fields are). - client_code?: string; -} - -function trimUrl(url: string): string { - return url.replace(/\/+$/, ''); -} - async function attemptLogin( upstreamUrl: string, username: string, @@ -54,13 +36,7 @@ async function attemptLogin( serverId: string | null, upstreamTrusted: boolean, ): Promise { - const base = trimUrl(upstreamUrl); - // A user-supplied endpoint (allowCustomJmapEndpoint) must connect through - // the rebinding-safe fetch; admin-configured servers may live on private - // addresses and use the plain one. - const upstreamFetch: typeof fetch = upstreamTrusted - ? fetch - : ((input, init) => fetchPublicUrl(String(input), init as Parameters[1]) as unknown as Promise); + const base = upstreamUrl.replace(/\/+$/, ''); // Per-server OAuth credentials override the global ones when the requested // server entry has its own oauth block configured. @@ -76,111 +52,50 @@ async function attemptLogin( || readFileEnv(process.env.OAUTH_CLIENT_SECRET_FILE) || ''; - // PKCE proves the token exchange originates from the same client that - // initiated the login, so no client secret is required for public clients. - const verifier = generateCodeVerifier(); - const challenge = await generateCodeChallenge(verifier); + const result = await stalwartPasswordLogin({ + serverUrl: base, + username, + password, + totp, + clientId, + clientSecret, + redirectUri, + trusted: upstreamTrusted, + }); - // Step 1: structured login with a separate MFA token. - let login: LoginResult; - try { - const loginResponse = await upstreamFetch(`${base}/api/auth`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - type: 'authCode', - accountName: username, - accountSecret: password, - ...(totp ? { mfaToken: totp } : {}), - clientId, - redirectUri, - codeChallenge: challenge, - codeChallengeMethod: 'S256', - }), - }); - - if (!loginResponse.ok) { - const detail = (await loginResponse.text()).substring(0, 500); - logger.warn('TOTP login: /api/auth rejected request', { status: loginResponse.status }); + if (!result.ok) { + switch (result.error) { // A 404 means the server predates the structured login endpoint; let the // caller fall back to the legacy basic-auth path. - return NextResponse.json( - { error: loginResponse.status === 404 ? 'login_endpoint_missing' : 'login_failed', detail }, - { status: loginResponse.status === 404 ? 404 : 502 }, - ); + case 'login_endpoint_missing': + return NextResponse.json({ error: 'login_endpoint_missing', detail: result.detail }, { status: 404 }); + case 'login_rejected': + return NextResponse.json({ error: 'login_failed', detail: result.detail }, { status: 502 }); + case 'invalid_server_url': + return NextResponse.json({ error: 'invalid_server_url' }, { status: 400 }); + case 'login_unreachable': + return NextResponse.json({ error: 'login_unreachable' }, { status: 502 }); + case 'totp_required': + return NextResponse.json({ error: 'totp_required' }, { status: 401 }); + case 'invalid_credentials': + return NextResponse.json({ error: 'invalid_credentials' }, { status: 401 }); + case 'login_failed': + return NextResponse.json({ error: 'login_failed' }, { status: 502 }); + case 'token_exchange_failed': + return NextResponse.json( + result.detail !== undefined ? { error: 'token_exchange_failed', detail: result.detail } : { error: 'token_exchange_failed' }, + { status: 502 }, + ); } - - login = await loginResponse.json(); - } catch (err) { - if (err instanceof DisallowedUrlError) { - logger.warn('TOTP login: rejected non-public server URL at connect time'); - return NextResponse.json({ error: 'invalid_server_url' }, { status: 400 }); - } - logger.warn('TOTP login: /api/auth request failed', { error: err instanceof Error ? err.message : String(err) }); - return NextResponse.json({ error: 'login_unreachable' }, { status: 502 }); - } - - switch (login.type) { - case 'authenticated': - break; - case 'mfaRequired': - return NextResponse.json({ error: 'totp_required' }, { status: 401 }); - case 'failure': - default: - return NextResponse.json({ error: 'invalid_credentials' }, { status: 401 }); - } - - if (!login.client_code) { - logger.warn('TOTP login: authenticated response missing client_code'); - return NextResponse.json({ error: 'login_failed' }, { status: 502 }); - } - - // Step 2: exchange the authorization code for tokens. - const tokenParams = new URLSearchParams({ - grant_type: 'authorization_code', - code: login.client_code, - client_id: clientId, - redirect_uri: redirectUri, - code_verifier: verifier, - }); - // Confidential clients still send their secret; harmless for public clients. - if (clientSecret) tokenParams.set('client_secret', clientSecret); - - let tokens: { access_token?: string; expires_in?: number; refresh_token?: string }; - try { - const tokenResponse = await upstreamFetch(`${base}/auth/token`, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: tokenParams.toString(), - }); - - if (!tokenResponse.ok) { - const detail = (await tokenResponse.text()).substring(0, 500); - logger.warn('TOTP login: token exchange failed', { status: tokenResponse.status, detail }); - return NextResponse.json({ error: 'token_exchange_failed', detail }, { status: 502 }); - } - - tokens = await tokenResponse.json(); - } catch (err) { - if (err instanceof DisallowedUrlError) { - logger.warn('TOTP login: rejected non-public server URL at connect time'); - return NextResponse.json({ error: 'invalid_server_url' }, { status: 400 }); - } - logger.warn('TOTP login: token endpoint failed', { error: err instanceof Error ? err.message : String(err) }); - return NextResponse.json({ error: 'token_exchange_failed' }, { status: 502 }); - } - - if (!tokens.access_token) { - return NextResponse.json({ error: 'token_exchange_failed', detail: 'Response missing access_token' }, { status: 502 }); } logger.info('TOTP login succeeded'); void recordLogin(username, base); - return await storeAndRespond( - { access_token: tokens.access_token, expires_in: tokens.expires_in, refresh_token: tokens.refresh_token }, - slot, - serverId, - ); + return await storeAndRespond(result.tokens, slot, serverId); +} + +function trimUrl(url: string): string { + return url.replace(/\/+$/, ''); } export async function POST(request: NextRequest) { diff --git a/app/api/auth/verify/route.ts b/app/api/auth/verify/route.ts index 1cc95d1d1..780ad690b 100644 --- a/app/api/auth/verify/route.ts +++ b/app/api/auth/verify/route.ts @@ -5,9 +5,12 @@ import { configManager } from '@/lib/admin/config-manager'; import { isPublicHttpUrl } from '@/lib/security/url-guard'; import { parseJmapServers, resolveTrustedJmapUrl } from '@/lib/admin/jmap-servers'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; +import { getClientIP } from '@/lib/admin/session'; +import { reserveVerifyProbe } from '@/lib/auth/verify-budget'; /** - * Server-side Basic-auth pre-check for the login form (#969). + * Server-side credential pre-check for the login form (#969): a password + * (Basic auth), or the access token of a token login (Bearer auth). * * When the browser itself probes the JMAP session URL with wrong credentials, * the server answers 401 + `WWW-Authenticate: Basic`, and on a same-origin @@ -40,8 +43,10 @@ export async function POST(request: NextRequest) { const serverUrl = body?.serverUrl; const username = body?.username; const password = body?.password; - if (typeof serverUrl !== 'string' || typeof username !== 'string' || typeof password !== 'string' - || !serverUrl || !username || !password) { + const token = body?.token; + const hasPassword = typeof username === 'string' && typeof password === 'string' && !!username && !!password; + const hasToken = typeof token === 'string' && !!token; + if (typeof serverUrl !== 'string' || !serverUrl || hasPassword === hasToken) { return NextResponse.json({ error: 'Missing required fields' }, { status: 400 }); } @@ -75,14 +80,23 @@ export async function POST(request: NextRequest) { return respond('inconclusive'); } - const authHeader = 'Basic ' + Buffer.from(username + ':' + password).toString('base64'); + // Wrong passwords tried from here count against this server's address + // upstream; over budget the browser probes the JMAP server itself. + const refund = reserveVerifyProbe(getClientIP(request)); + if (!refund) return respond('inconclusive'); + + const authHeader = hasToken + ? `Bearer ${token}` + : 'Basic ' + Buffer.from(username + ':' + password).toString('base64'); try { await verifyJmapAuth(upstreamUrl, authHeader, { trusted: upstreamTrusted }); + refund(); return respond('ok'); } catch (error) { if (error instanceof JmapAuthVerificationError && error.upstreamStatus === 401) { return respond('unauthorized'); } + refund(); logger.debug('Login pre-check inconclusive', { error: error instanceof Error ? error.message : 'Unknown error', }); diff --git a/app/api/caldav/discover/route.ts b/app/api/caldav/discover/route.ts index 1f82a1fc9..cd425ac1a 100644 --- a/app/api/caldav/discover/route.ts +++ b/app/api/caldav/discover/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; import { logger } from '@/lib/logger'; import { getStalwartCredentials } from '@/lib/stalwart/credentials'; import { fetchJmapServer } from '@/lib/stalwart/server-fetch'; @@ -56,6 +57,10 @@ async function probeCalendarHome( } export async function POST(request: NextRequest) { + // CSRF gate (GHSA-9mvj-98f5-9q6g): this handler acts with the caller's + // session cookie, which SameSite=Lax still sends from a same-site page. + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; try { const creds = await getStalwartCredentials(request); if (!creds) { diff --git a/app/api/calendar-agenda/route.ts b/app/api/calendar-agenda/route.ts index f03df7394..272687bea 100644 --- a/app/api/calendar-agenda/route.ts +++ b/app/api/calendar-agenda/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; import { logger } from '@/lib/logger'; import { getStalwartCredentials } from '@/lib/stalwart/credentials'; import { fetchJmapSession, postJmap, rebaseApiUrl } from '@/lib/stalwart/jmap-api'; @@ -11,10 +12,15 @@ import type { CalendarEvent } from '@/lib/jmap/types'; * POST /api/calendar-agenda * * Sidecar for the "Calendar Agenda" plugin. Resolves the caller's calendar - * account from the stored Stalwart auth context, queries upcoming + * accounts from the stored Stalwart auth context, queries upcoming * CalendarEvents over JMAP with Stalwart expanding recurring series into - * occurrences, and returns a slim, structured-cloneable agenda the plugin can - * render directly. + * occurrences, and returns a slim, structured-cloneable agenda the plugin + * can render directly. + * + * Events come from every account that has calendars: the primary calendar + * account plus shared and group accounts (a family or team calendar), the + * same set the calendar app shows. Ids are scoped by account, since event + * and calendar ids repeat across accounts. * * Credentials never leave the server — the sandboxed plugin only ever sees * the resulting agenda DTOs. @@ -41,7 +47,9 @@ const GET_BATCH = 100; const MAX_CALLS_FALLBACK = 16; interface AgendaEvent { + /** Unique across accounts: `:`. */ id: string; + accountId: string; uid: string | null; title: string; start: string; @@ -107,6 +115,10 @@ function firstCalendarId(event: Partial): string | null { } export async function POST(request: NextRequest) { + // CSRF gate (GHSA-9mvj-98f5-9q6g): this handler acts with the caller's + // session cookie, which SameSite=Lax still sends from a same-site page. + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; try { const creds = await getStalwartCredentials(request); if (!creds) { @@ -133,8 +145,8 @@ export async function POST(request: NextRequest) { if (!session) { return NextResponse.json({ error: 'JMAP session fetch failed' }, { status: 502 }); } - const accountId = session.primaryAccounts?.[CALENDAR_CAP]; - if (!accountId) { + const accountIds = calendarAccountIds(session); + if (accountIds.length === 0) { // No calendar account for this user — return an empty agenda, not an error. return NextResponse.json({ events: [], generatedAt: new Date().toISOString() }); } @@ -155,72 +167,22 @@ export async function POST(request: NextRequest) { const windowStart = new Date(now); windowStart.setHours(0, 0, 0, 0); - // ── 1) Query the occurrences in range + load calendars (colours) ── + // ── 1–3) Per account: query the occurrences in range, load calendars + // (colours), fetch the occurrences and hydrate them from their bases ── // expandRecurrences returns one id per occurrence (it needs both bounds), // the earliest first so the limit keeps the next ones. A range the server // will not expand - more occurrences than it allows in one query, or // longer than its maxExpandedQueryDuration - is refused; the agenda then // looks less far ahead instead of failing. - let queryRes: unknown; - let queryResp: Record | null; - for (;;) { - queryRes = await jmapPost(apiUrl, creds.authHeader, { - using, - methodCalls: [ - [ - 'CalendarEvent/query', - { - accountId, - filter: { after: windowStart.toISOString(), before: horizon.toISOString() }, - expandRecurrences: true, - sort: [{ property: 'start', isAscending: true }], - limit: 1000, - }, - '0', - ], - [ - 'Calendar/get', - { accountId, ids: null, properties: ['id', 'name', 'color'] }, - 'c', - ], - ], - }, fetchOptions); - queryResp = findResponse(queryRes, 'CalendarEvent/query', '0'); - if (queryResp) break; - const err = findResponse(queryRes, 'error', '0'); - const span = horizon.getTime() - now.getTime(); - if ((isOccurrenceLimit(err) || err?.type === 'expandDurationTooLarge') && span > DAY_MS) { - horizon = new Date(now.getTime() + Math.max(DAY_MS, Math.floor(span / 2))); - continue; - } - return NextResponse.json( - { error: (err?.description as string) || 'CalendarEvent/query failed' }, - { status: 502 }, - ); - } - const ids = (queryResp.ids as string[]) || []; - const calColors = new Map(); - const calResp = findResponse(queryRes, 'Calendar/get', 'c'); - for (const cal of ((calResp?.list as Array>) || [])) { - if (typeof cal.id === 'string') { - calColors.set(cal.id, { - name: typeof cal.name === 'string' ? cal.name : '', - color: typeof cal.color === 'string' ? cal.color : null, - }); - } - } + const expanded: Array = []; - if (ids.length === 0) { - return NextResponse.json({ events: [], generatedAt: now.toISOString() }); - } - - // ── 2) Fetch the occurrences (batched, several gets per request) ── const coreCapability = session.capabilities?.['urn:ietf:params:jmap:core'] as { maxCallsInRequest?: unknown } | undefined; const maxCalls = typeof coreCapability?.maxCallsInRequest === 'number' && coreCapability.maxCallsInRequest > 0 ? coreCapability.maxCallsInRequest : MAX_CALLS_FALLBACK; - const getEvents = async (eventIds: string[], properties: readonly string[]) => { + // Batched, several gets per request. + const getEvents = async (accountId: string, eventIds: string[], properties: readonly string[]) => { const list: Array> = []; const batches: string[][] = []; for (let i = 0; i < eventIds.length; i += GET_BATCH) batches.push(eventIds.slice(i, i + GET_BATCH)); @@ -242,34 +204,107 @@ export async function POST(request: NextRequest) { return list; }; - let occurrences: Partial[]; - const bases = new Map>(); - try { - occurrences = (await getEvents(ids, EVENT_PROPERTIES)) - .map((e) => normalizeCalendarEventLike(e as Partial)); - - // ── 3) Hydrate occurrences from their base events ── - // An expanded all-day occurrence comes back without showWithoutTime, - // and the base event has the duration an override leaves out. - const baseIds = Array.from(new Set(occurrences - .filter((e) => isServerRecurrenceInstance(e as CalendarEvent) && e.recurrenceId) - .map((e) => e.baseEventId as string))); - for (const base of await getEvents(baseIds, RECURRENCE_BASE_PROPERTIES)) { - if (typeof base.id === 'string') bases.set(base.id, normalizeCalendarEventLike(base as Partial)); + for (const accountId of accountIds) { + const isPrimary = accountId === accountIds[0]; + let queryRes: unknown; + let queryResp: Record | null; + let queryErr: Record | null = null; + for (;;) { + queryRes = await jmapPost(apiUrl, creds.authHeader, { + using, + methodCalls: [ + [ + 'CalendarEvent/query', + { + accountId, + filter: { after: windowStart.toISOString(), before: horizon.toISOString() }, + expandRecurrences: true, + sort: [{ property: 'start', isAscending: true }], + limit: 1000, + }, + '0', + ], + [ + 'Calendar/get', + { accountId, ids: null, properties: ['id', 'name', 'color'] }, + 'c', + ], + ], + }, fetchOptions); + queryResp = findResponse(queryRes, 'CalendarEvent/query', '0'); + if (queryResp) break; + queryErr = findResponse(queryRes, 'error', '0'); + const span = horizon.getTime() - now.getTime(); + if ((isOccurrenceLimit(queryErr) || queryErr?.type === 'expandDurationTooLarge') && span > DAY_MS) { + horizon = new Date(now.getTime() + Math.max(DAY_MS, Math.floor(span / 2))); + continue; + } + break; + } + if (!queryResp) { + if (!isPrimary) { + // A shared account the caller can see but not read calendars from + // (Stalwart answers forbidden/accountNotSupported) must not empty + // the agenda for the accounts that do work. + logger.debug('Calendar agenda: skipping account', { + accountId, + error: (queryErr?.type as string) || 'CalendarEvent/query failed', + }); + continue; + } + return NextResponse.json( + { error: (queryErr?.description as string) || 'CalendarEvent/query failed' }, + { status: 502 }, + ); + } + const ids = (queryResp.ids as string[]) || []; + + const calResp = findResponse(queryRes, 'Calendar/get', 'c'); + for (const cal of ((calResp?.list as Array>) || [])) { + if (typeof cal.id === 'string') { + calColors.set(scopedId(accountId, cal.id), { + name: typeof cal.name === 'string' ? cal.name : '', + color: typeof cal.color === 'string' ? cal.color : null, + }); + } + } + + if (ids.length === 0) continue; + + let occurrences: Partial[]; + const bases = new Map>(); + try { + occurrences = (await getEvents(accountId, ids, EVENT_PROPERTIES)) + .map((e) => normalizeCalendarEventLike(e as Partial)); + + // Hydrate occurrences from their base events: an expanded all-day + // occurrence comes back without showWithoutTime, and the base event + // has the duration an override leaves out. + const baseIds = Array.from(new Set(occurrences + .filter((e) => isServerRecurrenceInstance(e as CalendarEvent) && e.recurrenceId) + .map((e) => e.baseEventId as string))); + for (const base of await getEvents(accountId, baseIds, RECURRENCE_BASE_PROPERTIES)) { + if (typeof base.id === 'string') bases.set(base.id, normalizeCalendarEventLike(base as Partial)); + } + } catch (error) { + if (!(error instanceof AgendaFetchError)) throw error; + if (!isPrimary) { + logger.debug('Calendar agenda: skipping account', { accountId, error: error.message }); + continue; + } + return NextResponse.json({ error: error.message }, { status: 502 }); + } + + const valid = occurrences + .filter((e) => (e['@type'] ?? 'Event') === 'Event') + // Drop malformed events without a parseable start (would crash format()/ + // parseISO downstream) — mirrors the calendar store guard (#316). + .filter((e) => typeof e.start === 'string' && e.start && !isNaN(parseISO(e.start).getTime())) as CalendarEvent[]; + + for (const e of hydrateRecurrenceInstances(valid, bases)) { + expanded.push({ ...e, accountId }); } - } catch (error) { - if (!(error instanceof AgendaFetchError)) throw error; - return NextResponse.json({ error: error.message }, { status: 502 }); } - - const valid = occurrences - .filter((e) => (e['@type'] ?? 'Event') === 'Event') - // Drop malformed events without a parseable start (would crash format()/ - // parseISO downstream) — mirrors the calendar store guard (#316). - .filter((e) => typeof e.start === 'string' && e.start && !isNaN(parseISO(e.start).getTime())) as CalendarEvent[]; - - const expanded = hydrateRecurrenceInstances(valid, bases); - // ── 4) Keep ongoing/upcoming, sort, slice, map to DTOs ── const agenda: AgendaEvent[] = expanded .filter((e) => eventEnd(e).getTime() >= now.getTime()) @@ -277,9 +312,10 @@ export async function POST(request: NextRequest) { .slice(0, limit) .map((e) => { const calId = firstCalendarId(e); - const cal = calId ? calColors.get(calId) : undefined; + const cal = calId ? calColors.get(scopedId(e.accountId, calId)) : undefined; return { - id: String(e.id ?? ''), + id: scopedId(e.accountId, String(e.id ?? '')), + accountId: e.accountId, uid: e.uid ?? null, title: (e.title ?? '').trim() || '(no title)', start: eventStart(e).toISOString(), @@ -306,7 +342,7 @@ export async function POST(request: NextRequest) { } } -/** A method error on one of the agenda's gets, answered with 502. */ +/** A method error on one of the agenda's gets: 502 on the primary account. */ class AgendaFetchError extends Error {} /** @@ -319,6 +355,31 @@ function isOccurrenceLimit(err: Record | null): boolean { return err?.type === 'invalidArguments' && /exceeds/i.test(String(err.description ?? '')); } +/** + * The accounts to read calendars from, primary first. Mirrors the client's + * getCalendarCapableAccountIds(): shared and group accounts count even when + * Stalwart does not advertise the calendar capability on them. + */ +function calendarAccountIds(session: { + primaryAccounts?: Record; + accounts?: Record; +}): string[] { + const primary = session.primaryAccounts?.[CALENDAR_CAP]; + const ids: string[] = primary ? [primary] : []; + for (const [id, value] of Object.entries(session.accounts ?? {})) { + if (id === primary || !value || typeof value !== 'object') continue; + const account = value as { isPersonal?: unknown; accountCapabilities?: Record }; + if (account.accountCapabilities?.[CALENDAR_CAP] || account.isPersonal === false) { + ids.push(id); + } + } + return ids; +} + +function scopedId(accountId: string, id: string): string { + return `${accountId}:${id}`; +} + function clampInt(value: unknown, min: number, max: number, fallback: number): number { const n = typeof value === 'number' ? value : Number(value); if (!Number.isFinite(n)) return fallback; diff --git a/app/api/config/route.ts b/app/api/config/route.ts index 604e7a5c6..1f01fa83e 100644 --- a/app/api/config/route.ts +++ b/app/api/config/route.ts @@ -4,6 +4,7 @@ import { configManager } from '@/lib/admin/config-manager'; import { parseJmapServers, redactJmapServers } from '@/lib/admin/jmap-servers'; import { hasSessionSecret } from '@/lib/auth/session-secret'; import { getOauthScopes } from '@/lib/oauth/tokens'; +import { httpUrlOrEmpty } from '@/lib/config-validation'; import { matchDomainBranding, parseDomainBranding, @@ -53,6 +54,7 @@ export async function GET(request: NextRequest) { const stalwartJmapPassthroughEnabled = stalwartFeaturesEnabled && configManager.get('stalwartJmapPassthroughEnabled', true); const allowedFrameAncestors = configManager.get('allowedFrameAncestors', ''); + const autoPickByDomain = configManager.get('jmapServerAutoPickByDomain', false); return NextResponse.json( { @@ -82,19 +84,28 @@ export async function GET(request: NextRequest) { loginShowHeading: configManager.get('loginShowHeading', true), loginShowSubtitle: configManager.get('loginShowSubtitle', true), loginShowTotp: configManager.get('loginShowTotp', true), + loginShowTokenLogin: configManager.get('loginShowTokenLogin', false), loginShowVersion: configManager.get('loginShowVersion', true), demoMode: configManager.get('demoMode', false), allowCustomJmapEndpoint: configManager.get('allowCustomJmapEndpoint', false), - jmapServers: redactJmapServers(parseJmapServers(configManager.get('jmapServers', []))), - jmapServerAutoPickByDomain: configManager.get('jmapServerAutoPickByDomain', false), + // The domain lists name every organisation served here; the login page + // only needs them to pick the server by the typed address. + jmapServers: redactJmapServers(parseJmapServers(configManager.get('jmapServers', []))) + .map((server) => (autoPickByDomain ? server : { ...server, domains: [] })), + jmapServerAutoPickByDomain: autoPickByDomain, autoSsoEnabled: configManager.get('autoSsoEnabled', false), embeddedMode: !!allowedFrameAncestors && allowedFrameAncestors !== "'none'", parentOrigin: configManager.get('parentOrigin', ''), + sourceCodeUrl: httpUrlOrEmpty(configManager.get('sourceCodeUrl', '')), }, { - // Branding varies by host, so any cache between us and the browser - // must key its entry by the host headers we consulted. - headers: { Vary: 'Host, X-Forwarded-Host' }, + // Runtime settings can change without new asset URLs. Prevent stale + // browser/proxy responses, retaining Vary for host-specific branding. + headers: { + Vary: 'Host, X-Forwarded-Host', + 'Cache-Control': 'no-store, no-cache, must-revalidate', + 'CDN-Cache-Control': 'no-store', + }, }, ); } diff --git a/app/api/dev-jmap/[...path]/route.ts b/app/api/dev-jmap/[...path]/route.ts index 44c9e6c9e..70372c062 100644 --- a/app/api/dev-jmap/[...path]/route.ts +++ b/app/api/dev-jmap/[...path]/route.ts @@ -1795,7 +1795,7 @@ function handleEmailSet(args: MethodArgs, callId: string): MethodResult { from: (data.from as MockEmail['from']) || [{ name: 'Dev User', email: 'dev@localhost' }], to: (data.to as MockEmail['to']) || [], cc: (data.cc as MockEmail['cc']) || [], - subject: (data.subject as string) || '(no subject)', + subject: typeof data.subject === 'string' ? data.subject : '', preview: (previewText || (data.subject as string) || '').slice(0, 120), hasAttachment: false, textBody: [], @@ -2538,7 +2538,11 @@ function tooLargeFor(method: string, args: MethodArgs, callId: string): MethodRe // --------------------------------------------------------------------------- function isDevMockEnabled(): boolean { - return process.env.DEV_MOCK_JMAP === 'true'; + // NEXT_PUBLIC_DEV_MOCK_JMAP is inlined at build time from DEV_MOCK_JMAP + // (next.config.ts `env`), so a build made without the mock - every + // release image and tarball - cannot switch it on through the runtime + // environment: the mock accepts any password. + return process.env.NEXT_PUBLIC_DEV_MOCK_JMAP === 'true' && process.env.DEV_MOCK_JMAP === 'true'; } function getBaseUrl(request: NextRequest): string { diff --git a/app/api/favicon/route.ts b/app/api/favicon/route.ts index f1fafce2f..41d292c1e 100644 --- a/app/api/favicon/route.ts +++ b/app/api/favicon/route.ts @@ -455,10 +455,7 @@ export async function GET(request: NextRequest) { const cached = cache.get(normalizedDomain); if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) { return new NextResponse(cached.data, { - headers: { - 'Content-Type': cached.contentType, - 'Cache-Control': 'public, max-age=1209600', // 2 weeks - }, + headers: faviconHeaders(cached.contentType), }); } @@ -474,7 +471,15 @@ export async function GET(request: NextRequest) { return new NextResponse(TRANSPARENT_PNG, { headers: MISSING_FAVICON_HEADERS }); } - const contentType = upstream.headers.get('content-type') || 'image/x-icon'; + // Served inline on the webmail origin, so only raster image types pass: + // an image/svg+xml or text/html favicon opened on its own would run + // script as the webmail. + const contentType = rasterFaviconType(upstream.headers.get('content-type')); + if (!contentType) { + evictNegativeOldest(); + negativeCache.set(normalizedDomain, { fetchedAt: Date.now() }); + return new NextResponse(TRANSPARENT_PNG, { headers: MISSING_FAVICON_HEADERS }); + } const data = await upstream.arrayBuffer(); // Don't cache empty/tiny responses (likely no real favicon) @@ -489,10 +494,7 @@ export async function GET(request: NextRequest) { cache.set(normalizedDomain, { data, contentType, fetchedAt: Date.now() }); return new NextResponse(data, { - headers: { - 'Content-Type': contentType, - 'Cache-Control': 'public, max-age=1209600', - }, + headers: faviconHeaders(contentType), }); } catch { return new NextResponse(null, { @@ -502,6 +504,31 @@ export async function GET(request: NextRequest) { } } +const RASTER_FAVICON_TYPES = new Set([ + 'image/x-icon', + 'image/vnd.microsoft.icon', + 'image/png', + 'image/gif', + 'image/jpeg', + 'image/webp', + 'image/bmp', +]); + +/** The upstream type when it is a raster image, else null. */ +function rasterFaviconType(header: string | null): string | null { + const type = (header ?? 'image/x-icon').split(';')[0].trim().toLowerCase(); + return RASTER_FAVICON_TYPES.has(type) ? type : null; +} + +function faviconHeaders(contentType: string): Record { + return { + 'Content-Type': contentType, + 'Cache-Control': 'public, max-age=1209600', // 2 weeks + 'X-Content-Type-Options': 'nosniff', + 'Content-Security-Policy': "default-src 'none'; sandbox", + }; +} + function evictNegativeOldest() { if (negativeCache.size < NEGATIVE_CACHE_MAX_SIZE) return; let oldestKey: string | null = null; diff --git a/app/api/fetch-ical/route.ts b/app/api/fetch-ical/route.ts index 4653dfbe3..244ad5d0e 100644 --- a/app/api/fetch-ical/route.ts +++ b/app/api/fetch-ical/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; import { getStalwartCredentials } from '@/lib/stalwart/credentials'; import { DisallowedUrlError, fetchPublicUrl, type PublicFetchResponse } from '@/lib/security/url-guard'; @@ -57,6 +58,10 @@ function extractBasicAuth(rawUrl: string): { cleanUrl: string; authHeader: strin * (GHSA-24w9-8r42-8jwm). */ export async function POST(request: NextRequest) { + // CSRF gate (GHSA-9mvj-98f5-9q6g): this handler acts with the caller's + // session cookie, which SameSite=Lax still sends from a same-site page. + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; const creds = await getStalwartCredentials(request); if (!creds) { return NextResponse.json({ error: 'Not authenticated' }, { status: 401 }); diff --git a/app/api/health/route.ts b/app/api/health/route.ts index b7b1c52d1..0498ec818 100644 --- a/app/api/health/route.ts +++ b/app/api/health/route.ts @@ -2,6 +2,7 @@ import v8 from 'node:v8'; import { NextResponse } from 'next/server'; import { NextRequest } from 'next/server'; import { logger } from '@/lib/logger'; +import { canSeeInstanceDetails } from '@/lib/auth/instance-details'; const MEMORY_WARNING_THRESHOLD = 0.85; const MEMORY_CRITICAL_THRESHOLD = 0.95; @@ -40,12 +41,14 @@ interface HealthStatus { * Health check endpoint for container orchestration * * GET /api/health - Liveness probe for container orchestration - * GET /api/health?detailed=true - Diagnostics with advisory memory warnings + * GET /api/health?detailed=true - Diagnostics with advisory memory warnings, + * for signed-in users and admins (versions and memory fingerprint the + * instance); anyone else gets the plain liveness answer * HEAD /api/health - Lightweight liveness probe (status code only) */ export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams; - const detailed = searchParams.get('detailed') === 'true'; + const detailed = searchParams.get('detailed') === 'true' && await canSeeInstanceDetails(request); try { const timestamp = new Date().toISOString(); diff --git a/app/api/plugin-approval-status/route.ts b/app/api/plugin-approval-status/route.ts index 21c5f42ef..08f99867e 100644 --- a/app/api/plugin-approval-status/route.ts +++ b/app/api/plugin-approval-status/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; import { cookies } from 'next/headers'; import { decryptSession } from '@/lib/auth/crypto'; import { sessionCookieName } from '@/lib/auth/session-cookie'; @@ -58,6 +59,10 @@ export async function GET(request: NextRequest) { } export async function POST(request: NextRequest) { + // CSRF gate (GHSA-9mvj-98f5-9q6g): this handler acts with the caller's + // session cookie, which SameSite=Lax still sends from a same-site page. + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; try { const username = await resolveUsername(); if (!username) return NextResponse.json({ error: 'unauthenticated' }, { status: 401 }); diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index 3cb3a63fc..8332d1da9 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -1,4 +1,5 @@ -import { NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from 'next/server'; +import { canSeeInstanceDetails } from '@/lib/auth/instance-details'; import { getPluginRegistry, getThemeRegistry } from '@/lib/admin/plugin-registry'; import { listDevPlugins } from '@/lib/admin/plugin-dev'; import { configManager } from '@/lib/admin/config-manager'; @@ -8,9 +9,14 @@ import { logger } from '@/lib/logger'; * GET /api/plugins - Public endpoint for clients to discover server-managed plugins & themes * * Returns all enabled plugins and themes so the client can sync them to IndexedDB. - * No admin auth required - this is how regular users receive plugins/themes. + * No admin auth required - this is how regular users receive plugins/themes - + * but a session is: the list names the plugins and the hosts they may reach, + * and the client only syncs after signing in. */ -export async function GET() { +export async function GET(request: NextRequest) { + if (!(await canSeeInstanceDetails(request))) { + return NextResponse.json({ error: 'Not authenticated' }, { status: 401 }); + } try { await configManager.ensureLoaded(); const policy = configManager.getPolicy(); diff --git a/app/api/push/preview/route.ts b/app/api/push/preview/route.ts index 8273df184..bf19ccdcc 100644 --- a/app/api/push/preview/route.ts +++ b/app/api/push/preview/route.ts @@ -1,6 +1,7 @@ import { cookies } from 'next/headers'; import { NextRequest, NextResponse } from 'next/server'; import { logger } from '@/lib/logger'; +import { cleanPreview } from '@/lib/utils'; import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils'; import { readStalwartAuthContextFromStore } from '@/lib/stalwart/auth-context'; import { @@ -19,6 +20,12 @@ interface ResolvedTarget { accountId: string; /** See StalwartCredentials.trusted - false routes through the guarded fetch. */ trusted: boolean; + /** + * Cookie slot of the login that owns the account. Handed back so a click + * on the notification opens the message in that login: the worker knows + * only the JMAP account id, which can repeat across servers. + */ + slot?: number; } // When the SW passes ?accountId=, we need the slot whose JMAP session owns @@ -54,7 +61,7 @@ async function resolveTargetForAccount(accountId: string): Promise method === 'Mailbox/query', + ([method, , callId]) => method === 'Mailbox/query' && callId === 'mb', )?.[1] as { ids?: string[] } | undefined; - const inboxId = inboxBody?.ids?.[0]; + // A method-level JMAP error still has HTTP 200. Do not turn it into + // an empty Inbox: the service worker would silently discard the push. + if (!Array.isArray(inboxBody?.ids)) { + return NextResponse.json({ error: 'JMAP mailbox query failed' }, { status: 502 }); + } + + const inboxId = inboxBody.ids[0]; const emailProperties = ['id', 'threadId', 'from', 'subject', 'preview', 'receivedAt']; if (!inboxId && !requestedEmailId) { @@ -232,6 +245,21 @@ export async function GET(request: NextRequest) { methodResponses: [string, Record, string][]; }; + // Missing/failed method responses are preview failures, not proof that + // there is no unread mail. A non-2xx response lets the SW show its fallback. + // The message the server named, once read, is a complete preview on its + // own, whatever became of the Inbox lookups next to it. + const resultOf = (name: string, id: string) => + data.methodResponses.find(([method, , callId]) => method === name && callId === id)?.[1]; + const failed = (methodCalls as [string, unknown, string][]).some(([name, , id]) => { + const result = resultOf(name, id); + return !result || (name === 'Email/query' ? !Array.isArray(result.ids) : !Array.isArray(result.list)); + }); + const deliveredList = resultOf('Email/get', 'delivered')?.list; + if (failed && !(Array.isArray(deliveredList) && deliveredList.length > 0)) { + return NextResponse.json({ error: 'JMAP email query failed' }, { status: 502 }); + } + type EmailLite = { id: string; threadId: string; @@ -246,7 +274,9 @@ export async function GET(request: NextRequest) { let unreadTotal = 0; for (const [method, body, callId] of data.methodResponses) { if (method === 'Email/query') { - unreadTotal = ((body as { total?: number }).total) ?? 0; + // A server that leaves out the optional total still lists the ids. + const query = body as { total?: number; ids?: unknown[] }; + unreadTotal = typeof query.total === 'number' ? query.total : (query.ids?.length ?? 0); } if (method === 'Email/get') { const list = (body as { list?: EmailLite[] }).list ?? []; @@ -263,11 +293,23 @@ export async function GET(request: NextRequest) { unreadTotal = Math.max(unreadTotal, 1); } email = delivered; + } else if (requestedEmailId) { + // The server named the message that arrived and it could not be read - + // deleted since, or filed where this login cannot see it. "Newest unread + // in the Inbox" is then some other message, and announcing it would be + // confidently wrong. Name no message: the unread total still comes back, + // so the SW posts its generic toast instead of staying silent. + email = null; } + // Some servers build the preview from HTML without skipping ${effectiveEmailContent.html}`; +${resolveColorSchemeMedia(effectiveEmailContent.html, isDark)}`; }, [effectiveEmailContent.html, effectiveEmailContent.isHtml, effectiveEmailContent.hasStyleTag, effectiveEmailContent.externalBlocked, isDark, emailHasNativeDarkMode, messageSpacing]); // Unblocking external content is handled by rebuilding the iframe srcDoc: @@ -2473,6 +2596,13 @@ export function EmailViewer({ hide: t('hide_quoted_text'), }); + // Before the height wiring and after the quote toggle exists, so the + // toggle is converted too. Reads the mail's computed colours and + // un-hides the body when done. + if (isDark) { + applyEmailDarkMode(doc, { remoteContentAllowed: !effectiveEmailContent.externalBlocked }); + } + // Auto-resize iframe to fit content // Measure max(documentElement, body): a height:100% wrapper can leave // documentElement.scrollHeight short while the real content lives in body. @@ -2541,13 +2671,13 @@ export function EmailViewer({ // Second pass over the rendered iframe DOM (the hook above only sees // DOMPurify's output); http(s) → new tab, other schemes left in place. - doc.querySelectorAll('a').forEach(applyNewTabToAnchor); + doc.querySelectorAll('a, area').forEach(applyNewTabToAnchor); // Plugin intercept: let plugins cancel or rewrite external links inside // the email body before navigation happens. Bound on the iframe doc so - // it survives DOM mutations from dark-mode pass below. + // it survives later DOM mutations. const onLinkClick = async (ev: Event) => { - const targetEl = (ev.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null; + const targetEl = (ev.target as Element | null)?.closest?.('a[href], area[href]') as HTMLAnchorElement | HTMLAreaElement | null; if (!targetEl) return; const href = targetEl.getAttribute('href') || ''; if (!href || href.startsWith('#') || href.startsWith('mailto:')) return; @@ -2576,106 +2706,11 @@ export function EmailViewer({ }; doc.addEventListener('click', onLinkClick, true); - // Dark mode: re-invert elements with stylesheet-defined background images - // (CSS attribute selectors only catch inline styles, not ${emailContent.html}`; - }, [emailContent.isHtml, emailContent.html]); + }, [emailContent.isHtml, emailContent.html, allowExternal, isDark]); const handleIframeLoad = useCallback(() => { const iframe = iframeRef.current; @@ -505,6 +490,7 @@ function EmailCard({ show: t('email_viewer.show_quoted_text'), hide: t('email_viewer.hide_quoted_text'), }); + if (isDark) applyEmailDarkMode(doc, { remoteContentAllowed: allowExternal }); const resize = () => { // Fit desktop-width mail to the screen before measuring: the transform // leaves the layout height untouched, so scale the box by hand. @@ -515,14 +501,14 @@ function EmailCard({ resize(); const ro = new ResizeObserver(resize); ro.observe(doc.body); - doc.querySelectorAll('a').forEach((a) => { + doc.querySelectorAll('a, area').forEach((a) => { a.setAttribute('target', '_blank'); a.setAttribute('rel', 'noopener noreferrer'); }); } catch { // contentDocument may be inaccessible under stricter sandboxes; ignore. } - }, [t]); + }, [t, isDark, allowExternal]); return (
{!isExpanded && density !== 'extra-compact' && (

- {email.preview || t('email_viewer.no_preview_available')} + {cleanPreview(email.preview) || t('email_viewer.no_preview_available')}

)}
@@ -616,6 +602,12 @@ function EmailCard({
)} + {verificationCode && ( +
+ +
+ )} + {/* Email Body */}
{emailContent.isHtml ? ( @@ -691,10 +683,10 @@ function EmailCard({ e.stopPropagation(); onReply(); }} - className="flex-1" + className="flex-1 min-w-0 px-2 whitespace-nowrap" > - - {t("email_viewer.reply")} + + {t("email_viewer.reply")} )} {onReplyAll && ( @@ -705,10 +697,10 @@ function EmailCard({ e.stopPropagation(); onReplyAll(); }} - className="flex-1" + className="flex-1 min-w-0 px-2 whitespace-nowrap" > - - {t("email_viewer.reply_all")} + + {t("email_viewer.reply_all")} )} {onForward && ( @@ -719,10 +711,10 @@ function EmailCard({ e.stopPropagation(); onForward(); }} - className="flex-1" + className="flex-1 min-w-0 px-2 whitespace-nowrap" > - - {t("email_viewer.forward")} + + {t("email_viewer.forward")} )}
diff --git a/components/email/thread-email-item.tsx b/components/email/thread-email-item.tsx index 64f6e6d43..83f54244d 100644 --- a/components/email/thread-email-item.tsx +++ b/components/email/thread-email-item.tsx @@ -2,7 +2,7 @@ import { useCallback } from "react"; import { useTranslations } from "next-intl"; -import { formatDate } from "@/lib/utils"; +import { cleanPreview, formatDate } from "@/lib/utils"; import { Email } from "@/lib/jmap/types"; import { cn } from "@/lib/utils"; import { Avatar } from "@/components/ui/avatar"; @@ -12,7 +12,7 @@ import { useLongPress } from "@/hooks/use-long-press"; import { useEmailStore } from "@/stores/email-store"; import { useSettingsStore } from "@/stores/settings-store"; import { useUIStore } from "@/stores/ui-store"; -import { getEmailTagIds } from "@/lib/thread-utils"; +import { emailKeyFor, getEmailTagIds } from "@/lib/thread-utils"; import { useKeywordFormat } from "@/hooks/use-keyword-format"; import { useTagDisplay } from "@/hooks/use-tag-display"; import { TagBadge } from "./tag-badge"; @@ -45,9 +45,9 @@ export function ThreadEmailItem({ // header pools them, so without this they disappear on the way in. const tagIds = sortTagIds(getEmailTagIds(email.keywords)); const sender = email.from?.[0]; - const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore(); + const { selectedMailbox, selectedEmailKeys, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore(); const density = useSettingsStore((state) => state.density); - const isChecked = selectedEmailIds.has(email.id); + const isChecked = selectedEmailKeys.has(emailKeyFor(email)); const { dragHandlers, isDragging } = useEmailDrag({ email, @@ -73,18 +73,18 @@ export function ThreadEmailItem({ const handleCheckboxClick = (e: React.MouseEvent) => { e.stopPropagation(); - toggleEmailSelection(email.id); + toggleEmailSelection(email); }; const handleClick = (e: React.MouseEvent) => { if (e.ctrlKey || e.metaKey) { e.preventDefault(); - toggleEmailSelection(email.id); + toggleEmailSelection(email); } else if (e.shiftKey) { e.preventDefault(); - selectRangeEmails(email.id); + selectRangeEmails(email); } else { - if (selectedEmailIds.size > 0) clearSelection(); + if (selectedEmailKeys.size > 0) clearSelection(); onClick?.(); } }; @@ -118,7 +118,7 @@ export function ThreadEmailItem({ >
{/* Checkbox - only visible when in selection mode */} - {selectedEmailIds.size > 0 && ( + {selectedEmailKeys.size > 0 && ( + {onToggleStar && ( + + )} +
+ ); +} + +function MvMobileStar({ + starred, + onToggle, + label, +}: { + starred: boolean; + onToggle?: () => void; + label: string; +}) { + return ( + + ); +} + function StatusIcon({ icon: Icon, label, className }: { icon: AppIcon; label: string; className: string }) { return ( <> @@ -163,13 +285,15 @@ const SingleEmailItem = React.forwardRef( function SingleEmailItem({ email, selected, onClick, onDoubleClick, onContextMenu, showPreview, rowTint, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetTag, onMarkAsSpam, onUndoSpam, onOpenAttachment, loadAttachments }, ref) { const t = useTranslations('email_viewer'); const tBatch = useTranslations('email_list.batch_actions'); + const tHover = useTranslations('settings.email_behavior.hover_actions'); const tStatus = useTranslations('email_list'); const isUnread = !email.keywords?.$seen; const isStarred = email.keywords?.$flagged; const isPinned = email.keywords?.['$pinned'] === true; const isAnswered = email.keywords?.$answered; const isForwarded = email.keywords?.$forwarded; - const { selectedMailbox, mailboxes, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection, isUnifiedView, unifiedRole } = useEmailStore(); + const showPaperclip = useListHasAttachment(email, loadAttachments); + const { selectedMailbox, mailboxes, selectedEmailKeys, toggleEmailSelection, selectRangeEmails, clearSelection, isUnifiedView, unifiedRole } = useEmailStore(); // In Sent/Drafts folders, show recipient instead of sender (which is always // "me"). In aggregate role-views the selected mailbox is virtual → fall back // to the unified role so junk-contextual UI and avatar hiding work. @@ -181,10 +305,12 @@ const SingleEmailItem = React.forwardRef( const { sortTagIds, tagColor } = useKeywordFormat(); const { variant: tagVariant, placement: tagPlacement } = useTagDisplay(); const tintListRowsByTag = useSettingsStore((state) => state.tintListRowsByTag); + const tintListRowsByAccount = useSettingsStore((state) => state.tintListRowsByAccount); const density = useSettingsStore((state) => state.density); - const mailLayout = useSettingsStore((state) => state.mailLayout); + const mailLayout = useEffectiveMailLayout(); const timeFormat = useSettingsStore((state) => state.timeFormat); const showAvatarsInJunk = useSettingsStore((state) => state.showAvatarsInJunk); + const interfaceLayout = useSettingsStore((state) => state.interfaceLayout); const hideJunkAvatarImages = currentMailboxRole === 'junk' && !showAvatarsInJunk; // Show the originating folder in the aggregate "All …" views. const showSourceFolder = isUnifiedView && !!email.sourceFolder; @@ -192,22 +318,43 @@ const SingleEmailItem = React.forwardRef( const account = email.accountId ? getAccountById(email.accountId) : undefined; const accountColor = account?.avatarColor; const accountDescription = describeAccount(email.accountLabel, account); - const isChecked = selectedEmailIds.has(email.id); + const isChecked = selectedEmailKeys.has(emailKeyFor(email)); const isMobile = useUIStore((state) => state.isMobile); // The horizontal one-line "focus" layout doesn't fit on narrow screens; fall back to multi-line on mobile. const isFocusedMailLayout = mailLayout === 'focus' && !isMobile; - const trimmedPreview = stripInvisibleLeading(email.preview ?? ''); + // Mountain View leads its rows with a checkbox and a clickable star + // instead of an avatar, and marks unread with weight alone. Only the + // one-line layout is shaped that way, so the two conditions travel + // together. + const mvRow = interfaceLayout === 'mountain-view' && isFocusedMailLayout; + const mvMobileRow = interfaceLayout === 'mountain-view' && isMobile; + const trimmedPreview = cleanPreview(email.preview); const inlinePreview = showPreview && trimmedPreview ? ` ${trimmedPreview}` : ''; // Search hits carry server snippets with the matched terms marked; they // replace the plain subject / preview so the user sees why a mail matched. const subjectSnippet = email.searchSnippet?.subject ?? null; const previewSnippet = showPreview ? (email.searchSnippet?.preview ?? null) : null; const scheduledSendLabel = email.isScheduled && email.scheduledSendAt - ? formatDateTime(email.scheduledSendAt, timeFormat) + ? formatScheduledSendAt(email.scheduledSendAt, timeFormat) : null; const tagIds = sortTagIds(getEmailTagIds(email.keywords)); - const resolvedRowTint = !tintListRowsByTag ? null : (rowTint ?? (tagIds[0] ? tagColor(tagIds[0]).rowTint : null)); + // The account tint stands in for the per-account dot, so it outranks the + // tag tint - the tag still shows its own colour on its chip. + // + // `accountId` only resolves to a local account for personal entries; shared + // ones carry the JMAP owner id, which no AccountEntry matches. Falling back + // to the reaching client and then to a colour derived from the label means + // every row that knows which account it came from gets tinted, instead of + // silently staying blank. + const accountTintSource = accountColor + ?? (email.sourceClientAccountId ? getAccountById(email.sourceClientAccountId)?.avatarColor : undefined) + ?? (email.accountLabel ? generateAvatarColor(email.accountLabel) : undefined); + const accountRowTint = (tintListRowsByAccount && isUnifiedView && accountTintSource) + ? (KEYWORD_PALETTE[accountTintKey(accountTintSource)]?.rowTint ?? null) + : null; + const resolvedRowTint = accountRowTint + ?? (!tintListRowsByTag ? null : (rowTint ?? (tagIds[0] ? tagColor(tagIds[0]).rowTint : null))); const { dragHandlers, isDragging } = useEmailDrag({ email, @@ -272,9 +419,9 @@ const SingleEmailItem = React.forwardRef( const handleCheckboxClick = (e: React.MouseEvent) => { e.stopPropagation(); if (e.shiftKey) { - selectRangeEmails(email.id); + selectRangeEmails(email); } else { - toggleEmailSelection(email.id); + toggleEmailSelection(email); } }; @@ -286,12 +433,12 @@ const SingleEmailItem = React.forwardRef( if (swipeEnabled && consumeTap()) { return; } if (e.ctrlKey || e.metaKey) { e.preventDefault(); - toggleEmailSelection(email.id); + toggleEmailSelection(email); } else if (e.shiftKey) { e.preventDefault(); - selectRangeEmails(email.id); + selectRangeEmails(email); } else { - if (selectedEmailIds.size > 0) clearSelection(); + if (selectedEmailKeys.size > 0) clearSelection(); onClick(); } }; @@ -306,19 +453,25 @@ const SingleEmailItem = React.forwardRef( data-subject={email.subject || ''} data-unread={isUnread ? 'true' : 'false'} data-starred={email.keywords?.$flagged ? 'true' : 'false'} + data-mv-mobile-row={mvMobileRow ? "" : undefined} + data-mv-row={mvRow && !resolvedRowTint ? "" : undefined} + data-checked={isChecked ? "" : undefined} aria-current={selected ? 'true' : undefined} className={cn( "relative group cursor-pointer select-none transition-shadow duration-200 border-b border-border overflow-hidden", + mvMobileRow && "border-b-transparent", resolvedRowTint ? resolvedRowTint : ( selected ? "bg-accent" - : "bg-background" + : mvRow && !isUnread + ? "bg-muted/60" + : "bg-background" ), selected && !resolvedRowTint && "shadow-sm", !resolvedRowTint && !selected && !isChecked && "hover:bg-muted hover:shadow-sm", !resolvedRowTint && (selected || isChecked) && "hover:bg-accent hover:shadow-sm", resolvedRowTint && "hover:brightness-95 dark:hover:brightness-110", - isUnread && !resolvedRowTint && "bg-accent/30", + isUnread && !resolvedRowTint && !mvRow && !mvMobileRow && "bg-accent/30", isChecked && "ring-2 ring-primary/20", isChecked && !resolvedRowTint && "bg-accent/40", isDragging && "opacity-50 scale-[0.98] ring-2 ring-primary/30", @@ -349,11 +502,11 @@ const SingleEmailItem = React.forwardRef(
)}
{/* Checkbox - only for extra-compact density (no avatar) while in selection mode */} - {density === 'extra-compact' && selectedEmailIds.size > 0 && ( + {!mvRow && density === 'extra-compact' && selectedEmailKeys.size > 0 && ( )} - {density !== 'extra-compact' && ( - )} - {isUnread && ( - + {!mvRow && density !== 'extra-compact' && ( +
+ + {isUnread && } +
+ )} + + {isUnread && !mvRow && density === 'extra-compact' && ( + )}
{isFocusedMailLayout ? ( + <>
- {isUnifiedView && email.accountId && accountColor && ( + {isUnifiedView && email.accountId && accountColor && !tintListRowsByAccount && ( ( )} {sender?.name || (sender?.email && formatAddress(sender.email)) || 'Unknown'} -
+
{tagIds.length > 0 && ( - + {tagIds.map((id) => ( ))} @@ -422,29 +590,31 @@ const SingleEmailItem = React.forwardRef( )} {subjectSnippet ? : (email.subject || '(no subject)')} {(previewSnippet || inlinePreview) && ( - {previewSnippet ? <> : inlinePreview} + {/* Gmail runs the snippet on from the subject after a dash. */} + {mvRow && '\u00a0-\u00a0'} + {previewSnippet ? <> : (mvRow ? trimmedPreview : inlinePreview)} )}
{isPinned && } - {isStarred && } - {isAnswered && !isForwarded && } - {isForwarded && !isAnswered && } - {isAnswered && isForwarded && ( + {isStarred && !mvRow && } + {isAnswered && !isForwarded && !mvRow && } + {isForwarded && !isAnswered && !mvRow && } + {isAnswered && isForwarded && !mvRow && ( <> )} - {email.hasAttachment && } + {showPaperclip && } {showSourceFolder && } {scheduledSendLabel ? ( ( ) : ( - {formatDate(email.receivedAt)} + {formatDate(email.receivedAt, mvRow ? { listStyle: 'mountain-view' } : undefined)} )}
+ {mvRow && ( + + )} + ) : ( <>
- {isUnifiedView && email.accountId && accountColor && ( + {isUnifiedView && email.accountId && accountColor && !tintListRowsByAccount && ( ( {isPinned && ( )} - {isStarred && ( + {isStarred && !mvMobileRow && ( )} {isAnswered && !isForwarded && ( @@ -511,7 +685,7 @@ const SingleEmailItem = React.forwardRef( )} - {email.hasAttachment && ( + {showPaperclip && ( )}
@@ -536,6 +710,13 @@ const SingleEmailItem = React.forwardRef( {formatDate(email.receivedAt)} )} + {mvMobileRow && !(showPreview && density !== 'extra-compact' && density !== 'compact') && ( + + )}
@@ -558,23 +739,26 @@ const SingleEmailItem = React.forwardRef(
{showPreview && density !== 'extra-compact' && density !== 'compact' && ( -

- {previewSnippet ? : (trimmedPreview || t('no_preview_available'))} -

- )} - {onOpenAttachment && ( - +
+

+ {previewSnippet ? : (trimmedPreview || t('no_preview_available'))} +

+ {mvMobileRow && ( + + )} +
)} + )}
@@ -584,7 +768,7 @@ const SingleEmailItem = React.forwardRef( {!email.isScheduled && ( state.showPreview); const density = useSettingsStore((state) => state.density); - const mailLayout = useSettingsStore((state) => state.mailLayout); + const mailLayout = useEffectiveMailLayout(); const timeFormat = useSettingsStore((state) => state.timeFormat); const showAvatarsInJunk = useSettingsStore((state) => state.showAvatarsInJunk); + const interfaceLayout = useSettingsStore((state) => state.interfaceLayout); const isMobile = useUIStore((state) => state.isMobile); - const { latestEmail, participantNames, hasUnread, hasStarred, hasPinned, hasAttachment, hasAnswered, hasForwarded, emailCount } = thread; + const { latestEmail, participantNames, hasUnread, hasStarred, hasPinned, hasAnswered, hasForwarded, emailCount } = thread; + // Only the latest email's parts are loaded; an older one with the flag keeps the paperclip. + const latestHasAttachment = useListHasAttachment(latestEmail, loadAttachments); + const hasAttachment = latestHasAttachment || thread.emails.some((e) => e !== latestEmail && e.hasAttachment); // The horizontal one-line "focus" layout doesn't fit on narrow screens; fall back to multi-line on mobile. const isFocusedMailLayout = mailLayout === 'focus' && !isMobile; - const trimmedPreview = stripInvisibleLeading(latestEmail.preview ?? ''); + // Mountain View leads its rows with a checkbox and a clickable star + // instead of an avatar, and marks unread with weight alone. Only the + // one-line layout is shaped that way, so the two conditions travel + // together. + const mvRow = interfaceLayout === 'mountain-view' && isFocusedMailLayout; + const mvMobileRow = interfaceLayout === 'mountain-view' && isMobile; + const trimmedPreview = cleanPreview(latestEmail.preview); const inlinePreview = showPreview && trimmedPreview ? ` ${trimmedPreview}` : ''; // In a search the matched mail need not be the thread's latest one: show // the snippet of whichever email in the thread carries one. @@ -645,10 +840,10 @@ export const ThreadListItem = React.forwardRef state.getAccountById); const threadAccount = latestEmail.accountId ? getAccountById(latestEmail.accountId) : undefined; @@ -688,14 +883,22 @@ export const ThreadListItem = React.forwardRef state.tintListRowsByTag); + const tintListRowsByAccount = useSettingsStore((state) => state.tintListRowsByAccount); // A collapsed row speaks for every message under it, so it carries their tags too. const tagIds = sortTagIds(getThreadTagIds(thread.emails)); - const rowTint = (tintListRowsByTag && tagIds[0]) ? tagColor(tagIds[0]).rowTint : null; + const threadTintSource = threadAccountColor + ?? (latestEmail.sourceClientAccountId ? getAccountById(latestEmail.sourceClientAccountId)?.avatarColor : undefined) + ?? (latestEmail.accountLabel ? generateAvatarColor(latestEmail.accountLabel) : undefined); + const accountRowTint = (tintListRowsByAccount && isUnifiedView && threadTintSource) + ? (KEYWORD_PALETTE[accountTintKey(threadTintSource)]?.rowTint ?? null) + : null; + const rowTint = accountRowTint + ?? ((tintListRowsByTag && tagIds[0]) ? tagColor(tagIds[0]).rowTint : null); const isSelected = selectedEmailId === latestEmail.id || thread.emails.some(e => e.id === selectedEmailId); - const isChecked = thread.emails.some(e => selectedEmailIds.has(e.id)); + const isChecked = thread.emails.some(e => selectedEmailKeys.has(emailKeyFor(e))); if (emailCount === 1) { return ( @@ -725,22 +928,22 @@ export const ThreadListItem = React.forwardRef { - const allSelected = thread.emails.every(em => selectedEmailIds.has(em.id)); - const newSelection = new Set(selectedEmailIds); + const allSelected = thread.emails.every(em => selectedEmailKeys.has(emailKeyFor(em))); + const newSelection = new Set(selectedEmailKeys); thread.emails.forEach(em => { if (allSelected) { - newSelection.delete(em.id); + newSelection.delete(emailKeyFor(em)); } else { - newSelection.add(em.id); + newSelection.add(emailKeyFor(em)); } }); - useEmailStore.setState({ selectedEmailIds: newSelection, lastSelectedEmailId: latestEmail.id }); + useEmailStore.setState({ selectedEmailKeys: newSelection, lastSelectedEmailKey: emailKeyFor(latestEmail) }); }; const handleThreadCheckboxClick = (e: React.MouseEvent) => { e.stopPropagation(); if (e.shiftKey) { - selectRangeEmails(latestEmail.id); + selectRangeEmails(latestEmail); return; } toggleThreadSelection(); @@ -750,12 +953,12 @@ export const ThreadListItem = React.forwardRef toggleEmailSelection(em.id)); + thread.emails.forEach(em => toggleEmailSelection(em)); return; } if (e.shiftKey) { e.preventDefault(); - selectRangeEmails(latestEmail.id); + selectRangeEmails(latestEmail); return; } @@ -764,11 +967,19 @@ export const ThreadListItem = React.forwardRef 0) clearSelection(); + onEmailSelect(latestEmail); + return; + } + const target = e.target as HTMLElement; if (target.closest('[data-expand-toggle]')) { onToggleExpand(); } else { - if (selectedEmailIds.size > 0) clearSelection(); + if (selectedEmailKeys.size > 0) clearSelection(); if (!isExpanded) { onCollapseAllThreads?.(); onToggleExpand(); @@ -782,23 +993,33 @@ export const ThreadListItem = React.forwardRef +
{/* Checkbox for thread selection - only for extra-compact density (no avatar) while in selection mode */} - {density === 'extra-compact' && selectedEmailIds.size > 0 && ( + {!mvRow && density === 'extra-compact' && selectedEmailKeys.size > 0 && ( + ); +} diff --git a/components/files/__tests__/eml-preview-remote-block.test.tsx b/components/files/__tests__/eml-preview-remote-block.test.tsx new file mode 100644 index 000000000..bccca4a13 --- /dev/null +++ b/components/files/__tests__/eml-preview-remote-block.test.tsx @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { render } from '@testing-library/react'; + +vi.mock('next-intl', () => ({ + useTranslations: () => (key: string) => key, +})); + +import { EmlPreview } from '../eml-preview'; +import { useSettingsStore } from '@/stores/settings-store'; + +// The .eml attachment preview sanitized the body but never blocked remote +// content and set no CSP, so opening an attached message fired its trackers +// whatever the user's remote-content policy said. + +const HTML = '

x

'; + +function srcdoc(): string { + const { container } = render( + , + ); + return container.querySelector('iframe')?.getAttribute('srcdoc') ?? ''; +} + +afterEach(() => { + useSettingsStore.setState({ externalContentPolicy: 'ask' }); +}); + +describe('EmlPreview remote content', () => { + it('blocks remote images and sets the strict CSP by default', () => { + const doc = srcdoc(); + expect(doc).not.toMatch(/\s(src|srcset)="https:\/\/t\.example/); + const csp = /Content-Security-Policy" content="([^"]*)"/.exec(doc)?.[1] ?? ''; + expect(csp).toContain("img-src data: blob:;"); + expect(doc).toContain(''); + }); + + it('loads them when the user allows remote content everywhere', () => { + useSettingsStore.setState({ externalContentPolicy: 'allow' }); + expect(srcdoc()).toContain('src="https://t.example/pixel.gif"'); + }); +}); diff --git a/components/files/__tests__/file-browser-shared-folders.test.tsx b/components/files/__tests__/file-browser-shared-folders.test.tsx new file mode 100644 index 000000000..8ed739628 --- /dev/null +++ b/components/files/__tests__/file-browser-shared-folders.test.tsx @@ -0,0 +1,337 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import { FileBrowser } from '../file-browser'; +import { useFileStore, type FileResource } from '@/stores/file-store'; +import type { IJMAPClient } from '@/lib/jmap/client-interface'; +import type { FileNode } from '@/lib/jmap/types'; + +vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } })); +vi.mock('@/components/settings/share-collection-dialog', () => ({ + ShareCollectionDialog: ({ collectionName, shareWith }: { collectionName: string; shareWith?: Record | null }) => ( +
{collectionName}:{Object.keys(shareWith ?? {}).join(',')}
+ ), +})); + +function node(id: string, name: string, parentId: string | null, extra: Partial = {}): FileNode { + return { + id, + name, + parentId, + type: 'd', + blobId: null, + size: 0, + created: '2026-10-01T00:00:00Z', + modified: '2026-10-01T00:00:00Z', + ...extra, + }; +} + +function resource(n: FileNode): FileResource { + return { + id: n.id, + name: n.name, + serverName: n.name, + isDirectory: n.blobId == null, + contentType: n.blobId == null ? '' : n.type, + contentLength: n.size, + lastModified: n.modified ?? '', + blobId: n.blobId, + parentId: n.parentId, + shareWith: n.shareWith, + isShared: n.isShared, + ownerName: n.accountName, + } as FileResource; +} + +const OWN: FileNode[] = [ + node('f-docs', 'Documents', null), + node('f-notes', 'notes.txt', null, { blobId: 'b-notes', type: 'text/plain', size: 10 }), +]; +const SHARED = node('e:f-team', 'Team', null, { isShared: true, accountId: 'e', accountName: 'userb@example.org' }); + +type Overrides = Partial>; + +function renderBrowser(opts: { resources?: FileResource[]; allFolders?: FileResource[]; props?: Overrides; hasListed?: boolean; shared?: FileNode[] } = {}) { + const client = { + listAllFileNodesAcrossAccounts: vi.fn(async () => [...OWN, ...(opts.shared ?? [SHARED])]), + } as unknown as IJMAPClient; + act(() => { + useFileStore.setState({ + client, + sharedRoots: [], + allFolders: opts.allFolders ?? OWN.filter((n) => n.blobId == null).map(resource), + currentParentId: null, + pathStack: [{ id: null, name: '' }], + hasListed: opts.hasListed ?? true, + }); + }); + const handlers = { + onNavigate: vi.fn(), + onSetSelection: vi.fn(), + onToggleSelect: vi.fn(), + onPreviewFile: vi.fn(), + onDownload: vi.fn(async () => {}), + onRenameNode: vi.fn(async () => {}), + onDeleteNode: vi.fn(async () => {}), + onDownloadNode: vi.fn(async () => {}), + onRevealNode: vi.fn(async () => {}), + onRemoveRecent: vi.fn(), + }; + const noop = vi.fn(async () => {}); + render( + ''} + favorites={[]} + recentFiles={[]} + onToggleFavorite={vi.fn()} + onOpenRecent={vi.fn()} + client={client} + ownAccountId="a" + sharingEnabled + onShare={noop} + {...handlers} + {...opts.props} + />, + ); + return handlers; +} + +// Narrow panes (and jsdom) show the sidebar as a drawer; open it like a user would. +function tree() { + const toggle = screen.queryByRole('button', { name: 'open_folder_tree' }); + if (toggle && toggle.getAttribute('aria-expanded') !== 'true') fireEvent.click(toggle); + return screen.getByRole('navigation', { name: 'folders' }); +} + +function list() { + return screen.getByRole('grid', { name: 'file_list' }); +} + +describe('FileBrowser', () => { + beforeEach(() => localStorage.clear()); + afterEach(() => { + act(() => { useFileStore.setState({ client: null, sharedRoots: [], allFolders: [] }); }); + }); + + it('lists folders shared with the user at the root and in the sidebar (#1181)', async () => { + const { onNavigate } = renderBrowser(); + await screen.findAllByText('Team'); + const section = screen.getByRole('region', { name: 'shared_with_me' }); + fireEvent.click(within(section).getByText('Team')); + expect(onNavigate).toHaveBeenCalledWith('/Team', 'e:f-team'); + expect(within(tree()).getByText('Team')).toBeInTheDocument(); + }); + + it('lists files shared on their own on a page per owner, at the root and in the sidebar', async () => { + const lone = node('e:f-plan', 'plan.pdf', 'e:f-private', { + blobId: 'b-plan', type: 'application/pdf', size: 5, isShared: true, accountId: 'e', accountName: 'userb@example.org', + }); + const { onNavigate } = renderBrowser({ shared: [SHARED, lone] }); + const section = await screen.findByRole('region', { name: 'shared_with_me' }); + fireEvent.click(await within(section).findByText('shared_files_from')); + expect(onNavigate).toHaveBeenCalledWith('/shared_files_from', 'e:*'); + fireEvent.click(within(tree()).getByText('shared_files_from')); + expect(onNavigate).toHaveBeenLastCalledWith('/shared_files_from', 'e:*'); + }); + + it('offers no download for a symlink', () => { + const link = { ...resource(node('f-link', 'shortcut.txt', null, { blobId: null, nodeType: 'symlink' } as Partial)), isDirectory: false, isSymlink: true }; + renderBrowser({ resources: [...OWN.map(resource), link] }); + const row = within(list()).getByText('shortcut.txt').closest('[role="row"]') as HTMLElement; + expect(within(row).queryByRole('button', { name: 'download' })).toBeNull(); + const notes = within(list()).getByText('notes.txt').closest('[role="row"]') as HTMLElement; + expect(within(notes).getByRole('button', { name: 'download' })).toBeInTheDocument(); + }); + + it('shows shared folders instead of the empty state when the own root is empty', async () => { + renderBrowser({ resources: [], allFolders: [] }); + expect(await screen.findAllByText('Team')).not.toHaveLength(0); + expect(screen.queryByText('empty_state_title')).toBeNull(); + }); + + it('lists folders in the file list as well as the tree', () => { + renderBrowser(); + expect(within(list()).getByText('Documents')).toBeInTheDocument(); + expect(within(tree()).getByText('Documents')).toBeInTheDocument(); + }); + + it('opens a folder from its name and selects it from the row', () => { + const { onNavigate, onSetSelection } = renderBrowser(); + const row = within(list()).getByText('Documents').closest('[role=row]')!; + fireEvent.click(row); + expect(onSetSelection).toHaveBeenCalledWith(new Set(['Documents'])); + expect(onNavigate).not.toHaveBeenCalled(); + + fireEvent.click(within(list()).getByText('Documents')); + expect(onNavigate).toHaveBeenCalledWith('/Documents', 'f-docs'); + }); + + it('previews a text file when its name is clicked', () => { + const { onPreviewFile } = renderBrowser(); + fireEvent.click(within(list()).getByText('notes.txt')); + expect(onPreviewFile).toHaveBeenCalledWith('notes.txt'); + }); + + it('shares an own folder from the tree with its current shares', async () => { + const shared = resource({ ...OWN[0], shareWith: { p1: { mayRead: true } } } as unknown as FileNode); + // Browsing another folder: the tree's folder is not in the listing. + renderBrowser({ resources: [resource(OWN[1])], allFolders: [shared] }); + + fireEvent.contextMenu(within(tree()).getByText('Documents')); + fireEvent.click(await screen.findByRole('menuitem', { name: 'share' })); + + expect(await screen.findByTestId('share-dialog')).toHaveTextContent('Documents:p1'); + }); + + it('offers no share action on folders shared with the user', async () => { + renderBrowser(); + await screen.findAllByText('Team'); + fireEvent.contextMenu(within(tree()).getByText('Team')); + expect(screen.queryByRole('menuitem', { name: 'share' })).toBeNull(); + }); + + it('hides dot files unless the setting shows them', () => { + const hidden = resource(node('f-env', '.env', null, { blobId: 'b-env', type: 'text/plain', size: 1 })); + renderBrowser({ resources: [...OWN.map(resource), hidden] }); + expect(within(list()).queryByText('.env')).toBeNull(); + }); + + it('shows dot files when the setting is on', () => { + localStorage.setItem('files-settings', JSON.stringify({ showHiddenFiles: true })); + const hidden = resource(node('f-env', '.env', null, { blobId: 'b-env', type: 'text/plain', size: 1 })); + renderBrowser({ resources: [...OWN.map(resource), hidden] }); + expect(within(list()).getByText('.env')).toBeInTheDocument(); + }); + + it('starts in the default view and sort from the settings', () => { + localStorage.setItem('files-settings', JSON.stringify({ defaultSortKey: 'name', defaultSortDir: 'desc' })); + const files = ['a.txt', 'c.txt', 'b.txt'].map((n, i) => resource(node(`f${i}`, n, null, { blobId: `b${i}`, type: 'text/plain', size: 1 }))); + renderBrowser({ resources: files, allFolders: [] }); + const names = within(list()).getAllByRole('row').slice(1).map((r) => r.getAttribute('data-resource')); + expect(names).toEqual(['c.txt', 'b.txt', 'a.txt']); + }); + + it('shows the loading skeleton, not the empty state, before the first listing', () => { + renderBrowser({ resources: [], allFolders: [], hasListed: false }); + expect(screen.queryByText('empty_state_title')).toBeNull(); + expect(screen.queryByText('empty_folder_title')).toBeNull(); + }); + + it('shows an empty state with upload and new folder in an empty folder', () => { + renderBrowser({ resources: [], allFolders: [], props: { currentPath: '/Documents' } }); + expect(screen.getByText('empty_folder_title')).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: /upload_files/ }).length).toBeGreaterThan(0); + }); + + it('keeps a drag selection when the mouse is released', () => { + const onClearSelection = vi.fn(); + const { onSetSelection } = renderBrowser({ props: { onClearSelection, selectedResources: new Set(['notes.txt']) } }); + const area = list().parentElement!; + // jsdom lays everything out at 0,0, so a box from -5,-5 to 20,20 covers every row. + fireEvent.mouseDown(area, { button: 0, clientX: -5, clientY: -5 }); + fireEvent.mouseMove(window, { clientX: 20, clientY: 20 }); + fireEvent.mouseUp(window, { clientX: 20, clientY: 20 }); + fireEvent.click(area); + + expect(onSetSelection).toHaveBeenLastCalledWith(new Set(['Documents', 'notes.txt'])); + // Only the press that started the drag cleared the old selection. + expect(onClearSelection).toHaveBeenCalledTimes(1); + }); + + it('offers new and upload entries on My files in the sidebar', () => { + renderBrowser(); + fireEvent.contextMenu(within(tree()).getByText('my_files')); + for (const name of ['open', 'new_folder', 'new_text_file', 'upload_files', 'upload_folder']) { + expect(screen.getByRole('menuitem', { name })).toBeInTheDocument(); + } + }); + + it('renames and deletes a folder from the tree', async () => { + const { onRenameNode, onDeleteNode } = renderBrowser(); + fireEvent.contextMenu(within(tree()).getByText('Documents')); + fireEvent.click(screen.getByRole('menuitem', { name: 'rename' })); + const input = await screen.findByDisplayValue('Documents'); + fireEvent.change(input, { target: { value: 'Docs' } }); + fireEvent.submit(input.closest('form')!); + await vi.waitFor(() => expect(onRenameNode).toHaveBeenCalledWith('f-docs', 'Docs')); + + fireEvent.contextMenu(within(tree()).getByText('Documents')); + fireEvent.click(screen.getByRole('menuitem', { name: 'delete' })); + expect(onDeleteNode).toHaveBeenCalledWith('f-docs', 'Documents'); + }); + + it('offers no rename or delete on a folder shared with the user', async () => { + renderBrowser(); + await screen.findAllByText('Team'); + fireEvent.contextMenu(within(tree()).getByText('Team')); + expect(screen.getByRole('menuitem', { name: 'open' })).toBeInTheDocument(); + expect(screen.queryByRole('menuitem', { name: 'rename' })).toBeNull(); + expect(screen.queryByRole('menuitem', { name: 'delete' })).toBeNull(); + }); + + it('shows, downloads and forgets a recent file from its menu', () => { + const { onRevealNode, onDownloadNode, onRemoveRecent } = renderBrowser({ + props: { recentFiles: [{ name: 'notes.txt', id: 'f-notes', timestamp: 1 }] }, + }); + const open = (name: string) => { + fireEvent.contextMenu(within(tree()).getByText('notes.txt')); + fireEvent.click(screen.getByRole('menuitem', { name })); + }; + open('show_in_folder'); + expect(onRevealNode).toHaveBeenCalledWith('f-notes'); + open('download'); + expect(onDownloadNode).toHaveBeenCalledWith('f-notes'); + open('remove_from_recent'); + expect(onRemoveRecent).toHaveBeenCalledWith('f-notes'); + }); + + it('outlines the clicked item while it is selected', () => { + renderBrowser({ props: { selectedResources: new Set(['notes.txt']) } }); + const row = within(list()).getByText('notes.txt').closest('[role=row]')!; + fireEvent.click(row); + expect(row.className).toContain('ring-ring'); + }); + + it('drops the outline once the clicked item is deselected, but keeps it for the keyboard', () => { + // The selection prop stays empty, as after deselecting. + renderBrowser(); + const row = () => within(list()).getByText('notes.txt').closest('[role=row]')!; + fireEvent.click(row()); + expect(row().className).not.toContain('ring-ring'); + + fireEvent.keyDown(window, { key: 'ArrowUp' }); + fireEvent.keyDown(window, { key: 'ArrowDown' }); + expect(row().className).toContain('ring-ring'); + }); + + it('replaces the toolbar with selection actions when items are selected', () => { + renderBrowser({ props: { selectedResources: new Set(['notes.txt']) } }); + const bar = screen.getByRole('toolbar', { name: 'selection_actions' }); + expect(within(bar).getByRole('button', { name: 'download' })).toBeInTheDocument(); + expect(within(bar).getByRole('button', { name: 'delete' })).toBeInTheDocument(); + }); +}); diff --git a/components/files/__tests__/file-picker-dialog.test.tsx b/components/files/__tests__/file-picker-dialog.test.tsx new file mode 100644 index 000000000..75933339e --- /dev/null +++ b/components/files/__tests__/file-picker-dialog.test.tsx @@ -0,0 +1,102 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { FilePickerDialog } from '../file-picker-dialog'; +import type { IJMAPClient } from '@/lib/jmap/client-interface'; +import type { FileNode } from '@/lib/jmap/types'; + +vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } })); + +// Picking files from the Files app for a message (#1179). + +function node(id: string, name: string, parentId: string | null, extra: Partial = {}): FileNode { + const isFolder = extra.blobId === null; + return { + id, + name, + parentId, + type: isFolder ? 'd' : 'application/pdf', + blobId: `blob-${id}`, + size: isFolder ? 0 : 1000, + created: '2026-10-01T00:00:00Z', + modified: '2026-10-01T00:00:00Z', + ...extra, + }; +} + +const TREE: FileNode[] = [ + node('f-docs', 'Documents', null, { blobId: null }), + node('f-report', 'report.pdf', 'f-docs'), + node('f-invoice', 'invoice.pdf', null), + node('f-hidden', '.secret', null), + node('e:f-plan', 'plan.pdf', null, { isShared: true, accountId: 'e', accountName: 'userb@example.org' }), +]; + +function clientWith(list: () => Promise): IJMAPClient { + return { listAllFileNodesAcrossAccounts: vi.fn(list) } as unknown as IJMAPClient; +} + +function renderPicker(list: () => Promise = async () => TREE) { + const onPick = vi.fn(); + const onClose = vi.fn(); + const client = clientWith(list); + render(); + return { onPick, onClose, client }; +} + +describe('FilePickerDialog', () => { + it('lists the root without hidden or shared nodes, and offers Shared with me', async () => { + renderPicker(); + expect(await screen.findByText('invoice.pdf')).toBeInTheDocument(); + expect(screen.getByText('Documents')).toBeInTheDocument(); + expect(screen.getByText('shared_with_me')).toBeInTheDocument(); + expect(screen.queryByText('.secret')).toBeNull(); + expect(screen.queryByText('plan.pdf')).toBeNull(); + }); + + it('keeps the selection while browsing folders and hands back the picked nodes', async () => { + const { onPick } = renderPicker(); + fireEvent.click(await screen.findByText('invoice.pdf')); + fireEvent.click(screen.getByText('Documents')); + fireEvent.click(await screen.findByText('report.pdf')); + fireEvent.click(screen.getByText('my_files')); + fireEvent.click(screen.getByText('shared_with_me')); + fireEvent.click(await screen.findByText('plan.pdf')); + + fireEvent.click(screen.getByTestId('file-picker-attach')); + expect(onPick).toHaveBeenCalledTimes(1); + expect(onPick.mock.calls[0][0].map((n: FileNode) => n.id)).toEqual(['f-invoice', 'f-report', 'e:f-plan']); + }); + + it('unselects a file on a second click and only enables Attach with a selection', async () => { + renderPicker(); + const attach = screen.getByTestId('file-picker-attach'); + expect(attach).toBeDisabled(); + const row = (await screen.findByText('invoice.pdf')).closest('button')!; + fireEvent.click(row); + expect(row).toHaveAttribute('aria-checked', 'true'); + expect(attach).toBeEnabled(); + fireEvent.click(row); + expect(row).toHaveAttribute('aria-checked', 'false'); + expect(attach).toBeDisabled(); + }); + + it('searches files in every folder and shows where each one lives', async () => { + renderPicker(); + await screen.findByText('invoice.pdf'); + fireEvent.change(screen.getByPlaceholderText('search_placeholder'), { target: { value: 'RE' } }); + expect(screen.getByText('report.pdf')).toBeInTheDocument(); + expect(screen.getByText('Documents')).toBeInTheDocument(); + expect(screen.queryByText('invoice.pdf')).toBeNull(); + }); + + it('offers a retry when the listing fails', async () => { + let calls = 0; + renderPicker(async () => { + calls += 1; + if (calls === 1) throw new Error('boom'); + return TREE; + }); + fireEvent.click(await screen.findByText('retry')); + expect(await screen.findByText('invoice.pdf')).toBeInTheDocument(); + }); +}); diff --git a/components/files/__tests__/file-preview-modal-image.test.tsx b/components/files/__tests__/file-preview-modal-image.test.tsx new file mode 100644 index 000000000..95b67a35b --- /dev/null +++ b/components/files/__tests__/file-preview-modal-image.test.tsx @@ -0,0 +1,61 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; + +vi.mock('next-intl', () => ({ + useTranslations: () => (key: string) => key, +})); + +import { FilePreviewModal } from '../file-preview-modal'; + +// The image preview used a plain object URL of the attachment, and those share +// the webmail origin. "Open image in new tab" on a sender's SVG (or on HTML +// declared on an .svg name) then loaded it as a same-origin document. + +const SVG = ''; + +let created: Blob[]; + +beforeEach(() => { + created = []; + vi.spyOn(URL, 'createObjectURL').mockImplementation((blob) => { + created.push(blob as Blob); + return 'blob:test'; + }); + vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +async function previewSrc(name: string, contentType: string, bytes: BlobPart): Promise { + render( + {}} + onDownload={() => {}} + getFileContent={async () => ({ blob: new Blob([bytes], { type: contentType }), contentType })} + />, + ); + return (await screen.findByAltText(name)).getAttribute('src') ?? ''; +} + +describe('FilePreviewModal image URLs', () => { + it('shows an SVG from a data: URL, never a same-origin object URL', async () => { + const src = await previewSrc('drawing.svg', 'image/svg+xml', SVG); + expect(src.startsWith('data:image/svg+xml;base64,')).toBe(true); + expect(created).toEqual([]); + expect(screen.queryByLabelText('open_in_new_tab')).toBeNull(); + }); + + it('retypes HTML declared on an image name to something no browser runs', async () => { + expect(await previewSrc('drawing.svg', 'text/html', '')).toBe('blob:test'); + expect(created.map((b) => b.type)).toEqual(['application/octet-stream']); + }); + + it('keeps raster images as object URLs of their own type', async () => { + expect(await previewSrc('photo.png', 'image/png', new Uint8Array([137, 80, 78, 71]))).toBe('blob:test'); + expect(created.map((b) => b.type)).toEqual(['image/png']); + expect(screen.getByLabelText('open_in_new_tab')).toBeTruthy(); + }); +}); diff --git a/components/files/__tests__/image-preview-modal.test.tsx b/components/files/__tests__/image-preview-modal.test.tsx new file mode 100644 index 000000000..27f3d499c --- /dev/null +++ b/components/files/__tests__/image-preview-modal.test.tsx @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { ImagePreviewModal } from '../image-preview-modal'; + +async function renderViewer() { + const onClose = vi.fn(); + render( + {}} + getImageUrl={async () => 'data:image/png;base64,AAAA'} + />, + ); + const img = await screen.findByAltText('photo.jpg'); + return { onClose, img, box: img.parentElement! }; +} + +function tap(el: Element, x = 10, y = 10) { + fireEvent.pointerDown(el, { pointerId: 1, button: 0, clientX: x, clientY: y, pointerType: 'mouse' }); + fireEvent.pointerUp(el, { pointerId: 1, button: 0, clientX: x, clientY: y, pointerType: 'mouse' }); +} + +describe('ImagePreviewModal', () => { + it('closes when the area around the image is clicked', async () => { + const { onClose, box } = await renderViewer(); + tap(box); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('stays open when the image itself is clicked', async () => { + const { onClose, img } = await renderViewer(); + tap(img); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('does not close after a drag that starts beside the image', async () => { + const { onClose, box } = await renderViewer(); + fireEvent.pointerDown(box, { pointerId: 1, button: 0, clientX: 10, clientY: 10, pointerType: 'mouse' }); + fireEvent.pointerMove(box, { pointerId: 1, clientX: 80, clientY: 60, pointerType: 'mouse' }); + fireEvent.pointerUp(box, { pointerId: 1, button: 0, clientX: 80, clientY: 60, pointerType: 'mouse' }); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('zooms with the buttons and resets to fit', async () => { + const { img } = await renderViewer(); + fireEvent.click(screen.getByRole('button', { name: 'zoom_in' })); + expect(img.style.transform).toContain('scale(1.5)'); + act(() => { fireEvent.keyDown(window, { key: '0' }); }); + expect(img.style.transform).toContain('scale(1)'); + }); + + it('closes on Escape', async () => { + const { onClose } = await renderViewer(); + fireEvent.keyDown(window, { key: 'Escape' }); + expect(onClose).toHaveBeenCalled(); + }); +}); diff --git a/components/files/__tests__/wopi-base-path.test.tsx b/components/files/__tests__/wopi-base-path.test.tsx new file mode 100644 index 000000000..c1facd996 --- /dev/null +++ b/components/files/__tests__/wopi-base-path.test.tsx @@ -0,0 +1,39 @@ +import { render, renderHook, waitFor, cleanup } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { useWopiStatus } from '@/hooks/use-wopi-status'; +import { WopiEditor } from '@/components/files/wopi-editor'; + +// Behind a reverse proxy at a sub-path (e.g. /webmail) a bare +// fetch('/api/...') reaches the mail server instead of the webmail and comes +// back 404, which left office editing permanently "unavailable" there. Both +// WOPI requests have to carry the mount prefix. + +vi.mock('next-intl', () => ({ useTranslations: () => (key: string) => key, useLocale: () => 'de' })); + +let fetchMock: ReturnType; + +beforeEach(() => { + window.history.pushState({}, '', '/webmail/de/mail'); + fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 404, json: async () => ({}) }); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + window.history.pushState({}, '', '/'); +}); + +describe('WOPI requests under a sub-path mount', () => { + it('probes the editor status under the mount prefix', async () => { + renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + expect(fetchMock.mock.calls[0][0]).toBe('/webmail/api/wopi/status'); + }); + + it('launches the editor under the mount prefix', async () => { + render( {}} />); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + expect(fetchMock.mock.calls[0][0]).toBe('/webmail/api/wopi/launch'); + }); +}); diff --git a/components/files/eml-preview.tsx b/components/files/eml-preview.tsx index 49197d7da..4e249b1fe 100644 --- a/components/files/eml-preview.tsx +++ b/components/files/eml-preview.tsx @@ -2,8 +2,9 @@ import { useTranslations } from "next-intl"; import { Paperclip, Download } from "@/components/icons"; -import { sanitizeEmailHtmlForIframe } from "@/lib/email-sanitization"; +import { emailIframeCsp, sanitizeEmailBodyForIframe } from "@/lib/email-sanitization"; import { getEffectiveTimeZone } from "@/lib/timezone"; +import { useSettingsStore } from "@/stores/settings-store"; // A parsed message/rfc822 (.eml), as produced by postal-mime. Only the fields // this preview renders are typed. @@ -36,20 +37,24 @@ function escapeHtml(s: string): string { // body, plus the message's own attachments. The body is sanitized with // DOMPurify AND rendered in a fully-locked sandbox iframe (sandbox="" - no // scripts, no same-origin), so a script-bearing .eml can never execute in our -// origin. Parsing happens in the caller (FilePreviewModal); this is pure -// presentation. +// origin. Remote content is blocked unless the user allows it everywhere: +// there is no per-message "load" here. Parsing happens in the caller +// (FilePreviewModal); this is pure presentation. export function EmlPreview({ message }: { message: ParsedEml }) { const t = useTranslations("email_viewer"); + const blockRemote = useSettingsStore((state) => state.externalContentPolicy) !== "allow"; - // srcDoc gets a fragment, not a document, so the iframe's implicit - // is the browser's - left-to-right regardless of what the mail is written - // in. dir="auto" on a wrapper we do control lets the first strong character - // pick the direction, matching the main viewer. - const bodyDoc = message.html - ? `
${sanitizeEmailHtmlForIframe(message.html)}
` + // dir="auto" on a wrapper we control lets the first strong character pick + // the direction, matching the main viewer. + const body = message.html + ? `
${sanitizeEmailBodyForIframe(message.html, blockRemote).html}
` : message.text ? `
${escapeHtml(message.text)}
` : ""; + // The strict CSP is the network backstop for whatever the DOM walk misses. + const bodyDoc = body + ? `${body}` + : ""; const downloadAttachment = (att: NonNullable[number]) => { if (!att.content) return; diff --git a/components/files/file-browser.tsx b/components/files/file-browser.tsx index cf6fa01c0..5becc54cb 100644 --- a/components/files/file-browser.tsx +++ b/components/files/file-browser.tsx @@ -3,38 +3,34 @@ import { useState, useCallback, useRef, useEffect, useMemo } from "react"; import { useTranslations } from "next-intl"; import { - Folder, File, Upload, FolderPlus, Download, Trash2, - Pencil, RefreshCw, Home, ChevronRight, MoreVertical, - Search, ArrowUp, ArrowDown, X, LayoutGrid, LayoutList, - Copy, Clipboard, Scissors, Info, Image as ImageIcon, - FilePlus, CopyPlus, FileText, FileAudio, FileVideo, - AlertCircle, Star, Clock, FolderUp, - FileArchive, FileSpreadsheet, Presentation, FileCode, - Box, PenTool, Terminal as TerminalIcon, Database, Type as TypeIcon, - Menu, Users, Share2, SquarePen, Link, + Upload, FolderPlus, Download, Trash2, Pencil, Copy, Clipboard, Scissors, Info, + FilePlus, CopyPlus, AlertCircle, FolderUp, Share2, SquarePen, Eye, FolderOpen, + RefreshCw, Star, StarOff, Plus, CheckSquare, File, } from "@/components/icons"; -import { useIsDesktop } from "@/hooks/use-media-query"; +import { useIsDesktop, useIsMobile, useMediaQuery } from "@/hooks/use-media-query"; +import { useContextMenu } from "@/hooks/use-context-menu"; import { Button } from "@/components/ui/button"; -import { cn, formatFileSize } from "@/lib/utils"; +import { ContextMenu, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"; +import { Avatar } from "@/components/ui/avatar"; +import { cn } from "@/lib/utils"; import { NewFolderDialog } from "@/components/files/new-folder-dialog"; import { RenameDialog } from "@/components/files/rename-dialog"; import { fileNameProblem } from "@/lib/file-name-rules"; -import { FileUploadArea } from "@/components/files/file-upload-area"; -import { loadFilesSettings } from "@/components/files/files-settings-dialog"; -import type { FolderLayout } from "@/components/files/files-settings-dialog"; -import { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar"; +import { EmptyFolder, NoSearchResults } from "@/components/files/file-empty-state"; +import { isAudioFile, isImageFile, isPdfFile, isTextFile, isVideoFile } from "@/components/files/file-icons"; +import { loadFilesSettings, saveFilesSettings, type FilesSettings } from "@/components/files/files-settings"; +import { FilesSidebar, type CreateKind } from "@/components/files/files-sidebar"; +import { FilesHeader, type Crumb, type SortDir, type SortKey, type ViewMode } from "@/components/files/files-header"; +import { FileGridView, FileListView, type FileItemHandlers } from "@/components/files/file-views"; +import { FileDetailsPanel } from "@/components/files/file-details-panel"; +import { INTERNAL_DRAG_TYPE, anchorEvent, isInternalDrag, readDraggedNames } from "@/components/files/file-item-parts"; import { ResizeHandle } from "@/components/layout/resize-handle"; -import { Avatar } from "@/components/ui/avatar"; import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils"; -import type { FileResource } from "@/stores/file-store"; +import { useFileStore, isSharedFilesPage, sharedFilePages, type FileResource } from "@/stores/file-store"; +import { toast } from "@/stores/toast-store"; import { ShareCollectionDialog } from "@/components/settings/share-collection-dialog"; import type { IJMAPClient } from "@/lib/jmap/client-interface"; import type { FileNodeRights } from "@/lib/jmap/types"; -import { getEffectiveTimeZone } from "@/lib/timezone"; - -type SortKey = "name" | "size" | "modified"; -type SortDir = "asc" | "desc"; -type ViewMode = "list" | "grid"; interface ClipboardState { mode: "cut" | "copy"; @@ -69,39 +65,39 @@ interface FileBrowserProps { onDownload: (name: string) => Promise; onBatchDownload: (names: string[]) => Promise; onRefresh: () => Promise; - onSelectResource: (name: string | null) => void; onToggleSelect: (name: string) => void; - onSelectAll: () => void; onClearSelection: () => void; onSetSelection: (names: Set) => void; onCut: (names: string[]) => void; onCopy: (names: string[]) => void; onPaste: () => Promise; - onMoveToFolder: (names: string[], targetFolder: string) => Promise; - onMoveToParent: (names: string[]) => Promise; + /** Move listed items into a folder by id (null = the root). */ + onMoveTo: (names: string[], targetId: string | null) => Promise; onPreviewImage: (name: string) => void; onPreviewFile: (name: string) => void; /** WOPI document editing (#425): whether a file can open in the document editor. */ isOfficeEditable?: (name: string) => boolean; onEditFile?: (name: string) => void; - onShowDetails: (name: string) => void; onCreateTextFile: (name: string) => Promise; onDuplicate: (name: string) => Promise; getImageUrl: (name: string) => Promise; - listPath: (path: string) => Promise; - listByParentId: (parentId: string | null) => Promise; favorites: string[]; recentFiles: { name: string; id: string; timestamp: number }[]; onToggleFavorite: (path: string) => void; - showDetails: boolean; - onToggleDetails: () => void; - detailResource: FileResource | null; + /** Open a recently used file wherever it now lives. */ + onOpenRecent: (id: string) => void; + /** Sidebar actions on items that need not be in the open folder. */ + onRenameNode: (id: string, newName: string) => Promise; + onDeleteNode: (id: string, name: string) => Promise; + onDownloadNode: (id: string) => Promise; + onRevealNode: (id: string) => Promise; + onRemoveRecent: (id: string) => void; /** Pro shell only: all connected accounts surfaced as top-level folders at the root. */ accountFolders?: AccountFolderEntry[]; onSelectAccount?: (accountId: string) => void; - /** Pro shell only: when true, the root is a pure account picker - hide the file toolbar and don't render a regular listing. */ + /** Pro shell only: when true, the root is a pure account picker - hide the file tools and don't render a regular listing. */ accountPickerMode?: boolean; - /** Pro shell only: label of the currently-attached account, shown as a breadcrumb segment after Home. */ + /** Pro shell only: label of the currently-attached account, shown as a breadcrumb segment after the root. */ accountLabel?: string | null; /** JMAP client for the browsing account, used by the share dialog to list principals. */ client?: IJMAPClient | null; @@ -113,248 +109,18 @@ interface FileBrowserProps { onShare?: (id: string, principalId: string, rights: FileNodeRights | null) => Promise; } -const IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "gif", "svg", "webp", "bmp", "ico", "avif"]); - -function isImageFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return IMAGE_EXTENSIONS.has(ext); -} - -const TEXT_EXTENSIONS = new Set([ - "txt", "md", "markdown", "json", "xml", "html", "htm", "css", "js", "ts", - "jsx", "tsx", "py", "rb", "java", "c", "cpp", "h", "hpp", "go", "rs", - "sh", "bash", "zsh", "yaml", "yml", "toml", "ini", "cfg", "conf", "env", - "log", "csv", "sql", "graphql", "vue", "svelte", "astro", "php", "pl", - "swift", "kt", "scala", "r", "lua", "vim", -]); - -function isTextFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - const baseName = name.toLowerCase(); - return TEXT_EXTENSIONS.has(ext) || ["dockerfile", "makefile", "readme", "license", "changelog"].includes(baseName); -} - -const AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "flac", "aac", "m4a", "wma", "opus"]); -function isAudioFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return AUDIO_EXTENSIONS.has(ext); -} - -const VIDEO_EXTENSIONS = new Set(["mp4", "webm", "ogv", "mov", "avi", "mkv", "m4v"]); -function isVideoFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return VIDEO_EXTENSIONS.has(ext); -} - -const PDF_EXTENSIONS = new Set(["pdf"]); -function isPdfFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return PDF_EXTENSIONS.has(ext); -} - -const VECTOR_EXTENSIONS = new Set(["svg", "ai", "eps", "ps", "sketch", "fig", "xd", "gvdesign"]); -function isVectorFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return VECTOR_EXTENSIONS.has(ext); -} - -const THREE_D_EXTENSIONS = new Set([ - "obj", "fbx", "gltf", "glb", "stl", "3mf", "step", "stp", "iges", "igs", - "blend", "3ds", "dae", "usdz", "usd", "usda", "usdc", "ply", "wrl", - "c4d", "max", "ma", "mb", "dwg", "dxf", -]); -function is3DFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return THREE_D_EXTENSIONS.has(ext); -} - -const EXECUTABLE_EXTENSIONS = new Set([ - "exe", "msi", "dmg", "app", "appimage", "deb", "rpm", "snap", "flatpak", - "bat", "cmd", "com", "scr", "ps1", "apk", "ipa", "jar", "run", -]); -function isExecutableFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return EXECUTABLE_EXTENSIONS.has(ext); -} - -const ARCHIVE_EXTENSIONS = new Set([ - "zip", "rar", "7z", "tar", "gz", "bz2", "xz", "zst", "lz", "lzma", - "tgz", "tbz2", "txz", "cab", "iso", "img", -]); -function isArchiveFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return ARCHIVE_EXTENSIONS.has(ext); -} - -const SPREADSHEET_EXTENSIONS = new Set(["xls", "xlsx", "ods", "numbers", "tsv"]); -function isSpreadsheetFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return SPREADSHEET_EXTENSIONS.has(ext); -} - -const PRESENTATION_EXTENSIONS = new Set(["ppt", "pptx", "odp", "key"]); -function isPresentationFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return PRESENTATION_EXTENSIONS.has(ext); -} - -const WORD_DOCUMENT_EXTENSIONS = new Set(["doc", "docx", "odt", "rtf"]); -function isWordDocumentFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return WORD_DOCUMENT_EXTENSIONS.has(ext); -} - -const FONT_EXTENSIONS = new Set(["ttf", "otf", "woff", "woff2", "eot"]); -function isFontFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return FONT_EXTENSIONS.has(ext); -} - -const DATABASE_EXTENSIONS = new Set(["db", "sqlite", "sqlite3", "mdb", "accdb"]); -function isDatabaseFile(name: string): boolean { - const ext = name.split(".").pop()?.toLowerCase() || ""; - return DATABASE_EXTENSIONS.has(ext); -} - function isPreviewable(name: string): boolean { return isImageFile(name) || isTextFile(name) || isPdfFile(name) || isAudioFile(name) || isVideoFile(name); } -function getFileIconByName(name: string, size: "sm" | "lg") { - const cls = size === "sm" ? "w-5 h-5" : "w-10 h-10"; - if (isVectorFile(name)) return ; - if (is3DFile(name)) return ; - if (isImageFile(name)) return ; - if (isAudioFile(name)) return ; - if (isVideoFile(name)) return ; - if (isArchiveFile(name)) return ; - if (isExecutableFile(name)) return ; - if (isSpreadsheetFile(name)) return ; - if (isPresentationFile(name)) return ; - if (isWordDocumentFile(name)) return ; - if (isFontFile(name)) return ; - if (isDatabaseFile(name)) return ; - if (isPdfFile(name)) return ; - if (isTextFile(name)) return ; - return ; -} +type MenuData = { kind: "item"; resource: FileResource } | { kind: "empty" } | { kind: "new" }; -// A symlink's icon, whatever its name suggests: it has no content to open. -function SymlinkIcon({ className, label }: { className: string; label: string }) { - return ( - - {label} - - ); -} +const SIDEBAR_DEFAULT_WIDTH = 256; -function getFileIcon(resource: FileResource, symlinkLabel: string) { - if (resource.isDirectory) { - return ; - } - if (resource.isSymlink) return ; - return getFileIconByName(resource.name, "sm"); -} - -function getGridIcon(resource: FileResource, symlinkLabel: string) { - if (resource.isDirectory) { - return ; - } - if (resource.isSymlink) return ; - return getFileIconByName(resource.name, "lg"); -} - -// Small inline indicator: a node shared out by the user (shareWith has entries) -// or a node shared *with* the user by another principal (isShared). -function ShareBadge({ resource, t }: { resource: FileResource; t: (key: string) => string }) { - const sharedOut = !!resource.shareWith && Object.keys(resource.shareWith).length > 0; - if (resource.isShared) { - return ( - - {t("shared_with_me")} - - ); - } - if (sharedOut) { - return ( - - {t("shared")} - - ); - } - return null; -} - -function Thumbnail({ name, getImageUrl: fetchUrl, size = "sm" }: { - name: string; - getImageUrl: (n: string) => Promise; - size?: "sm" | "lg"; -}) { - const [src, setSrc] = useState(null); - const [failed, setFailed] = useState(false); - - useEffect(() => { - let cancelled = false; - fetchUrl(name).then(url => { if (!cancelled) setSrc(url); }).catch(() => { if (!cancelled) setFailed(true); }); - return () => { cancelled = true; }; - }, [name, fetchUrl]); - - if (failed || !src) { - return size === "sm" - ? - : ; - } - - const cls = size === "sm" - ? "w-5 h-5 rounded object-cover" - : "w-10 h-10 rounded object-cover"; - - return {name}; -} - -function formatDate(dateString: string): string { - if (!dateString) return ""; - try { - return new Date(dateString).toLocaleDateString(undefined, { - timeZone: getEffectiveTimeZone(), - year: "numeric", - month: "short", - day: "numeric", - hour: "2-digit", - minute: "2-digit", - }); - } catch { - return dateString; - } -} - -function SkeletonRow() { - return ( - - -
-
-
-
-
- - -
- - -
- - -
- - - ); +function isTypingTarget(target: EventTarget | null): boolean { + const el = target as HTMLElement | null; + if (!el) return false; + return el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable; } export function FileBrowser({ @@ -364,6 +130,7 @@ export function FileBrowser({ error, selectedResources, uploadProgress, + clipboard, onNavigate, onCreateFolder, onUploadFiles, @@ -375,33 +142,29 @@ export function FileBrowser({ onDownload, onBatchDownload, onRefresh, - onSelectResource, onToggleSelect, - onSelectAll, onClearSelection, onSetSelection, onCut, onCopy, onPaste, - onMoveToFolder, - onMoveToParent, + onMoveTo, onPreviewImage, onPreviewFile, isOfficeEditable, onEditFile, - onShowDetails, onCreateTextFile, onDuplicate, getImageUrl, - listPath, - listByParentId, favorites, recentFiles, onToggleFavorite, - showDetails, - onToggleDetails, - detailResource, - clipboard, + onOpenRecent, + onRenameNode, + onDeleteNode, + onDownloadNode, + onRevealNode, + onRemoveRecent, accountFolders, onSelectAccount, accountPickerMode, @@ -423,13 +186,139 @@ export function FileBrowser({ case "reserved": return t("name_reserved"); } }, [fileNameRules, t]); + + // ---- Store-derived state --------------------------------------------------- + const storeClient = useFileStore((s) => s.client); + const sharedRoots = useFileStore((s) => s.sharedRoots); + const loadSharedRoots = useFileStore((s) => s.loadSharedRoots); + const allFolders = useFileStore((s) => s.allFolders); + const hasListed = useFileStore((s) => s.hasListed); + const currentParentId = useFileStore((s) => s.currentParentId); + const pathStack = useFileStore((s) => s.pathStack); + useEffect(() => { + if (storeClient) void loadSharedRoots(); + }, [storeClient, loadSharedRoots]); + + // ---- Settings -------------------------------------------------------------- + const [settings, setSettings] = useState(loadFilesSettings); + const [sortKey, setSortKey] = useState(() => settings.defaultSortKey); + const [sortDir, setSortDir] = useState(() => settings.defaultSortDir); + useEffect(() => { + const reload = () => { + const next = loadFilesSettings(); + setSettings(next); + setSortKey(next.defaultSortKey); + setSortDir(next.defaultSortDir); + }; + const handleStorage = (e: StorageEvent) => { if (e.key === "files-settings") reload(); }; + // StorageEvent fires cross-tab, the custom event same-tab + window.addEventListener("storage", handleStorage); + window.addEventListener("files-settings-changed", reload); + return () => { + window.removeEventListener("storage", handleStorage); + window.removeEventListener("files-settings-changed", reload); + }; + }, []); + const viewMode: ViewMode = settings.defaultViewMode; + const handleViewModeChange = useCallback((mode: ViewMode) => { + // The toggle and Settings > Files edit the same preference. + const next = { ...loadFilesSettings(), defaultViewMode: mode }; + setSettings(next); + saveFilesSettings(next); + }, []); + const iconOptions = useMemo(() => ({ + showIcons: settings.showIcons, + coloredIcons: settings.coloredIcons, + showThumbnails: settings.showThumbnails, + }), [settings.showIcons, settings.coloredIcons, settings.showThumbnails]); + + // ---- Layout ---------------------------------------------------------------- + const isDesktop = useIsDesktop(); + const isNarrow = !isDesktop; + const isMobile = useIsMobile(); + const touch = useMediaQuery("(pointer: coarse)") && isMobile; + const [narrowSidebarOpen, setNarrowSidebarOpen] = useState(false); + useEffect(() => { if (!isNarrow) setNarrowSidebarOpen(false); }, [isNarrow]); + useEffect(() => { setNarrowSidebarOpen(false); }, [currentPath]); + const [sidebarWidth, setSidebarWidth] = useState(() => { + if (typeof window !== "undefined") { + const saved = Number(localStorage.getItem("files-sidebar-width")); + if (saved) return Math.max(180, Math.min(400, saved)); + } + return SIDEBAR_DEFAULT_WIDTH; + }); + const [isResizing, setIsResizing] = useState(false); + const dragStartWidth = useRef(SIDEBAR_DEFAULT_WIDTH); + const [showDetails, setShowDetails] = useState(() => { + try { return localStorage.getItem("files-show-details") === "1"; } catch { return false; } + }); + const toggleDetails = useCallback((open?: boolean) => { + setShowDetails((v) => { + const next = open ?? !v; + try { localStorage.setItem("files-show-details", next ? "1" : "0"); } catch { /* ignore */ } + return next; + }); + }, []); + + // ---- Dialogs and transient UI --------------------------------------------- const [showNewFolder, setShowNewFolder] = useState(false); + const [showNewTextFile, setShowNewTextFile] = useState(false); const [renameTarget, setRenameTarget] = useState(null); + const [renameFolder, setRenameFolder] = useState(null); const [shareTargetId, setShareTargetId] = useState(null); - const [isDraggingOver, setIsDraggingOver] = useState(false); - // The share dialog is bound to a node id (not name) so its shareWith stays - // live after a share refresh re-derives the resource list. - const shareTarget = shareTargetId ? resources.find(r => r.id === shareTargetId) ?? null : null; + const [searchQuery, setSearchQuery] = useState(""); + const [focusedName, setFocusedName] = useState(null); + // The cursor outline follows a click or the arrow keys, but goes away once + // the clicked item is deselected; while the keyboard is in use it stays. + const [keyboardNav, setKeyboardNav] = useState(false); + const [dropTarget, setDropTarget] = useState(null); + const [isDraggingFiles, setIsDraggingFiles] = useState(false); + const dragDepth = useRef(0); + const anchorName = useRef(null); + const menu = useContextMenu(); + const fileInputRef = useRef(null); + const folderInputRef = useRef(null); + const searchInputRef = useRef(null); + const scrollAreaRef = useRef(null); + + useEffect(() => { + setSearchQuery(""); + setFocusedName(null); + anchorName.current = null; + if (scrollAreaRef.current) scrollAreaRef.current.scrollTop = 0; + }, [currentPath]); + + // ---- Upload progress, shown as a toast like every other notice ---------------- + const uploadToastId = useRef(null); + const cancelUploadRef = useRef(onCancelUpload); + cancelUploadRef.current = onCancelUpload; + useEffect(() => { + if (!uploadProgress) { + if (uploadToastId.current) toast.dismiss(uploadToastId.current); + uploadToastId.current = null; + return; + } + const progress = uploadProgress.total > 0 ? uploadProgress.loaded / uploadProgress.total : null; + const title = uploadProgress.totalFiles > 1 + ? t("uploading_count", { current: uploadProgress.current, total: uploadProgress.totalFiles }) + : t("uploading"); + const message = progress === null ? uploadProgress.name : `${uploadProgress.name} · ${Math.round(progress * 100)}%`; + if (uploadToastId.current) { + // Closing the toast only hides it; the upload carries on. + toast.update(uploadToastId.current, { title, message, progress }); + } else { + uploadToastId.current = toast.progress(title, { + message, + progress, + action: { label: t("cancel"), onClick: () => cancelUploadRef.current() }, + }); + } + }, [uploadProgress, t]); + useEffect(() => () => { + if (uploadToastId.current) toast.dismiss(uploadToastId.current); + }, []); + + // ---- Sharing --------------------------------------------------------------- // A node is shareable when the server supports JMAP Sharing, the viewer owns // it (not a shared-with-me node), and holds the mayShare right (owned nodes // report full rights; treat missing myRights as allowed). @@ -439,120 +328,36 @@ export function FileBrowser({ // Files have content to preview, open, download or duplicate. Folders and // symlinks don't: a symlink row only supports rename, move and delete. const hasContent = useCallback((name: string): boolean => { - const r = resources.find(res => res.name === name); + const r = resources.find((res) => res.name === name); return !!r && !r.isDirectory && !r.isSymlink; }, [resources]); - const symlinkLabel = t("symlink"); - const [contextMenu, setContextMenu] = useState<{ x: number; y: number; name: string } | null>(null); - const [emptyContextMenu, setEmptyContextMenu] = useState<{ x: number; y: number } | null>(null); - const [showNewTextFile, setShowNewTextFile] = useState(false); - const [isUploading, setIsUploading] = useState(false); - const [searchQuery, setSearchQuery] = useState(""); - const [showSearch, setShowSearch] = useState(false); - const [sortKey, setSortKey] = useState("name"); - const [sortDir, setSortDir] = useState("asc"); - const [viewMode, setViewMode] = useState(() => { - if (typeof window !== "undefined") { - return (localStorage.getItem("files-view-mode") as ViewMode) || "list"; - } - return "list"; - }); - const [showThumbnails, setShowThumbnails] = useState(() => loadFilesSettings().showThumbnails); - const [folderLayout, setFolderLayout] = useState(() => loadFilesSettings().folderLayout); - const [sidebarWidth, setSidebarWidth] = useState(() => { - if (typeof window !== "undefined") { - const saved = localStorage.getItem("files-sidebar-width"); - if (saved) return Math.max(180, Math.min(400, Number(saved))); - } - return 256; - }); - const [isResizing, setIsResizing] = useState(false); - const dragStartWidth = useRef(256); - const [dragTarget, setDragTarget] = useState(null); - // Pane-aware: in a Pro split pane (or a narrow window) the folder tree - // sidebar collapses into a burger-toggled overlay so it doesn't crowd the - // file list. - const isDesktopPane = useIsDesktop(); - const isNarrow = !isDesktopPane; - const [narrowSidebarOpen, setNarrowSidebarOpen] = useState(false); - useEffect(() => { if (!isNarrow) setNarrowSidebarOpen(false); }, [isNarrow]); + // Looked up by id so the dialog shows the shares as they change. A folder + // shared from the tree is usually not in the listing, so fall back to it. + const shareTarget = shareTargetId + ? resources.find((r) => r.id === shareTargetId) ?? allFolders.find((r) => r.id === shareTargetId) ?? null + : null; - // Sync showThumbnails and folderLayout when settings change - useEffect(() => { - const reloadSettings = () => { - const s = loadFilesSettings(); - setShowThumbnails(s.showThumbnails); - setFolderLayout(s.folderLayout); - }; - const handleStorage = (e: StorageEvent) => { - if (e.key === "files-settings") reloadSettings(); - }; - // StorageEvent fires cross-tab, custom event fires same-tab - window.addEventListener("storage", handleStorage); - window.addEventListener("files-settings-changed", reloadSettings); - return () => { - window.removeEventListener("storage", handleStorage); - window.removeEventListener("files-settings-changed", reloadSettings); - }; - }, []); - const [breadcrumbDropdown, setBreadcrumbDropdown] = useState<{ - path: string; - folders: FileResource[]; - x: number; - y: number; - } | null>(null); - const [marquee, setMarquee] = useState<{ - startX: number; - startY: number; - currentX: number; - currentY: number; - } | null>(null); - const marqueeRef = useRef<{ - additive: boolean; - initialSelection: Set; - } | null>(null); - const fileInputRef = useRef(null); - const folderInputRef = useRef(null); - const searchInputRef = useRef(null); - const containerRef = useRef(null); - const scrollAreaRef = useRef(null); + // Whether the user may add items to the folder on screen. Nothing can be + // put on a page listing files shared on their own. + const currentFolder = currentParentId ? allFolders.find((f) => f.id === currentParentId) : null; + const canCreate = !accountPickerMode && !isSharedFilesPage(currentParentId) + && (currentFolder?.myRights?.mayAddChildren ?? true); - // Reset search when navigating - useEffect(() => { - setSearchQuery(""); - }, [currentPath]); - - // Focus search input when shown - useEffect(() => { - if (showSearch) searchInputRef.current?.focus(); - }, [showSearch]); - - // Persist view mode - const handleViewModeChange = useCallback((mode: ViewMode) => { - setViewMode(mode); - localStorage.setItem("files-view-mode", mode); - }, []); - - // Filter and sort resources + // ---- Listing --------------------------------------------------------------- const displayResources = useMemo(() => { - let filtered = resources; - // In sidebar mode, folders are shown in the sidebar tree - hide them from the main list - if (folderLayout === "sidebar") { - filtered = filtered.filter(r => !r.isDirectory); - } + let list = resources; + if (!settings.showHiddenFiles) list = list.filter((r) => !r.name.startsWith(".")); if (searchQuery) { const q = searchQuery.toLowerCase(); - filtered = filtered.filter(r => r.name.toLowerCase().includes(q)); + list = list.filter((r) => r.name.toLowerCase().includes(q)); } - - const sorted = [...filtered].sort((a, b) => { - // Directories always first + return [...list].sort((a, b) => { + // Folders always first if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1; - let cmp = 0; switch (sortKey) { case "name": - cmp = a.name.localeCompare(b.name); + cmp = a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }); break; case "size": cmp = a.contentLength - b.contentLength; @@ -561,1480 +366,832 @@ export function FileBrowser({ cmp = new Date(a.lastModified || 0).getTime() - new Date(b.lastModified || 0).getTime(); break; } + if (cmp === 0) cmp = a.name.localeCompare(b.name); return sortDir === "asc" ? cmp : -cmp; }); - return sorted; - }, [resources, searchQuery, sortKey, sortDir, folderLayout]); + }, [resources, settings.showHiddenFiles, searchQuery, sortKey, sortDir]); - // Build breadcrumb segments. In Pro mode an account is mounted "between" - // Home and the account's filesystem - surfaced as a non-clickable label - // (clicking the actual account again would be a no-op; Home detaches it). - const breadcrumbs: { name: string; path: string; isAccount?: boolean }[] = currentPath === '/' - ? [{ name: t("breadcrumb_root"), path: '/' }] - : [ - { name: t("breadcrumb_root"), path: '/' }, - ...currentPath.split('/').filter(Boolean).map((segment, i, arr) => ({ - name: segment, - path: '/' + arr.slice(0, i + 1).join('/'), - })), - ]; - if (accountLabel) { - breadcrumbs.splice(1, 0, { name: accountLabel, path: '', isAccount: true }); - } + // Folders other principals shared with the user, listed at the root next to + // the user's own (#1181). + const sharedAtRoot = useMemo(() => { + if (currentPath !== "/" || accountPickerMode) return []; + const q = searchQuery.toLowerCase(); + return sharedRoots.filter((r) => r.isDirectory && (!q || r.name.toLowerCase().includes(q))); + }, [currentPath, accountPickerMode, sharedRoots, searchQuery]); + // Files shared on their own are listed on one page per owner. + const sharedPagesAtRoot = useMemo(() => { + if (currentPath !== "/" || accountPickerMode) return []; + const q = searchQuery.toLowerCase(); + return sharedFilePages(sharedRoots) + .map((page) => ({ ...page, name: t("shared_files_from", { name: page.ownerName }) })) + .filter((page) => !q || page.name.toLowerCase().includes(q)); + }, [currentPath, accountPickerMode, sharedRoots, searchQuery, t]); - const handleNavigateUp = useCallback(() => { - if (currentPath === '/') return; - const segments = currentPath.split('/').filter(Boolean); - segments.pop(); - const parentPath = segments.length === 0 ? '/' : '/' + segments.join('/'); - // Pro shell: going up to root from a subfolder must land on the - // account's filesystem root, not detach back to the account picker. - // Home click (breadcrumb) still detaches. - if (parentPath === '/' && accountLabel) { - onNavigate('/', '__account_root__'); + const pathOf = useCallback((r: FileResource) => (currentPath === "/" ? `/${r.name}` : `${currentPath}/${r.name}`), [currentPath]); + const starredPaths = useMemo(() => new Set(favorites), [favorites]); + const cutNames = useMemo(() => new Set(clipboard?.mode === "cut" ? clipboard.names : []), [clipboard]); + const selectedList = useMemo(() => displayResources.filter((r) => selectedResources.has(r.name)), [displayResources, selectedResources]); + const singleSelected = selectedList.length === 1 ? selectedList[0] : null; + + // ---- Breadcrumbs ----------------------------------------------------------- + const crumbs: Crumb[] = useMemo(() => { + const segments = currentPath.split("/").filter(Boolean); + // Inside a folder someone shared with the user, the trail starts there. + const insideShared = !!pathStack[1]?.id?.includes(":"); + const list: Crumb[] = [{ id: null, name: insideShared ? t("shared_with_me") : t("my_files"), path: "/" }]; + segments.forEach((name, i) => { + list.push({ id: pathStack[i + 1]?.id ?? null, name, path: "/" + segments.slice(0, i + 1).join("/") }); + }); + return list; + }, [currentPath, pathStack, t]); + const folderName = crumbs[crumbs.length - 1].name; + + const navigateCrumb = useCallback((crumb: Crumb) => { + if (crumb.path === "/") { + // Pro shell: the root detaches the account and returns to the picker. + onNavigate("/"); return; } - onNavigate(parentPath); - }, [currentPath, onNavigate, accountLabel]); + if (crumb.id) onNavigate(crumb.path, crumb.id); + else onNavigate(crumb.path); + }, [onNavigate]); - const handleResourceClick = (resource: FileResource, e: React.MouseEvent) => { + const navigateUp = useCallback(() => { + if (crumbs.length < 2) return; + const parent = crumbs[crumbs.length - 2]; + // Pro shell: going up from a top folder lands on the account's root, not + // back on the account picker. + if (parent.path === "/" && accountLabel) onNavigate("/", "__account_root__"); + else if (parent.path === "/") onNavigate("/", null); + else navigateCrumb(parent); + }, [crumbs, accountLabel, onNavigate, navigateCrumb]); + + // ---- Opening --------------------------------------------------------------- + const openResource = useCallback((resource: FileResource) => { + // A symlink has nothing to open (Stalwart 1.0). + if (resource.isSymlink) return; if (resource.isDirectory) { - // Ctrl/Cmd+click on directories also toggles selection - if (e.ctrlKey || e.metaKey) { - onToggleSelect(resource.name); - return; - } - const newPath = currentPath === '/' - ? `/${resource.name}` - : `${currentPath}/${resource.name}`; - onNavigate(newPath, resource.id); + onNavigate(pathOf(resource), resource.id); + } else if (isOfficeEditable?.(resource.name) && onEditFile) { + onEditFile(resource.name); + } else if (isImageFile(resource.name)) { + onPreviewImage(resource.name); + } else if (isPreviewable(resource.name)) { + onPreviewFile(resource.name); } else { - if (e.ctrlKey || e.metaKey) { - onToggleSelect(resource.name); - } else if (e.shiftKey && resources.length > 0) { - // Shift+click range select - handleShiftSelect(resource.name); - } else { - onSelectResource(resource.name === [...selectedResources][0] && selectedResources.size === 1 ? null : resource.name); - } + void onDownload(resource.name); } - }; + }, [onNavigate, pathOf, isOfficeEditable, onEditFile, onPreviewImage, onPreviewFile, onDownload]); - const handleShiftSelect = (targetName: string) => { - const lastSelected = [...selectedResources].pop(); - if (!lastSelected) { - onToggleSelect(targetName); + const previewResource = useCallback((resource: FileResource) => { + if (isImageFile(resource.name)) onPreviewImage(resource.name); + else onPreviewFile(resource.name); + }, [onPreviewImage, onPreviewFile]); + + // ---- Selection ------------------------------------------------------------- + const selectRange = useCallback((from: string, to: string, additive: boolean) => { + const names = displayResources.map((r) => r.name); + const a = names.indexOf(from); + const b = names.indexOf(to); + if (a === -1 || b === -1) return; + const next = additive ? new Set(selectedResources) : new Set(); + for (let i = Math.min(a, b); i <= Math.max(a, b); i++) next.add(names[i]); + onSetSelection(next); + }, [displayResources, selectedResources, onSetSelection]); + + const handleSelectClick = useCallback((resource: FileResource, e: React.MouseEvent) => { + setFocusedName(resource.name); + setKeyboardNav(false); + if (e.shiftKey && anchorName.current) { + selectRange(anchorName.current, resource.name, e.ctrlKey || e.metaKey); return; } - const names = displayResources.map(r => r.name); - const startIdx = names.indexOf(lastSelected); - const endIdx = names.indexOf(targetName); - if (startIdx === -1 || endIdx === -1) return; - const from = Math.min(startIdx, endIdx); - const to = Math.max(startIdx, endIdx); - for (let i = from; i <= to; i++) { - if (!selectedResources.has(names[i])) { - onToggleSelect(names[i]); - } + anchorName.current = resource.name; + if (e.ctrlKey || e.metaKey) { + onToggleSelect(resource.name); + } else { + onSetSelection(new Set([resource.name])); } + }, [selectRange, onToggleSelect, onSetSelection]); + + const handleToggleSelect = useCallback((resource: FileResource) => { + anchorName.current = resource.name; + setFocusedName(resource.name); + setKeyboardNav(false); + onToggleSelect(resource.name); + }, [onToggleSelect]); + + const selectAllVisible = useCallback(() => { + onSetSelection(new Set(displayResources.map((r) => r.name))); + }, [displayResources, onSetSelection]); + + const allSelected = displayResources.length > 0 && selectedList.length === displayResources.length; + const someSelected = selectedList.length > 0; + + // ---- Deleting -------------------------------------------------------------- + const deleteNames = useCallback((names: string[]) => { + if (names.length === 1) void onDelete(names[0]); + else if (names.length > 1) void onBatchDelete(names); + }, [onDelete, onBatchDelete]); + + const downloadNames = useCallback((names: string[]) => { + const files = names.filter(hasContent); + if (files.length === 1) void onDownload(files[0]); + else if (files.length > 1) void onBatchDownload(files); + }, [hasContent, onDownload, onBatchDownload]); + + // ---- Drag and drop --------------------------------------------------------- + const moveNames = useCallback((names: string[], targetId: string | null) => { + void onMoveTo(names, targetId); + }, [onMoveTo]); + + const itemDragProps = useCallback((resource: FileResource) => ({ + draggable: !touch, + onDragStart: (e: React.DragEvent) => { + const names = selectedResources.has(resource.name) ? [...selectedResources] : [resource.name]; + e.dataTransfer.setData(INTERNAL_DRAG_TYPE, JSON.stringify(names)); + e.dataTransfer.effectAllowed = "move"; + }, + onDragOver: (e: React.DragEvent) => { + if (!resource.isDirectory || !isInternalDrag(e)) return; + e.preventDefault(); + e.stopPropagation(); + e.dataTransfer.dropEffect = "move"; + setDropTarget(resource.name); + }, + onDragLeave: () => setDropTarget((cur) => (cur === resource.name ? null : cur)), + onDrop: (e: React.DragEvent) => { + if (!resource.isDirectory || !isInternalDrag(e)) return; + e.preventDefault(); + e.stopPropagation(); + setDropTarget(null); + const names = readDraggedNames(e).filter((n) => n !== resource.name); + if (names.length > 0) moveNames(names, resource.id); + }, + }), [touch, selectedResources, moveNames]); + + const runUpload = useCallback(async (files: File[], asFolder: boolean) => { + if (files.length === 0) return; + if (asFolder) await onUploadFolder(files); + else await onUploadFiles(files); + }, [onUploadFiles, onUploadFolder]); + + const handleContentDragEnter = useCallback((e: React.DragEvent) => { + if (!e.dataTransfer.types.includes("Files") || !canCreate) return; + e.preventDefault(); + dragDepth.current += 1; + setIsDraggingFiles(true); + }, [canCreate]); + const handleContentDragOver = useCallback((e: React.DragEvent) => { + if (!e.dataTransfer.types.includes("Files") || !canCreate) return; + e.preventDefault(); + e.dataTransfer.dropEffect = "copy"; + }, [canCreate]); + const handleContentDragLeave = useCallback((e: React.DragEvent) => { + if (!e.dataTransfer.types.includes("Files")) return; + dragDepth.current = Math.max(0, dragDepth.current - 1); + if (dragDepth.current === 0) setIsDraggingFiles(false); + }, []); + const handleContentDrop = useCallback(async (e: React.DragEvent) => { + if (!e.dataTransfer.types.includes("Files") || !canCreate) return; + e.preventDefault(); + dragDepth.current = 0; + setIsDraggingFiles(false); + const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer); + await runUpload(files, hasDirectories); + }, [canCreate, runUpload]); + + const handleInputChange = (asFolder: boolean) => async (e: React.ChangeEvent) => { + const files = Array.from(e.target.files || []); + e.target.value = ""; + await runUpload(files, asFolder); }; - // Marquee (rubber-band) selection + // ---- Marquee (rubber-band) selection ---------------------------------------- + const [marquee, setMarquee] = useState<{ startX: number; startY: number; currentX: number; currentY: number } | null>(null); + const marqueeInfo = useRef<{ initialSelection: Set } | null>(null); + const handleMarqueeMouseDown = useCallback((e: React.MouseEvent) => { - if (e.button !== 0) return; + if (e.button !== 0 || touch) return; const target = e.target as HTMLElement; - if (target.closest('[data-resource]') || target.closest('input') || target.closest('button') || target.closest('thead')) return; - - const scrollArea = scrollAreaRef.current; - if (!scrollArea) return; - - const rect = scrollArea.getBoundingClientRect(); - const x = e.clientX - rect.left + scrollArea.scrollLeft; - const y = e.clientY - rect.top + scrollArea.scrollTop; - + if (target.closest("[data-resource], button, input, [role=columnheader], a")) return; + const area = scrollAreaRef.current; + if (!area) return; + const rect = area.getBoundingClientRect(); + const x = e.clientX - rect.left + area.scrollLeft; + const y = e.clientY - rect.top + area.scrollTop; const additive = e.ctrlKey || e.metaKey; - marqueeRef.current = { - additive, - initialSelection: additive ? new Set(selectedResources) : new Set(), - }; - + marqueeInfo.current = { initialSelection: additive ? new Set(selectedResources) : new Set() }; setMarquee({ startX: x, startY: y, currentX: x, currentY: y }); - - if (!additive) { - onClearSelection(); - } - + if (!additive) onClearSelection(); e.preventDefault(); - }, [selectedResources, onClearSelection]); + }, [touch, selectedResources, onClearSelection]); useEffect(() => { if (!marquee) return; - - const handleMouseMove = (e: MouseEvent) => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) return; - - const rect = scrollArea.getBoundingClientRect(); - const x = e.clientX - rect.left + scrollArea.scrollLeft; - const y = e.clientY - rect.top + scrollArea.scrollTop; - - setMarquee(prev => prev ? { ...prev, currentX: x, currentY: y } : null); - - // Calculate marquee rect - const info = marqueeRef.current; - if (!info) return; - + const handleMove = (e: MouseEvent) => { + const area = scrollAreaRef.current; + const info = marqueeInfo.current; + if (!area || !info) return; + const rect = area.getBoundingClientRect(); + const x = e.clientX - rect.left + area.scrollLeft; + const y = e.clientY - rect.top + area.scrollTop; + setMarquee((prev) => (prev ? { ...prev, currentX: x, currentY: y } : null)); const mx = Math.min(marquee.startX, x); const my = Math.min(marquee.startY, y); const mw = Math.abs(x - marquee.startX); const mh = Math.abs(y - marquee.startY); - - // Find intersecting items - const elements = scrollArea.querySelectorAll('[data-resource]'); - const containerRect = scrollArea.getBoundingClientRect(); - const newSelection = new Set(info.initialSelection); - - elements.forEach(el => { - const name = el.getAttribute('data-resource'); + if (mw < 4 && mh < 4) return; + const next = new Set(info.initialSelection); + area.querySelectorAll("[data-resource]").forEach((el) => { + const name = el.getAttribute("data-resource"); if (!name) return; - const elRect = el.getBoundingClientRect(); - const elX = elRect.left - containerRect.left + scrollArea.scrollLeft; - const elY = elRect.top - containerRect.top + scrollArea.scrollTop; - - if (mx < elX + elRect.width && mx + mw > elX && my < elY + elRect.height && my + mh > elY) { - newSelection.add(name); - } + const r = el.getBoundingClientRect(); + const ex = r.left - rect.left + area.scrollLeft; + const ey = r.top - rect.top + area.scrollTop; + if (mx < ex + r.width && mx + mw > ex && my < ey + r.height && my + mh > ey) next.add(name); }); - - onSetSelection(newSelection); + onSetSelection(next); }; - - const handleMouseUp = () => { + const handleUp = () => { setMarquee(null); - marqueeRef.current = null; + marqueeInfo.current = null; }; - - window.addEventListener('mousemove', handleMouseMove); - window.addEventListener('mouseup', handleMouseUp); + window.addEventListener("mousemove", handleMove); + window.addEventListener("mouseup", handleUp); return () => { - window.removeEventListener('mousemove', handleMouseMove); - window.removeEventListener('mouseup', handleMouseUp); + window.removeEventListener("mousemove", handleMove); + window.removeEventListener("mouseup", handleUp); }; }, [marquee, onSetSelection]); - const handleResourceDoubleClick = (resource: FileResource) => { - if (resource.isSymlink) return; - if (resource.isDirectory) { - const newPath = currentPath === '/' - ? `/${resource.name}` - : `${currentPath}/${resource.name}`; - onNavigate(newPath, resource.id); - } else if (isOfficeEditable?.(resource.name) && onEditFile) { - onEditFile(resource.name); - } else if (isPreviewable(resource.name)) { - if (isImageFile(resource.name)) { - onPreviewImage(resource.name); - } else { - onPreviewFile(resource.name); - } + // ---- Keyboard ---------------------------------------------------------------- + const moveFocus = useCallback((delta: number, extend: boolean) => { + const names = displayResources.map((r) => r.name); + if (names.length === 0) return; + const current = focusedName ? names.indexOf(focusedName) : -1; + const base = current === -1 ? (delta > 0 ? -1 : names.length) : current; + const nextIndex = Math.max(0, Math.min(names.length - 1, base + delta)); + const name = names[nextIndex]; + setFocusedName(name); + setKeyboardNav(true); + if (extend && anchorName.current) { + selectRange(anchorName.current, name, false); } else { - onDownload(resource.name); + anchorName.current = name; + onSetSelection(new Set([name])); } - }; + scrollAreaRef.current?.querySelector(`[data-resource="${CSS.escape(name)}"]`)?.scrollIntoView?.({ block: "nearest" }); + }, [displayResources, focusedName, selectRange, onSetSelection]); - const handleDragOver = useCallback((e: React.DragEvent) => { - e.preventDefault(); - e.stopPropagation(); - // Only show upload overlay for external file drags, not internal resource drags - if (e.dataTransfer.types.includes("Files")) { - setIsDraggingOver(true); - } - }, []); + // Columns in the grid's file section, for Up/Down. + const gridColumns = useCallback((): number => { + const area = scrollAreaRef.current; + if (!area || !focusedName) return 1; + const el = area.querySelector(`[data-resource="${CSS.escape(focusedName)}"]`); + const row = el?.parentElement; + if (!row) return 1; + const tops = Array.from(row.children).map((c) => (c as HTMLElement).offsetTop); + return Math.max(1, tops.filter((top) => top === tops[0]).length); + }, [focusedName]); - const handleDragLeave = useCallback((e: React.DragEvent) => { - e.preventDefault(); - e.stopPropagation(); - setIsDraggingOver(false); - }, []); - - const handleDrop = useCallback(async (e: React.DragEvent) => { - e.preventDefault(); - e.stopPropagation(); - setIsDraggingOver(false); - - setIsUploading(true); - try { - const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer); - if (files.length > 0) { - if (hasDirectories) { - await onUploadFolder(files); - } else { - await onUploadFiles(files); - } - } - } finally { - setIsUploading(false); - } - }, [onUploadFiles, onUploadFolder]); - - const handleFileInputChange = async (e: React.ChangeEvent) => { - const files = Array.from(e.target.files || []); - if (files.length > 0) { - setIsUploading(true); - try { - await onUploadFiles(files); - } finally { - setIsUploading(false); - } - } - if (fileInputRef.current) { - fileInputRef.current.value = ''; - } - }; - - const handleFolderInputChange = async (e: React.ChangeEvent) => { - const files = Array.from(e.target.files || []); - if (files.length > 0) { - setIsUploading(true); - try { - await onUploadFolder(files); - } finally { - setIsUploading(false); - } - } - if (folderInputRef.current) { - folderInputRef.current.value = ''; - } - }; - - const contextMenuRef = useRef(null); - - const handleContextMenu = (e: React.MouseEvent, name: string) => { - e.preventDefault(); - setContextMenu({ x: e.clientX, y: e.clientY, name }); - }; - - // Adjust context menu position to stay within viewport - useEffect(() => { - if (contextMenu && contextMenuRef.current) { - const menu = contextMenuRef.current; - const rect = menu.getBoundingClientRect(); - let { x, y } = contextMenu; - let adjusted = false; - - if (x + rect.width > window.innerWidth) { - x = window.innerWidth - rect.width - 8; - adjusted = true; - } - if (y + rect.height > window.innerHeight) { - y = window.innerHeight - rect.height - 8; - adjusted = true; - } - - if (adjusted) { - setContextMenu({ ...contextMenu, x, y }); - } - } - }, [contextMenu]); - - const handleContainerClick = () => { - if (contextMenu) setContextMenu(null); - if (emptyContextMenu) setEmptyContextMenu(null); - if (breadcrumbDropdown) setBreadcrumbDropdown(null); - }; - - const handleBreadcrumbRightClick = async (e: React.MouseEvent, crumbPath: string) => { - e.preventDefault(); - e.stopPropagation(); - const parentPath = crumbPath === '/' ? '/' : '/' + crumbPath.split('/').filter(Boolean).slice(0, -1).join('/') || '/'; - try { - const items = await listPath(parentPath === '/' ? '/' : parentPath); - const folders = items.filter(r => r.isDirectory); - setBreadcrumbDropdown({ path: parentPath, folders, x: e.clientX, y: e.clientY }); - } catch { - // ignore - } - }; - - const handleSortClick = (key: SortKey) => { - if (sortKey === key) { - setSortDir(d => d === "asc" ? "desc" : "asc"); - } else { - setSortKey(key); - setSortDir("asc"); - } - }; - - const SortIndicator = ({ column }: { column: SortKey }) => { - if (sortKey !== column) return null; - return sortDir === "asc" - ? - : ; - }; - - // Keyboard shortcuts useEffect(() => { const handler = (e: KeyboardEvent) => { - // Don't capture when typing in inputs or dialogs - const tag = (e.target as HTMLElement)?.tagName; - if (tag === 'INPUT' || tag === 'TEXTAREA') return; - if (showNewFolder || renameTarget) return; + if (isTypingTarget(e.target)) return; + if (showNewFolder || showNewTextFile || renameTarget || renameFolder || shareTargetId) return; + // A preview, editor or confirmation is open on top of the list. + if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return; + if (accountPickerMode) return; + const mod = e.ctrlKey || e.metaKey; + const selected = selectedList.map((r) => r.name); - // Ctrl+F / Cmd+F: toggle search - if ((e.ctrlKey || e.metaKey) && e.key === 'f') { + if (mod && e.key.toLowerCase() === "f") { e.preventDefault(); - setShowSearch(v => !v); + searchInputRef.current?.focus(); return; } - - // Ctrl+A / Cmd+A: select all - if ((e.ctrlKey || e.metaKey) && e.key === 'a') { + if (mod && e.key.toLowerCase() === "a") { e.preventDefault(); - onSelectAll(); + selectAllVisible(); return; } - - // Ctrl+C / Cmd+C: copy selected - if ((e.ctrlKey || e.metaKey) && e.key === 'c') { - if (selectedResources.size > 0) { - e.preventDefault(); - onCopy([...selectedResources]); - } + if (mod && e.key.toLowerCase() === "c" && selected.length > 0) { + if (window.getSelection()?.toString()) return; + e.preventDefault(); + onCopy(selected); return; } - - // Ctrl+X / Cmd+X: cut selected - if ((e.ctrlKey || e.metaKey) && e.key === 'x') { - if (selectedResources.size > 0) { - e.preventDefault(); - onCut([...selectedResources]); - } + if (mod && e.key.toLowerCase() === "x" && selected.length > 0) { + e.preventDefault(); + onCut(selected); return; } - - // Ctrl+V / Cmd+V: paste - if ((e.ctrlKey || e.metaKey) && e.key === 'v') { - if (clipboard) { - e.preventDefault(); - onPaste(); - } + if (mod && e.key.toLowerCase() === "v" && clipboard) { + e.preventDefault(); + void onPaste(); return; } - - // Escape: clear selection, close search - if (e.key === 'Escape') { - if (showSearch) { setShowSearch(false); setSearchQuery(""); } - else if (selectedResources.size > 0) onClearSelection(); + if (e.key === "Escape") { + if (searchQuery) setSearchQuery(""); + else if (selected.length > 0) onClearSelection(); return; } - - // Delete: delete selected - if (e.key === 'Delete') { - if (selectedResources.size === 1) { - onDelete([...selectedResources][0]); - } else if (selectedResources.size > 1) { - onBatchDelete([...selectedResources]); - } + if (e.key === "Delete" && selected.length > 0) { + e.preventDefault(); + deleteNames(selected); return; } - - // F2: rename selected (single) - if (e.key === 'F2' && selectedResources.size === 1) { - setRenameTarget([...selectedResources][0]); + if (e.key === "F2" && singleSelected) { + e.preventDefault(); + setRenameTarget(singleSelected.name); return; } - - // Enter: open selected directory or download selected file - if (e.key === 'Enter' && selectedResources.size === 1) { - const name = [...selectedResources][0]; - const resource = resources.find(r => r.name === name); - if (resource?.isDirectory) { - const newPath = currentPath === '/' - ? `/${resource.name}` - : `${currentPath}/${resource.name}`; - onNavigate(newPath, resource.id); - } else if (resource && !resource.isSymlink) { - onDownload(resource.name); - } + if (e.key === "Enter" && singleSelected) { + e.preventDefault(); + openResource(singleSelected); return; } - - // Backspace: navigate up - if (e.key === 'Backspace' && currentPath !== '/') { - handleNavigateUp(); + if (e.key === " " && focusedName) { + e.preventDefault(); + onToggleSelect(focusedName); return; } + if ((e.key === "Backspace" || (e.altKey && e.key === "ArrowUp")) && currentPath !== "/") { + e.preventDefault(); + navigateUp(); + return; + } + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + const step = viewMode === "grid" ? gridColumns() : 1; + moveFocus(e.key === "ArrowDown" ? step : -step, e.shiftKey); + return; + } + if (viewMode === "grid" && (e.key === "ArrowRight" || e.key === "ArrowLeft")) { + e.preventDefault(); + const rtl = document.dir === "rtl"; + moveFocus((e.key === "ArrowRight") !== rtl ? 1 : -1, e.shiftKey); + return; + } + if (e.key === "Home" || e.key === "End") { + e.preventDefault(); + moveFocus(e.key === "Home" ? -Infinity : Infinity, e.shiftKey); + } }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }, [ + showNewFolder, showNewTextFile, renameTarget, renameFolder, shareTargetId, accountPickerMode, selectedList, singleSelected, + selectAllVisible, onCopy, onCut, onPaste, clipboard, searchQuery, onClearSelection, deleteNames, openResource, + focusedName, onToggleSelect, currentPath, navigateUp, viewMode, gridColumns, moveFocus, + ]); - window.addEventListener('keydown', handler); - return () => window.removeEventListener('keydown', handler); - }, [selectedResources, resources, currentPath, showSearch, showNewFolder, renameTarget, onDelete, onBatchDelete, onSelectAll, onClearSelection, onNavigate, onDownload, onCut, onCopy, onPaste, clipboard, handleNavigateUp]); + // ---- Context menu ---------------------------------------------------------- + const openMenu = menu.openContextMenu; + const openItemMenu = useCallback((e: React.MouseEvent, resource: FileResource) => { + // Acting on an item outside the selection makes it the selection, like a + // desktop file manager. + if (!selectedResources.has(resource.name)) { + onSetSelection(new Set([resource.name])); + anchorName.current = resource.name; + } + setFocusedName(resource.name); + setKeyboardNav(false); + const target = e.currentTarget as HTMLElement | null; + // The "..." button opens the menu under itself; a right-click at the pointer. + if (e.type === "click" && target) openMenu(anchorEvent(target, "end"), { kind: "item", resource }); + else openMenu(e, { kind: "item", resource }); + }, [selectedResources, onSetSelection, openMenu]); - const allSelected = resources.length > 0 && selectedResources.size === resources.length; - const someSelected = selectedResources.size > 0 && !allSelected; + const closeMenu = menu.closeContextMenu; + const menuData = menu.contextMenu.data; + const menuSelection = menuData?.kind === "item" && selectedResources.has(menuData.resource.name) && selectedResources.size > 1 + ? selectedList + : menuData?.kind === "item" ? [menuData.resource] : []; + + const renderItemMenu = (resource: FileResource) => { + if (menuSelection.length > 1) { + const names = menuSelection.map((r) => r.name); + const fileCount = menuSelection.filter((r) => !r.isDirectory && !r.isSymlink).length; + return ( + <> + {fileCount > 0 && ( + { closeMenu(); downloadNames(names); }} /> + )} + { closeMenu(); onCut(names); }} /> + {menuSelection.some((r) => !r.isSymlink) && ( + { closeMenu(); onCopy(names); }} /> + )} + + { closeMenu(); deleteNames(names); }} /> + + ); + } + const path = pathOf(resource); + const starred = starredPaths.has(path); + return ( + <> + {resource.isDirectory ? ( + { closeMenu(); openResource(resource); }} /> + ) : resource.isSymlink ? null : ( + <> + {isOfficeEditable?.(resource.name) && onEditFile && ( + { closeMenu(); onEditFile(resource.name); }} /> + )} + {isPreviewable(resource.name) && ( + { closeMenu(); previewResource(resource); }} /> + )} + { closeMenu(); void onDownload(resource.name); }} /> + + )} + {(canShare(resource) || (resource.isDirectory && !resource.isShared)) && } + {canShare(resource) && ( + { closeMenu(); setShareTargetId(resource.id); }} /> + )} + {resource.isDirectory && !resource.isShared && ( + { closeMenu(); onToggleFavorite(path); }} + /> + )} + + { closeMenu(); setRenameTarget(resource.name); }} /> + {!resource.isDirectory && !resource.isSymlink && ( + { closeMenu(); void onDuplicate(resource.name); }} /> + )} + { closeMenu(); onCut([resource.name]); }} /> + {!resource.isSymlink && ( + { closeMenu(); onCopy([resource.name]); }} /> + )} + { closeMenu(); toggleDetails(true); }} /> + + { closeMenu(); deleteNames([resource.name]); }} /> + + ); + }; + + const newItems = ( + <> + { closeMenu(); fileInputRef.current?.click(); }} /> + { closeMenu(); folderInputRef.current?.click(); }} /> + + { closeMenu(); setShowNewFolder(true); }} /> + { closeMenu(); setShowNewTextFile(true); }} /> + + ); + + const handlers: FileItemHandlers = useMemo(() => ({ + onSelectClick: handleSelectClick, + onToggleSelect: handleToggleSelect, + onOpen: openResource, + onContextMenu: openItemMenu, + onDownload: (r) => void onDownload(r.name), + onShare: (r) => setShareTargetId(r.id), + canShare, + dragProps: itemDragProps, + }), [handleSelectClick, handleToggleSelect, openResource, openItemMenu, onDownload, canShare, itemDragProps]); + + const handleSort = useCallback((key: SortKey) => { + if (sortKey === key) setSortDir((d) => (d === "asc" ? "desc" : "asc")); + else { + setSortKey(key); + setSortDir(key === "name" ? "asc" : "desc"); + } + }, [sortKey]); + + // A sidebar entry's "New folder" / "Upload" acts on that folder: open it first. + const createIn = useCallback((path: string, id: string | null, kind: CreateKind) => { + if (id !== currentParentId) onNavigate(path, id); + if (kind === "folder") setShowNewFolder(true); + else if (kind === "text") setShowNewTextFile(true); + else if (kind === "files") fileInputRef.current?.click(); + else folderInputRef.current?.click(); + }, [currentParentId, onNavigate]); + + // ---- Rendering ------------------------------------------------------------- + const sidebar = !accountPickerMode && ( + fileInputRef.current?.click()} + onUploadFolder={() => folderInputRef.current?.click()} + onNewFolder={() => setShowNewFolder(true)} + onNewTextFile={() => setShowNewTextFile(true)} + onToggleFavorite={onToggleFavorite} + onDropItems={moveNames} + canShare={canShare} + onShare={(r) => setShareTargetId(r.id)} + onCreateIn={createIn} + onRenameFolder={setRenameFolder} + onDeleteFolder={(folder) => void onDeleteNode(folder.id, folder.name)} + onRevealRecent={(id) => void onRevealNode(id)} + onDownloadRecent={(id) => void onDownloadNode(id)} + onRemoveRecent={onRemoveRecent} + /> + ); + + const showEmpty = !isLoading && !error && displayResources.length === 0 && sharedAtRoot.length === 0 && sharedPagesAtRoot.length === 0; + + const listing = (() => { + if (accountPickerMode) { + return accountFolders && accountFolders.length > 0 && onSelectAccount ? ( +
+

{t("choose_account")}

+
+ {accountFolders.map((acc) => ( + + ))} +
+
+ ) : ( +
+

{t("no_accounts")}

+
+ ); + } + // Until the first listing is in, an empty list means "not loaded yet". + if ((isLoading || !hasListed) && resources.length === 0) return ; + if (showEmpty && searchQuery) return setSearchQuery("")} />; + if (showEmpty) { + return ( + fileInputRef.current?.click()} + onCreateFolder={() => setShowNewFolder(true)} + /> + ); + } + const viewProps = { + resources: displayResources, + selected: selectedResources, + focusedName: focusedName && (keyboardNav || selectedResources.has(focusedName)) ? focusedName : null, + dropTarget, + cutNames, + starredPaths, + pathOf, + touch, + iconOptions, + getImageUrl, + handlers, + }; + return ( + <> + {displayResources.length > 0 && (viewMode === "grid" ? ( + + ) : ( + (allSelected ? onClearSelection() : selectAllVisible())} + /> + ))} + {(sharedAtRoot.length > 0 || sharedPagesAtRoot.length > 0) && ( + onNavigate(`/${r.name}`, r.id)} + iconOptions={iconOptions} + /> + )} + + ); + })(); + + const detailsPanel = showDetails && !accountPickerMode && ( + toggleDetails(false)} + onOpen={() => singleSelected && (singleSelected.isDirectory ? openResource(singleSelected) : previewResource(singleSelected))} + onEdit={() => singleSelected && onEditFile?.(singleSelected.name)} + onDownload={() => singleSelected && void onDownload(singleSelected.name)} + onShare={() => singleSelected && setShareTargetId(singleSelected.id)} + onToggleStar={() => singleSelected && onToggleFavorite(pathOf(singleSelected))} + className={cn( + "flex-shrink-0", + isNarrow ? "absolute inset-y-0 end-0 z-30 w-80 max-w-[85%] shadow-xl" : "w-72", + )} + /> + ); + + const selectionActions = selectedList.length > 0 ? { + count: selectedList.length, + fileCount: selectedList.filter((r) => !r.isDirectory && !r.isSymlink).length, + canOpen: !!singleSelected && !singleSelected.isSymlink + && (singleSelected.isDirectory || isPreviewable(singleSelected.name) || !!isOfficeEditable?.(singleSelected.name)), + canRename: !!singleSelected, + canShare: !!singleSelected && canShare(singleSelected), + onOpen: () => singleSelected && openResource(singleSelected), + onDownload: () => downloadNames(selectedList.map((r) => r.name)), + onShare: () => singleSelected && setShareTargetId(singleSelected.id), + onRename: () => singleSelected && setRenameTarget(singleSelected.name), + onCut: () => onCut(selectedList.map((r) => r.name)), + onCopy: () => onCopy(selectedList.map((r) => r.name)), + onDelete: () => deleteNames(selectedList.map((r) => r.name)), + onClear: onClearSelection, + } : null; return ( -
- {/* Toolbar */} -
- {isNarrow && folderLayout === "sidebar" && ( - - )} - {/* Breadcrumbs */} - + {sidebar} +
+ { dragStartWidth.current = sidebarWidth; setIsResizing(true); }} + onResize={(delta) => setSidebarWidth(Math.max(180, Math.min(400, dragStartWidth.current + delta)))} + onResizeEnd={() => { + setIsResizing(false); + localStorage.setItem("files-sidebar-width", String(sidebarWidth)); + }} + onDoubleClick={() => { setSidebarWidth(SIDEBAR_DEFAULT_WIDTH); localStorage.setItem("files-sidebar-width", String(SIDEBAR_DEFAULT_WIDTH)); }} + /> + + ))} - {/* Action buttons */} -
- {selectedResources.size > 1 && ( - <> - - - - )} - {clipboard && ( - +
+ )} + +
+
{ + if (accountPickerMode || (e.target as HTMLElement).closest("[data-resource]")) return; + menu.openContextMenu(e, { kind: "empty" }); + }} + onClick={(e) => { + // With a mouse, pressing on empty space already cleared the + // selection, and the click that ends a drag-select lands here + // too: clearing again would drop what was just selected. + if (touch && e.target === e.currentTarget && selectedResources.size > 0) onClearSelection(); + }} + onDragEnter={handleContentDragEnter} + onDragOver={handleContentDragOver} + onDragLeave={handleContentDragLeave} + onDrop={handleContentDrop} + > + {listing} + + {marquee && ( +
+ )} +
+ + {isDraggingFiles && ( +
+
+ +

{t("drop_to_upload", { folder: folderName })}

+
+
)} - {!accountPickerMode && ( + + {detailsPanel} + + {isNarrow && canCreate && !selectionActions && ( )} - - {!accountPickerMode && ( - <> - - - - - - - - )} - +
- {/* Search bar */} - {showSearch && ( -
- - setSearchQuery(e.target.value)} - placeholder={t("search_placeholder")} - className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground" - onKeyDown={(e) => { - if (e.key === 'Escape') { - setShowSearch(false); - setSearchQuery(""); - } - }} - /> - {searchQuery && ( - - )} -
- )} - - {/* Hidden file input */} - - {/* Hidden folder input */} + )} + onChange={handleInputChange(true)} + {...({ webkitdirectory: "", directory: "" } as React.InputHTMLAttributes)} /> - {/* Error display with retry */} - {error && ( -
- - {error} - -
- )} - - {/* Drag overlay */} - {isDraggingOver && ( -
-
- -

{t("drop_files_here")}

-
-
- )} - - {/* Upload progress */} - {uploadProgress && ( -
-
- - - {t("uploading")} {uploadProgress.name} - {uploadProgress.totalFiles > 1 && ( - - ({uploadProgress.current}/{uploadProgress.totalFiles}) - - )} - - - {uploadProgress.total > 0 - ? `${Math.round((uploadProgress.loaded / uploadProgress.total) * 100)}%` - : "…"} - - -
-
-
0 - ? `${(uploadProgress.loaded / uploadProgress.total) * 100}%` - : '0%' }} - /> -
-
- )} - - {/* File list */} -
- {/* Narrow-pane backdrop for the overlay folder tree */} - {folderLayout === "sidebar" && isNarrow && narrowSidebarOpen && ( -
setNarrowSidebarOpen(false)} - /> - )} - {/* Folder tree sidebar (when layout is sidebar) */} - {folderLayout === "sidebar" && ( - isNarrow ? ( -
{ - // Auto-close when the user taps a folder name. Chevrons stay - // open so they can expand/collapse without dismissing. - const target = e.target as HTMLElement; - const btn = target.closest('button'); - if (btn && !btn.querySelector('svg.tabler-icon-chevron-right, svg.tabler-icon-chevron-down')) { - setNarrowSidebarOpen(false); - } - }} - > - -
- ) : ( - <> - - { dragStartWidth.current = sidebarWidth; setIsResizing(true); }} - onResize={(delta) => setSidebarWidth(Math.max(180, Math.min(400, dragStartWidth.current + delta)))} - onResizeEnd={() => { - setIsResizing(false); - localStorage.setItem("files-sidebar-width", String(sidebarWidth)); - }} - onDoubleClick={() => { setSidebarWidth(256); localStorage.setItem("files-sidebar-width", "256"); }} - /> - - ) - )} - {/* Favorites & Recent sidebar (when layout is inline) */} - {folderLayout === "inline" && (favorites.length > 0 || recentFiles.length > 0) && ( -
- {favorites.length > 0 && ( -
-

- - {t("favorites")} -

-
- {favorites.map((fav) => ( - - ))} -
-
- )} - {recentFiles.length > 0 && ( -
-

- - {t("recent")} -

-
- {recentFiles.slice(0, 10).map((recent) => ( - - ))} -
-
- )} -
- )} -
- {isLoading && resources.length === 0 ? ( - - - - - - - - - - - - - - - - -
-
-
- {t("name")} -
-
{t("size")}{t("modified")} -
- ) : accountPickerMode && accountFolders && accountFolders.length > 0 && onSelectAccount ? ( - /* ======= ACCOUNT PICKER (Pro mode root) ======= */ -
-
- {accountFolders.map((acc) => ( - - ))} -
-
- ) : accountPickerMode ? ( -
-

{t("no_accounts")}

-
- ) : resources.length === 0 && !searchQuery && currentPath === '/' ? ( - { - setIsUploading(true); - try { - await onUploadFiles(files); - } finally { - setIsUploading(false); - } - }} - onUploadFolder={async (files: File[]) => { - setIsUploading(true); - try { - await onUploadFolder(files); - } finally { - setIsUploading(false); - } - }} - onCreateFolder={() => setShowNewFolder(true)} - onCreateTextFile={() => setShowNewTextFile(true)} - /> - ) : viewMode === "grid" ? ( - /* ======= GRID VIEW ======= */ -
- {currentPath !== '/' && !searchQuery && ( -
{ - if (e.dataTransfer.types.includes("application/x-file-names")) { - e.preventDefault(); - e.dataTransfer.dropEffect = "move"; - setDragTarget('..'); - } - }} - onDragLeave={() => setDragTarget(null)} - onDrop={async (e) => { - e.preventDefault(); - setDragTarget(null); - const raw = e.dataTransfer.getData("application/x-file-names"); - if (!raw) return; - const names: string[] = JSON.parse(raw); - await onMoveToParent(names); - }} - > - - .. -
- )} - {displayResources.length === 0 && searchQuery ? ( -

{t("no_results")}

- ) : ( -
{ - if ((e.target as HTMLElement).closest('[data-resource]')) return; - e.preventDefault(); - setEmptyContextMenu({ x: e.clientX, y: e.clientY }); - }} - > - {displayResources.map((resource) => ( -
{ - const names = selectedResources.has(resource.name) ? [...selectedResources] : [resource.name]; - e.dataTransfer.setData("application/x-file-names", JSON.stringify(names)); - e.dataTransfer.effectAllowed = "move"; - }} - onDragOver={(e) => { - if (resource.isDirectory) { - e.preventDefault(); - e.dataTransfer.dropEffect = "move"; - setDragTarget(resource.name); - } - }} - onDragLeave={() => setDragTarget(null)} - onDrop={async (e) => { - e.preventDefault(); - setDragTarget(null); - if (!resource.isDirectory) return; - const raw = e.dataTransfer.getData("application/x-file-names"); - if (!raw) return; - const names: string[] = JSON.parse(raw); - if (names.includes(resource.name)) return; - await onMoveToFolder(names, resource.name); - }} - className={cn( - "flex flex-col items-center gap-2 p-3 rounded-lg cursor-pointer transition-colors relative group", - selectedResources.has(resource.name) - ? "bg-primary/10 ring-1 ring-primary/30" - : dragTarget === resource.name - ? "bg-primary/5 ring-1 ring-primary/40" - : "hover:bg-muted/50", - clipboard?.mode === "cut" && clipboard.names.includes(resource.name) && "opacity-50" - )} - onClick={(e) => handleResourceClick(resource, e)} - onDoubleClick={() => handleResourceDoubleClick(resource)} - onContextMenu={(e) => handleContextMenu(e, resource.name)} - > - onToggleSelect(resource.name)} - className="w-3.5 h-3.5 rounded border-border accent-primary cursor-pointer absolute top-2 left-2 opacity-0 group-hover:opacity-100 data-[checked=true]:opacity-100" - data-checked={selectedResources.has(resource.name)} - onClick={(e) => e.stopPropagation()} - /> - {showThumbnails && !resource.isSymlink && isImageFile(resource.name) - ? - : getGridIcon(resource, symlinkLabel)} - - {resource.name} - - -
- ))} -
- )} -
- ) : ( - /* ======= LIST VIEW ======= */ - { - if ((e.target as HTMLElement).closest('tr[data-resource]')) return; - e.preventDefault(); - setEmptyContextMenu({ x: e.clientX, y: e.clientY }); - }} - > - - - - - - - - - {currentPath !== '/' && !searchQuery && ( - { - if (e.dataTransfer.types.includes("application/x-file-names")) { - e.preventDefault(); - e.dataTransfer.dropEffect = "move"; - setDragTarget('..'); - } - }} - onDragLeave={() => setDragTarget(null)} - onDrop={async (e) => { - e.preventDefault(); - setDragTarget(null); - const raw = e.dataTransfer.getData("application/x-file-names"); - if (!raw) return; - const names: string[] = JSON.parse(raw); - await onMoveToParent(names); - }} - > - - - )} - {displayResources.length === 0 && searchQuery ? ( - - - - ) : displayResources.map((resource) => ( - { - const names = selectedResources.has(resource.name) ? [...selectedResources] : [resource.name]; - e.dataTransfer.setData("application/x-file-names", JSON.stringify(names)); - e.dataTransfer.effectAllowed = "move"; - }} - onDragOver={(e) => { - if (resource.isDirectory) { - e.preventDefault(); - e.dataTransfer.dropEffect = "move"; - setDragTarget(resource.name); - } - }} - onDragLeave={() => setDragTarget(null)} - onDrop={async (e) => { - e.preventDefault(); - setDragTarget(null); - if (!resource.isDirectory) return; - const raw = e.dataTransfer.getData("application/x-file-names"); - if (!raw) return; - const names: string[] = JSON.parse(raw); - if (names.includes(resource.name)) return; - await onMoveToFolder(names, resource.name); - }} - className={cn( - "border-b border-border cursor-pointer transition-colors", - selectedResources.has(resource.name) - ? "bg-primary/10" - : dragTarget === resource.name - ? "bg-primary/5 ring-1 ring-primary/40" - : "hover:bg-muted/50", - clipboard?.mode === "cut" && clipboard.names.includes(resource.name) && "opacity-50" - )} - onClick={(e) => handleResourceClick(resource, e)} - onDoubleClick={() => handleResourceDoubleClick(resource)} - onContextMenu={(e) => handleContextMenu(e, resource.name)} - > - - - - - - ))} - -
-
- { if (el) el.indeterminate = someSelected; }} - onChange={() => allSelected ? onClearSelection() : onSelectAll()} - className="w-4 h-4 rounded border-border accent-primary cursor-pointer" - onClick={(e) => e.stopPropagation()} - /> - -
-
- - - - -
-
-
- - .. -
-
- - -
- {t("no_results")} -
-
- onToggleSelect(resource.name)} - className="w-4 h-4 rounded border-border accent-primary cursor-pointer shrink-0" - onClick={(e) => e.stopPropagation()} - /> - {showThumbnails && !resource.isSymlink && isImageFile(resource.name) - ? - : getFileIcon(resource, symlinkLabel)} - {resource.name} - -
-
- {resource.isDirectory || resource.isSymlink ? "-" : formatFileSize(resource.contentLength)} - - {formatDate(resource.lastModified)} - - -
- )} - - {/* Context menu */} - {contextMenu && ( -
e.stopPropagation()} - > - {hasContent(contextMenu.name) && isPreviewable(contextMenu.name) && ( - - )} - {hasContent(contextMenu.name) && isOfficeEditable?.(contextMenu.name) && onEditFile && ( - - )} - {hasContent(contextMenu.name) && ( - - )} - - {!resources.find(r => r.name === contextMenu.name)?.isSymlink && ( - - )} - {clipboard && ( - - )} - {hasContent(contextMenu.name) && ( - - )} - {canShare(resources.find(r => r.name === contextMenu.name)) && ( - - )} -
- - - -
- )} - - {/* Empty-area context menu */} - {emptyContextMenu && ( -
e.stopPropagation()} - > - - - - - {clipboard && ( + + {menuData?.kind === "item" && renderItemMenu(menuData.resource)} + {menuData?.kind === "new" && newItems} + {menuData?.kind === "empty" && ( + <> + {canCreate && newItems} + {clipboard && canCreate && ( <> -
- + + { closeMenu(); void onPaste(); }} /> )} -
- -
- )} - - {/* Breadcrumb dropdown */} - {breadcrumbDropdown && ( -
e.stopPropagation()} - > - {breadcrumbDropdown.folders.length === 0 ? ( -

{t("no_results")}

- ) : ( - breadcrumbDropdown.folders.map((folder) => { - const folderPath = breadcrumbDropdown.path === '/' - ? `/${folder.name}` - : `${breadcrumbDropdown.path}/${folder.name}`; - return ( - - ); - }) + + {displayResources.length > 0 && ( + { closeMenu(); selectAllVisible(); }} /> )} -
+ { closeMenu(); void onRefresh(); }} /> + )} + - {/* Marquee selection rectangle */} - {marquee && ( -
- )} -
- - {/* Details sidebar */} - {showDetails && detailResource && ( -
-
-

{t("details")}

- -
-
- {detailResource.isDirectory - ? - : detailResource.isSymlink - ? - : getFileIconByName(detailResource.name, "lg")} -

{detailResource.name}

-
-
-
-
{t("type")}
-
- {detailResource.isDirectory - ? t("folder") - : detailResource.isSymlink ? symlinkLabel : (detailResource.contentType || t("file"))} -
-
- {!detailResource.isDirectory && !detailResource.isSymlink && ( -
-
{t("size")}
-
{formatFileSize(detailResource.contentLength)}
-
- )} - {detailResource.lastModified && ( -
-
{t("modified")}
-
{formatDate(detailResource.lastModified)}
-
- )} -
-
{t("path")}
-
- {currentPath === "/" ? `/${detailResource.name}` : `${currentPath}/${detailResource.name}`} -
-
-
-
- )} -
- - {/* New folder dialog */} {showNewFolder && ( { @@ -2046,7 +1203,6 @@ export function FileBrowser({ /> )} - {/* New text file dialog */} {showNewTextFile && ( )} - {/* Rename dialog */} {renameTarget && ( )} - {/* Share dialog */} + {renameFolder && ( + { + await onRenameNode(renameFolder.id, newName); + setRenameFolder(null); + }} + onCancel={() => setRenameFolder(null)} + validate={validateFileName} + /> + )} + {shareTarget && client && onShare && ( - onShare(shareTarget.id, principalId, rights as FileNodeRights | null)} + onShare={async (principalId, rights) => { + await onShare(shareTarget.id, principalId, rights as FileNodeRights | null); + }} onClose={() => setShareTargetId(null)} /> )}
); } + +function SharedWithMe({ folders, pages, onOpen, iconOptions }: { + folders: FileResource[]; + /** Pages of files shared on their own, one per owner. */ + pages: { id: string; name: string; ownerName: string }[]; + onOpen: (r: { id: string; name: string }) => void; + iconOptions: { showIcons: boolean; coloredIcons: boolean }; +}) { + const t = useTranslations("files"); + return ( +
+

+ + {t("shared_with_me")} +

+
+ {folders.map((folder) => ( + + ))} + {pages.map((page) => ( + + ))} +
+
+ ); +} + +function ListSkeleton() { + return ( +
+
+ {Array.from({ length: 7 }, (_, i) => ( +
+
+
+
+
+ ))} +
+ ); +} diff --git a/components/files/file-details-panel.tsx b/components/files/file-details-panel.tsx new file mode 100644 index 000000000..0751e87be --- /dev/null +++ b/components/files/file-details-panel.tsx @@ -0,0 +1,173 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { X, Download, Share2, Star, StarOff, FolderOpen, Eye, SquarePen, Files } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { cn, formatFileSize } from "@/lib/utils"; +import type { FileResource } from "@/stores/file-store"; +import { + ResourceIcon, Thumbnail, canShowThumbnail, formatFullDate, type IconOptions, +} from "@/components/files/file-item-parts"; + +interface FileDetailsPanelProps { + /** The one selected item, or null. */ + resource: FileResource | null; + /** Everything selected, when more than one item is. */ + selection: FileResource[]; + /** The folder on screen, summarised when nothing is selected. */ + folderName: string; + folderItems: FileResource[]; + path: string; + isStarred: boolean; + canShare: boolean; + canPreview: boolean; + canEdit: boolean; + iconOptions: IconOptions; + getImageUrl: (name: string) => Promise; + onClose: () => void; + onOpen: () => void; + onEdit: () => void; + onDownload: () => void; + onShare: () => void; + onToggleStar: () => void; + className?: string; +} + +function kindOf(resource: FileResource, t: (key: string, values?: Record) => string): string { + if (resource.isDirectory) return t("folder"); + if (resource.isSymlink) return t("symlink"); + const dot = resource.name.lastIndexOf("."); + const ext = dot > 0 ? resource.name.slice(dot + 1).toUpperCase() : ""; + return ext ? t("file_kind", { ext }) : (resource.contentType || t("file")); +} + +function totalSize(items: FileResource[]): number { + return items.reduce((sum, r) => sum + (r.isDirectory || r.isSymlink ? 0 : r.contentLength), 0); +} + +export function FileDetailsPanel({ + resource, selection, folderName, folderItems, path, isStarred, canShare, canPreview, canEdit, + iconOptions, getImageUrl, onClose, onOpen, onEdit, onDownload, onShare, onToggleStar, className, +}: FileDetailsPanelProps) { + const t = useTranslations("files"); + + const header = ( +
+

{t("details")}

+ +
+ ); + + const shell = (body: React.ReactNode) => ( + + ); + + if (!resource) { + const items = selection.length > 1 ? selection : folderItems; + const folders = items.filter((r) => r.isDirectory).length; + const files = items.length - folders; + return shell( +
+
+ {selection.length > 1 + ? + : } +
+
+

+ {selection.length > 1 ? t("selected_count", { count: selection.length }) : folderName} +

+

{t("folder_summary", { folders, files })}

+
+
+ + {selection.length <= 1 && } +
+ {selection.length <= 1 && ( +

{t("details_hint")}

+ )} +
, + ); + } + + const sharedWith = resource.shareWith ? Object.keys(resource.shareWith).length : 0; + const sharing = resource.isShared + ? (resource.ownerName ? t("shared_by", { name: resource.ownerName }) : t("shared_with_me")) + : sharedWith > 0 ? t("shared_with_count", { count: sharedWith }) : t("only_you"); + const bigIcon = ; + + return shell( +
+
+ {canShowThumbnail(resource, iconOptions) ? ( + + ) : bigIcon} +
+
+

{resource.name}

+

{kindOf(resource, t)}

+
+
+ {resource.isDirectory ? ( + + ) : canEdit ? ( + + ) : canPreview ? ( + + ) : null} + {!resource.isDirectory && !resource.isSymlink && ( + + )} + {canShare && ( + + )} + {resource.isDirectory && !resource.isShared && ( + + )} +
+
+ + {!resource.isDirectory && !resource.isSymlink && } + {resource.lastModified && } + + +
+
, + ); +} + +function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) { + return ( +
+
{label}
+
{value}
+
+ ); +} diff --git a/components/files/file-empty-state.tsx b/components/files/file-empty-state.tsx new file mode 100644 index 000000000..8d10930d7 --- /dev/null +++ b/components/files/file-empty-state.tsx @@ -0,0 +1,53 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { Upload, FolderPlus, FolderOpen, SearchX } from "@/components/icons"; +import { Button } from "@/components/ui/button"; + +interface EmptyFolderProps { + isRoot: boolean; + canCreate: boolean; + onUpload: () => void; + onCreateFolder: () => void; +} + +/** What an empty folder shows: what to do next, and that dropping files works. */ +export function EmptyFolder({ isRoot, canCreate, onUpload, onCreateFolder }: EmptyFolderProps) { + const t = useTranslations("files"); + return ( +
+
+
+ {isRoot ? : } +
+

{isRoot ? t("empty_state_title") : t("empty_folder_title")}

+

+ {canCreate ? t("empty_folder_description") : t("empty_folder_read_only")} +

+ {canCreate && ( +
+ + +
+ )} +
+
+ ); +} + +export function NoSearchResults({ query, onClear }: { query: string; onClear: () => void }) { + const t = useTranslations("files"); + return ( +
+ +

{t("no_results_for", { query })}

+ +
+ ); +} diff --git a/components/files/file-icons.tsx b/components/files/file-icons.tsx new file mode 100644 index 000000000..23d8d10b8 --- /dev/null +++ b/components/files/file-icons.tsx @@ -0,0 +1,160 @@ +import { + File, Folder, Image as ImageIcon, FileText, FileAudio, FileVideo, FileArchive, + FileSpreadsheet, Presentation, FileCode, Box, PenTool, + Terminal as TerminalIcon, Database, Type as TypeIcon, Link, +} from "@/components/icons"; + +// File types by extension and the icon for each, shared by the Files app +// and the composer's Files picker. + +const IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "gif", "svg", "webp", "bmp", "ico", "avif"]); + +export function isImageFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return IMAGE_EXTENSIONS.has(ext); +} + +const TEXT_EXTENSIONS = new Set([ + "txt", "md", "markdown", "json", "xml", "html", "htm", "css", "js", "ts", + "jsx", "tsx", "py", "rb", "java", "c", "cpp", "h", "hpp", "go", "rs", + "sh", "bash", "zsh", "yaml", "yml", "toml", "ini", "cfg", "conf", "env", + "log", "csv", "sql", "graphql", "vue", "svelte", "astro", "php", "pl", + "swift", "kt", "scala", "r", "lua", "vim", +]); + +export function isTextFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + const baseName = name.toLowerCase(); + return TEXT_EXTENSIONS.has(ext) || ["dockerfile", "makefile", "readme", "license", "changelog"].includes(baseName); +} + +const AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "flac", "aac", "m4a", "wma", "opus"]); +export function isAudioFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return AUDIO_EXTENSIONS.has(ext); +} + +const VIDEO_EXTENSIONS = new Set(["mp4", "webm", "ogv", "mov", "avi", "mkv", "m4v"]); +export function isVideoFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return VIDEO_EXTENSIONS.has(ext); +} + +const PDF_EXTENSIONS = new Set(["pdf"]); +export function isPdfFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return PDF_EXTENSIONS.has(ext); +} + +const VECTOR_EXTENSIONS = new Set(["svg", "ai", "eps", "ps", "sketch", "fig", "xd", "gvdesign"]); +function isVectorFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return VECTOR_EXTENSIONS.has(ext); +} + +const THREE_D_EXTENSIONS = new Set([ + "obj", "fbx", "gltf", "glb", "stl", "3mf", "step", "stp", "iges", "igs", + "blend", "3ds", "dae", "usdz", "usd", "usda", "usdc", "ply", "wrl", + "c4d", "max", "ma", "mb", "dwg", "dxf", +]); +function is3DFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return THREE_D_EXTENSIONS.has(ext); +} + +const EXECUTABLE_EXTENSIONS = new Set([ + "exe", "msi", "dmg", "app", "appimage", "deb", "rpm", "snap", "flatpak", + "bat", "cmd", "com", "scr", "ps1", "apk", "ipa", "jar", "run", +]); +function isExecutableFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return EXECUTABLE_EXTENSIONS.has(ext); +} + +const ARCHIVE_EXTENSIONS = new Set([ + "zip", "rar", "7z", "tar", "gz", "bz2", "xz", "zst", "lz", "lzma", + "tgz", "tbz2", "txz", "cab", "iso", "img", +]); +function isArchiveFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return ARCHIVE_EXTENSIONS.has(ext); +} + +const SPREADSHEET_EXTENSIONS = new Set(["xls", "xlsx", "ods", "numbers", "tsv"]); +function isSpreadsheetFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return SPREADSHEET_EXTENSIONS.has(ext); +} + +const PRESENTATION_EXTENSIONS = new Set(["ppt", "pptx", "odp", "key"]); +function isPresentationFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return PRESENTATION_EXTENSIONS.has(ext); +} + +const WORD_DOCUMENT_EXTENSIONS = new Set(["doc", "docx", "odt", "rtf"]); +function isWordDocumentFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return WORD_DOCUMENT_EXTENSIONS.has(ext); +} + +const FONT_EXTENSIONS = new Set(["ttf", "otf", "woff", "woff2", "eot"]); +function isFontFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return FONT_EXTENSIONS.has(ext); +} + +const DATABASE_EXTENSIONS = new Set(["db", "sqlite", "sqlite3", "mdb", "accdb"]); +function isDatabaseFile(name: string): boolean { + const ext = name.split(".").pop()?.toLowerCase() || ""; + return DATABASE_EXTENSIONS.has(ext); +} + +export type FileIconSize = "sm" | "md" | "lg" | "xl"; + +const ICON_SIZE_CLASSES: Record = { + sm: "w-5 h-5", + md: "w-6 h-6", + lg: "w-10 h-10", + xl: "w-14 h-14", +}; + +function fileIconFor(name: string): [typeof File, string] { + if (isVectorFile(name)) return [PenTool, "text-orange-500"]; + if (is3DFile(name)) return [Box, "text-cyan-500"]; + if (isImageFile(name)) return [ImageIcon, "text-emerald-500"]; + if (isAudioFile(name)) return [FileAudio, "text-purple-500"]; + if (isVideoFile(name)) return [FileVideo, "text-pink-500"]; + if (isArchiveFile(name)) return [FileArchive, "text-amber-600"]; + if (isExecutableFile(name)) return [TerminalIcon, "text-red-500"]; + if (isSpreadsheetFile(name)) return [FileSpreadsheet, "text-green-600"]; + if (isPresentationFile(name)) return [Presentation, "text-orange-600"]; + if (isWordDocumentFile(name)) return [FileText, "text-blue-600"]; + if (isFontFile(name)) return [TypeIcon, "text-indigo-500"]; + if (isDatabaseFile(name)) return [Database, "text-slate-500"]; + if (isPdfFile(name)) return [FileText, "text-red-600"]; + if (isTextFile(name)) return [FileCode, "text-yellow-600"]; + return [File, "text-muted-foreground"]; +} + +/** The icon for a file name; `colored: false` draws every type in the muted text colour. */ +export function getFileIconByName(name: string, size: FileIconSize, colored = true) { + const [Icon, color] = fileIconFor(name); + return ; +} + +/** + * A symlink's icon, whatever its name suggests: it has no content to open + * (Stalwart 1.0). + */ +export function getSymlinkIcon(size: FileIconSize, label: string) { + return ( + + {label} + + ); +} + +export function getFolderIcon(size: FileIconSize, colored = true) { + return ; +} diff --git a/components/files/file-item-parts.tsx b/components/files/file-item-parts.tsx new file mode 100644 index 000000000..2b201fc3e --- /dev/null +++ b/components/files/file-item-parts.tsx @@ -0,0 +1,198 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { useTranslations } from "next-intl"; +import { Share2, Users } from "@/components/icons"; +import { cn } from "@/lib/utils"; +import { getEffectiveTimeZone } from "@/lib/timezone"; +import type { FileResource } from "@/stores/file-store"; +import { getFileIconByName, getFolderIcon, getSymlinkIcon, isImageFile, type FileIconSize } from "@/components/files/file-icons"; + +/** How list and grid items draw their icon, from Settings > Files. */ +export interface IconOptions { + showIcons: boolean; + coloredIcons: boolean; + showThumbnails: boolean; +} + +// Thumbnails download the whole image, so skip very large ones. +const MAX_THUMBNAIL_BYTES = 15 * 1024 * 1024; + +// Blob ids name immutable content, so a thumbnail fetched once stays valid +// while the page lives; switching views or folders reuses it. +const thumbnailCache = new Map>(); + +export function canShowThumbnail(resource: FileResource, options: IconOptions): boolean { + return options.showThumbnails + && !resource.isDirectory + && !resource.isSymlink + && !!resource.blobId + && isImageFile(resource.name) + && resource.contentLength <= MAX_THUMBNAIL_BYTES; +} + +/** + * An image file's preview, fetched once it scrolls into view. Renders + * `fallback` until the image is ready, and keeps it when the fetch fails. + */ +export function Thumbnail({ resource, getImageUrl, className, wrapperClassName, fallback }: { + resource: FileResource; + getImageUrl: (name: string) => Promise; + className?: string; + /** Sizes the box the image or fallback sits in. */ + wrapperClassName?: string; + fallback: React.ReactNode; +}) { + const [src, setSrc] = useState(null); + const [visible, setVisible] = useState(false); + const ref = useRef(null); + + useEffect(() => { + const el = ref.current; + if (!el) return; + if (typeof IntersectionObserver === "undefined") { + setVisible(true); + return; + } + const observer = new IntersectionObserver((entries) => { + if (entries.some((e) => e.isIntersecting)) { + setVisible(true); + observer.disconnect(); + } + }, { rootMargin: "200px" }); + observer.observe(el); + return () => observer.disconnect(); + }, []); + + useEffect(() => { + if (!visible || !resource.blobId) return; + let cancelled = false; + const key = resource.blobId; + let pending = thumbnailCache.get(key); + if (!pending) { + pending = getImageUrl(resource.name); + thumbnailCache.set(key, pending); + pending.catch(() => thumbnailCache.delete(key)); + } + pending.then((url) => { if (!cancelled) setSrc(url); }).catch(() => {}); + return () => { cancelled = true; }; + }, [visible, resource.blobId, resource.name, getImageUrl]); + + return ( + + {src ? : fallback} + + ); +} + +/** A folder, symlink or file icon, or nothing when icons are turned off. */ +export function ResourceIcon({ resource, size, options }: { + resource: FileResource; + size: FileIconSize; + options: Pick; +}) { + const t = useTranslations("files"); + if (!options.showIcons) return null; + if (resource.isDirectory) return getFolderIcon(size, options.coloredIcons); + if (resource.isSymlink) return getSymlinkIcon(size, t("symlink")); + return getFileIconByName(resource.name, size, options.coloredIcons); +} + +// A node shared out by the user (shareWith has entries) or a node shared +// *with* the user by another principal (isShared). +export function ShareBadge({ resource, t, className }: { + resource: FileResource; + t: (key: string, values?: Record) => string; + className?: string; +}) { + const sharedOut = !!resource.shareWith && Object.keys(resource.shareWith).length > 0; + if (resource.isShared) { + const label = resource.ownerName ? t("shared_by", { name: resource.ownerName }) : t("shared_with_me"); + return ( + + {label} + + ); + } + if (sharedOut) { + return ( + + {t("shared")} + + ); + } + return null; +} + +/** Full date and time, for tooltips and the details panel. */ +export function formatFullDate(value: string): string { + if (!value) return ""; + try { + return new Date(value).toLocaleString(undefined, { + timeZone: getEffectiveTimeZone(), + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }); + } catch { + return value; + } +} + +/** Short date for the list: the time today, day and month this year, the full date otherwise. */ +export function formatShortDate(value: string, now = new Date()): string { + if (!value) return ""; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return value; + const timeZone = getEffectiveTimeZone(); + const dayKey = (d: Date) => d.toLocaleDateString("en-CA", { timeZone }); + try { + if (dayKey(date) === dayKey(now)) { + return date.toLocaleTimeString(undefined, { timeZone, hour: "2-digit", minute: "2-digit" }); + } + const sameYear = date.toLocaleDateString("en-CA", { timeZone, year: "numeric" }) + === now.toLocaleDateString("en-CA", { timeZone, year: "numeric" }); + return date.toLocaleDateString(undefined, { + timeZone, + day: "numeric", + month: "short", + ...(sameYear ? {} : { year: "numeric" }), + }); + } catch { + return value; + } +} + +// Items dragged inside the app carry their names under this type; external +// drags carry "Files" and mean an upload. +export const INTERNAL_DRAG_TYPE = "application/x-file-names"; + +export function isInternalDrag(e: React.DragEvent): boolean { + return e.dataTransfer.types.includes(INTERNAL_DRAG_TYPE); +} + +export function readDraggedNames(e: React.DragEvent): string[] { + const raw = e.dataTransfer.getData(INTERNAL_DRAG_TYPE); + if (!raw) return []; + try { + const parsed = JSON.parse(raw); + return Array.isArray(parsed) ? parsed.filter((n): n is string => typeof n === "string") : []; + } catch { + return []; + } +} + +/** Open a shared context menu as a dropdown under a button. */ +export function anchorEvent(el: HTMLElement, align: "start" | "end" = "start"): React.MouseEvent { + const rect = el.getBoundingClientRect(); + const rtl = typeof document !== "undefined" && document.dir === "rtl"; + const alignEnd = (align === "end") !== rtl; + return { + clientX: alignEnd ? rect.right - 200 : rect.left, + clientY: rect.bottom + 4, + preventDefault: () => {}, + stopPropagation: () => {}, + } as unknown as React.MouseEvent; +} diff --git a/components/files/file-picker-dialog.tsx b/components/files/file-picker-dialog.tsx new file mode 100644 index 000000000..4e1aaf223 --- /dev/null +++ b/components/files/file-picker-dialog.tsx @@ -0,0 +1,311 @@ +"use client"; + +import { useEffect, useMemo, useState, type ReactNode } from "react"; +import { useTranslations } from "next-intl"; +import { AlertCircle, Check, ChevronRight, Folder, Loader2, Search, Users, X } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { useFocusTrap } from "@/hooks/use-focus-trap"; +import { debug } from "@/lib/debug"; +import { cn, formatFileSize } from "@/lib/utils"; +import { getFileIconByName } from "@/components/files/file-icons"; +import { loadFilesSettings } from "@/components/files/files-settings"; +import type { IJMAPClient } from "@/lib/jmap/client-interface"; +import type { FileNode } from "@/lib/jmap/types"; + +// The level that holds what other people share with the user. JMAP ids are +// base64url (shared ones add an "accountId:" prefix), so "#" never collides. +const SHARED_WITH_ME = "#shared"; + +const MAX_SEARCH_RESULTS = 200; + +interface FilePickerDialogProps { + /** Client of the account whose files are listed. */ + client: IJMAPClient; + onClose: () => void; + /** Called with the chosen files, never folders. */ + onPick: (files: FileNode[]) => void; +} + +// A FileNode is a folder iff it has no content blob (see isFolder in the file store). +function isFolder(node: FileNode): boolean { + return node.blobId == null; +} + +function byFolderThenName(a: FileNode, b: FileNode): number { + if (isFolder(a) !== isFolder(b)) return isFolder(a) ? -1 : 1; + return a.name.localeCompare(b.name); +} + +/** + * Lets the user pick files from the Files app, for example to attach them to a + * message (#1179). Lists the whole tree once and browses it locally, so it + * leaves the Files app's own location and selection alone. + */ +export function FilePickerDialog({ client, onClose, onPick }: FilePickerDialogProps) { + const t = useTranslations("files"); + const tComposer = useTranslations("email_composer"); + const [nodes, setNodes] = useState(null); + const [failed, setFailed] = useState(false); + const [attempt, setAttempt] = useState(0); + const [trail, setTrail] = useState<{ id: string; name: string }[]>([]); + const [query, setQuery] = useState(""); + const [selected, setSelected] = useState>(() => new Map()); + const [showHidden] = useState(() => loadFilesSettings().showHiddenFiles); + + const modalRef = useFocusTrap({ isActive: true, onEscape: onClose, restoreFocus: true }); + + useEffect(() => { + let cancelled = false; + client.listAllFileNodesAcrossAccounts().then( + (list) => { + if (!cancelled) setNodes(list); + }, + (error) => { + debug.error("Failed to list files for the picker:", error); + if (!cancelled) setFailed(true); + }, + ); + return () => { + cancelled = true; + }; + }, [client, attempt]); + + const retry = () => { + setNodes(null); + setFailed(false); + setAttempt((n) => n + 1); + }; + + const byId = useMemo(() => new Map((nodes ?? []).map((n) => [n.id, n])), [nodes]); + + // Shared nodes whose parent the user can't see, as in the Files app's + // "Shared with me". + const sharedRoots = useMemo( + () => (nodes ?? []).filter((n) => n.isShared && (n.parentId == null || !byId.has(n.parentId))), + [nodes, byId], + ); + + const here = trail.length > 0 ? trail[trail.length - 1].id : null; + const needle = query.trim().toLowerCase(); + + const entries = useMemo(() => { + if (!nodes) return []; + if (needle) { + return nodes + .filter((n) => !isFolder(n) && n.name.toLowerCase().includes(needle)) + .filter((n) => showHidden || !n.name.startsWith(".")) + .sort(byFolderThenName) + .slice(0, MAX_SEARCH_RESULTS); + } + const level = here === SHARED_WITH_ME + ? sharedRoots + : nodes.filter((n) => (n.parentId ?? null) === here && (here !== null || !n.isShared)); + return level.filter((n) => showHidden || !n.name.startsWith(".")).sort(byFolderThenName); + }, [nodes, needle, here, sharedRoots, showHidden]); + + // Where a search hit lives, e.g. "userb@example.org / Projects". + const folderPath = (node: FileNode): string => { + const names: string[] = []; + const seen = new Set(); + let parent = node.parentId ? byId.get(node.parentId) : undefined; + while (parent && !seen.has(parent.id)) { + seen.add(parent.id); + names.unshift(parent.name); + parent = parent.parentId ? byId.get(parent.parentId) : undefined; + } + if (node.isShared && node.accountName) names.unshift(node.accountName); + return names.join(" / "); + }; + + const openFolder = (id: string, name: string) => { + setTrail((prev) => [...prev, { id, name }]); + setQuery(""); + }; + + const toggle = (node: FileNode) => { + setSelected((prev) => { + const next = new Map(prev); + if (next.has(node.id)) next.delete(node.id); + else next.set(node.id, node); + return next; + }); + }; + + const folderRow = (key: string, name: string, icon: ReactNode, onOpen: () => void, detail?: string) => ( + + ); + + const fileRow = (node: FileNode, detail?: string) => { + const checked = selected.has(node.id); + return ( + + ); + }; + + const sharedBy = (node: FileNode) => + here === SHARED_WITH_ME && node.accountName ? t("shared_by", { name: node.accountName }) : undefined; + + let body: ReactNode; + if (failed) { + body = ( +
+ +

{tComposer("files_picker.load_failed")}

+ +
+ ); + } else if (!nodes) { + body = ( +
+ +
+ ); + } else if (entries.length === 0 && !(here === null && !needle && sharedRoots.length > 0)) { + body = ( +

+ {needle ? t("no_results") : here === null ? t("empty_state_title") : tComposer("files_picker.empty_folder")} +

+ ); + } else { + body = ( +
+ {here === null && !needle && sharedRoots.length > 0 && folderRow( + SHARED_WITH_ME, + t("shared_with_me"), + , + () => openFolder(SHARED_WITH_ME, t("shared_with_me")), + )} + {entries.map((node) => + isFolder(node) + ? folderRow( + node.id, + node.name, + , + () => openFolder(node.id, node.name), + sharedBy(node), + ) + : fileRow(node, needle ? folderPath(node) : sharedBy(node)), + )} +
+ ); + } + + return ( +
+
+
+

+ {tComposer("attach_from_files")} +

+ +
+ +
+
+ + setQuery(e.target.value)} + placeholder={t("search_placeholder")} + className="ps-9 h-9" + /> +
+ {!needle && ( + + )} +
+ +
{body}
+ +
+ + +
+
+
+ ); +} diff --git a/components/files/file-preview-modal.tsx b/components/files/file-preview-modal.tsx index a6366bafc..212d63a10 100644 --- a/components/files/file-preview-modal.tsx +++ b/components/files/file-preview-modal.tsx @@ -4,7 +4,8 @@ import { useState, useEffect, useRef } from "react"; import { useTranslations } from "next-intl"; import { X, Download, Loader2, ExternalLink } from "@/components/icons"; import { Button } from "@/components/ui/button"; -import { getFilePreviewKind, isMimeTypeSafeForInlinePreview } from "@/lib/file-preview"; +import { ZoomableImage } from "@/components/files/zoomable-image"; +import { getFilePreviewKind, imageBlobUrl, isMimeTypeSafeForInlinePreview, previewBlobType } from "@/lib/file-preview"; import dynamic from "next/dynamic"; import { EmlPreview, type ParsedEml } from "@/components/files/eml-preview"; @@ -16,34 +17,6 @@ const PdfMobileViewer = dynamic( { ssr: false }, ); -// Map a few well-known extensions back to canonical MIME types. Used when the -// server returns application/octet-stream (or empty) for an attachment whose -// actual type is obvious from the filename. The blob.type drives how browsers -// render blob: URLs, so guessing wrong here means the inline preview silently -// downgrades to a download. -const EXT_TO_MIME: Record = { - pdf: "application/pdf", - png: "image/png", - jpg: "image/jpeg", - jpeg: "image/jpeg", - gif: "image/gif", - webp: "image/webp", - avif: "image/avif", - bmp: "image/bmp", - mp3: "audio/mpeg", - wav: "audio/wav", - ogg: "audio/ogg", - m4a: "audio/mp4", - mp4: "video/mp4", - webm: "video/webm", - ogv: "video/ogg", -}; - -function inferMimeFromName(name: string): string | undefined { - const ext = name.toLowerCase().split(".").pop(); - return ext ? EXT_TO_MIME[ext] : undefined; -} - interface FilePreviewModalProps { name: string; onClose: () => void; @@ -237,30 +210,26 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }: const parsed = await new PostalMime().parse(await blob.arrayBuffer()); if (!cancelled) setEmlContent(parsed as ParsedEml); } else { - // Stalwart's download endpoint can return generic - // application/octet-stream for attachments even when the email's - // MIME structure declared application/pdf (etc.). The blob inherits - // that, so a blob: URL plugged into