Files
SRCmail/next.config.ts
T
Bernd Rodler 3f3f3a36b1 fix(jmap): CSP blocked wss:, WS circuit breaker too slow to trip
Two real bugs in the previous WS-push commit, both found while building the
integration test for it (not theoretical - each reproduced and verified
before and after the fix):

1. proxy.ts's production CSP (`connect-src 'self' https:`) has no `wss:`
   term, so `new WebSocket(...)` was blocked before any network attempt at
   all - confirmed by listening for `securitypolicyviolation` against the
   real reference server (stalwart.sandbox.vnc.de, HTTPS): the WS feature
   was entirely inert in a production build, for every server, not just
   ones with an incompatible auth model. Fixed by adding `wss:` alongside
   `https:` in production - no new trust surface, since `https:` here
   already allows fetch/XHR to any TLS host (needed for
   ALLOW_CUSTOM_JMAP_ENDPOINT / multi-server setups), so extending that same
   model to WebSocket is consistent, not a new precedent. Verified after the
   fix: the same probe now reaches the network and gets a real (expected)
   auth rejection from Stalwart instead of a CSP block.

2. lib/jmap/client.ts's circuit breaker (5 attempts, 1s/30s backoff) could
   take up to ~31s to give up on WS and fall back to SSE. Against a server
   that fails the handshake instantly and deterministically every time (the
   auth-header limitation documented in the previous commit), that's ~31s
   of NO live push at all - WS hasn't succeeded and hasn't given up yet, so
   SSE never starts connecting, and any mail delivered in that window was
   silently missed (SSE only streams changes from the moment it connects,
   no catch-up). Reproduced directly: a real SMTP delivery sent during that
   window never reached the notification bridge.

   Fixed two ways:
     - Tightened the ladder to a 200ms base / 5s cap / 3-attempt circuit
       breaker (worst case ~1.75s instead of ~31s) - still genuine
       exponential-with-jitter backoff, just tuned for a failure mode that's
       fast and deterministic rather than slow and flaky. A slow/real
       network issue is unaffected: a hanging attempt is still bounded by
       the browser's own WebSocket connect timeout, not by these constants.
     - setupPushNotifications() now primes a polling baseline
       (fetchCurrentStates()) in parallel with the WS attempt, and
       fallbackFromWebSocket() diffs against it (checkForStateChanges())
       BEFORE connectSSE()/startPollingFallback() get a chance to erase that
       opportunity. This is what actually closes the gap rather than just
       shrinking it: it catches a change that happened to the primary
       account during the (now much shorter) WS retry window.

electron/main.ts also gets a test-only escape hatch (ELECTRON_LOAD_URL): set
it to skip spawning the standalone server and load that URL instead. Real
users and every packaging/CI path never set it - added because verifying
the fixes above against this repo's own local Stalwart fixture (deliberately
plaintext HTTP - integration/webmail.Dockerfile makes the identical
trade-off for the browser-based suite) needs a dev-mode Next.js server
(proxy.ts only widens connect-src for plain http/ws in dev), not the
production standalone build electron/main.ts normally boots.

next.config.ts: added 127.0.0.1 to allowedDevOrigins alongside the existing
LAN entry - electron/main.ts always loads its window at 127.0.0.1, so a
dev-mode Electron run (only used by the escape hatch above) needs it in this
allowlist the same as any other cross-origin dev client would.

Verified: full lib/__tests__ JMAP suite still green (158/158); npm run
test:electron still green (4/4); the raw WebSocket probe against the real
sandbox now reaches the network post-fix instead of being CSP-blocked.
2026-08-04 14:18:08 +02:00

73 lines
2.7 KiB
TypeScript

import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin";
import { execSync } from "child_process";
import { readFileSync } from "fs";
import { join } from "path";
// Prefer an explicit build arg (passed in by CI / Docker, where .git is
// excluded from the build context) and fall back to `git rev-parse` for
// local builds.
let gitCommitHash = process.env.GIT_COMMIT?.trim() || "";
if (!gitCommitHash) {
try {
gitCommitHash = execSync("git rev-parse --short HEAD").toString().trim();
} catch {
gitCommitHash = "unknown";
}
}
// Normalise full 40-char SHAs (e.g. ${{ github.sha }}) to the short form.
if (/^[0-9a-f]{40}$/i.test(gitCommitHash)) {
gitCommitHash = gitCommitHash.slice(0, 7);
}
let appVersion = "0.0.0";
try {
appVersion = readFileSync(join(import.meta.dirname, "VERSION"), "utf-8").trim();
} catch {
// VERSION file not found
}
// Subpath deployment, e.g. NEXT_PUBLIC_BASE_PATH=/webmail. Read at build time
// because Next.js bakes basePath into emitted asset URLs and route metadata.
// Trailing slash is stripped; an empty/missing value disables the feature.
const rawBasePath = process.env.NEXT_PUBLIC_BASE_PATH?.trim() ?? "";
const basePath = rawBasePath.replace(/\/+$/, "");
if (basePath && !basePath.startsWith("/")) {
throw new Error(
`NEXT_PUBLIC_BASE_PATH must start with "/" (got: ${JSON.stringify(rawBasePath)})`
);
}
const nextConfig: NextConfig = {
output: "standalone",
// 127.0.0.1 alongside the existing LAN entry: electron/main.ts always
// loads its window at 127.0.0.1 (see ELECTRON_LOAD_URL and
// startStandaloneServer()), so dev-mode Electron runs (only used by
// integration/tests/11-electron-notification.spec.ts today) need it in
// this allowlist the same way any other cross-origin dev client would.
allowedDevOrigins: ["192.168.1.51", "127.0.0.1"],
basePath: basePath || undefined,
// esbuild ships native binaries + a README the bundler can't parse; load
// it from node_modules at runtime instead of trying to bundle it. Used by
// PLUGIN_DEV_DIR's on-the-fly bundler.
serverExternalPackages: ["esbuild"],
// Sibling repos checked out under ./repos/ are unrelated source trees that
// Turbopack's NFT can otherwise rope into the trace when dynamic fs calls
// confuse it. Keeps the build from ballooning memory tracing dead code.
outputFileTracingExcludes: {
"*": ["./repos/**/*"],
},
turbopack: {
root: import.meta.dirname,
},
env: {
NEXT_PUBLIC_GIT_COMMIT: gitCommitHash,
NEXT_PUBLIC_APP_VERSION: appVersion,
NEXT_PUBLIC_BASE_PATH: basePath,
NEXT_PUBLIC_DEV_MOCK_JMAP: process.env.DEV_MOCK_JMAP ?? "",
},
};
const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);