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 @@
-
+
@@ -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. */}
-
+ With a client ID, this label gives the server its own sign-in button on the login page, whichever server is selected and even while OAuth is off globally.
+
+
)}
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}