feat: apiFetch helper for mount-prefix-aware API calls

Makes every client-side fetch('/api/...') call respect the mount prefix
when Bulwark is served behind a reverse proxy at a sub-path (e.g.
`/webmail`).

### Problem

`getPathPrefix()` (added in 1.4.13 by #XXX / d762b94) already fixes
router navigation and redirect URIs for reverse-proxy deployments.
Client-side `fetch()` calls, though, still target the browser origin:

    await fetch('/api/foo')
    // Browser at /webmail/en/inbox → hits /api/foo (not proxied → 404)

That means the login flow, session establishment, settings save, plugin
loader, calendar import, etc. all break the moment you front Bulwark
with nginx (or any proxy) at a sub-path.

### Fix

Add `apiFetch(input, init)` next to `getPathPrefix()` in
`lib/browser-navigation.ts`. It prepends the mount prefix to any
absolute path at call time:

    await apiFetch('/api/foo')
    // /webmail/en/inbox → /webmail/api/foo
    // /en/inbox         → /api/foo

Same runtime-detection model as `getPathPrefix()` — the built bundle
works at any mount point without rebuilding or env-var config.
Protocol-relative (`//cdn...`) and absolute (`https://...`) URLs pass
through unchanged. Server-side route handlers are untouched (the mount
prefix is a browser-only concept).

### Migration

Mechanical rewrite of every client-side `fetch('/api/...')` call in
hooks/, lib/, stores/, components/, app/ — 99 call sites across
26 files. `route.ts` handlers and other server-only files are skipped.

### Compat

- No behaviour change when mounted at `/` (the common case): an empty
  prefix + raw path is identical to raw path.
- No new config knobs, env vars, or build flags.
- Supersedes PR #181 (which required a build-time `NEXT_PUBLIC_BASE_PATH`)
  — will close #181 after this lands.

### Testing

Should run the existing suite; smoke-tested by Jabali Panel which
reverse-proxies Bulwark at `/webmail/` (https://github.com/shukiv/jabali-panel).
This commit is contained in:
shuki
2026-04-14 14:37:19 +02:00
committed by Linus Rath
parent bdb76c3d90
commit a7db3883aa
27 changed files with 154 additions and 101 deletions
+12 -11
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand';
import { debug } from '@/lib/debug';
import { getActiveAccountSlotHeaders } from '@/lib/auth/active-account-slot';
import { apiFetch } from '@/lib/browser-navigation';
interface AccountSecurityState {
// Detection
@@ -66,7 +67,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
probe: async () => {
set({ isProbing: true });
try {
const response = await fetch('/api/account/stalwart/probe', {
const response = await apiFetch('/api/account/stalwart/probe', {
headers: getApiHeaders(),
});
const data = await response.json();
@@ -83,7 +84,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
fetchAuthInfo: async () => {
set({ isLoadingAuth: true, error: null });
try {
const response = await fetch('/api/account/stalwart/auth', {
const response = await apiFetch('/api/account/stalwart/auth', {
headers: getApiHeaders(),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -105,7 +106,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
fetchCryptoInfo: async () => {
set({ isLoadingCrypto: true, error: null });
try {
const response = await fetch('/api/account/stalwart/crypto', {
const response = await apiFetch('/api/account/stalwart/crypto', {
headers: getApiHeaders(),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -126,7 +127,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
fetchPrincipal: async () => {
set({ isLoadingPrincipal: true, error: null });
try {
const response = await fetch('/api/account/stalwart/principal', {
const response = await apiFetch('/api/account/stalwart/principal', {
headers: getApiHeaders(),
});
if (!response.ok) {
@@ -169,7 +170,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
changePassword: async (currentPassword, newPassword) => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/password', {
const response = await apiFetch('/api/account/stalwart/password', {
method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ currentPassword, newPassword }),
@@ -193,7 +194,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
updateDisplayName: async (displayName) => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/principal', {
const response = await apiFetch('/api/account/stalwart/principal', {
method: 'PATCH',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([
@@ -219,7 +220,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
enableTotp: async () => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/auth', {
const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'enableOtpAuth' }]),
@@ -245,7 +246,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
disableTotp: async () => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/auth', {
const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'disableOtpAuth' }]),
@@ -269,7 +270,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
addAppPassword: async (name, password) => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/auth', {
const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'addAppPassword', name, password }]),
@@ -295,7 +296,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
removeAppPassword: async (name) => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/auth', {
const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'removeAppPassword', name }]),
@@ -321,7 +322,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
updateEncryption: async (settings) => {
set({ isSaving: true, error: null });
try {
const response = await fetch('/api/account/stalwart/crypto', {
const response = await apiFetch('/api/account/stalwart/crypto', {
method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(settings),
+20 -20
View File
@@ -12,7 +12,7 @@ import { useAccountStore } from './account-store';
import { fetchConfig } from '@/hooks/use-config';
import { debug } from '@/lib/debug';
import { generateAccountId } from '@/lib/account-utils';
import { replaceWindowLocation, getPathPrefix, getLocaleFromPath } from '@/lib/browser-navigation';
import { replaceWindowLocation, getPathPrefix, getLocaleFromPath, apiFetch } from '@/lib/browser-navigation';
import { notifyParent } from '@/lib/iframe-bridge';
import { snapshotAccount, restoreAccount, clearAllStores, evictAccount, evictAll } from '@/lib/account-state-manager';
import type { Identity } from '@/lib/jmap/types';
@@ -95,7 +95,7 @@ async function syncStalwartAuthContext(
slot: number,
): Promise<void> {
try {
const response = await fetch('/api/auth/stalwart-context', {
const response = await apiFetch('/api/auth/stalwart-context', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverUrl, username, authHeader, slot }),
@@ -403,7 +403,7 @@ export const useAuthStore = create<AuthState>()(
if (totp) {
try {
const tokenRes = await fetch('/api/auth/totp-token-exchange', {
const tokenRes = await apiFetch('/api/auth/totp-token-exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }),
@@ -470,7 +470,7 @@ export const useAuthStore = create<AuthState>()(
if (rememberMe && !upgradedToOAuth) {
// For basic auth (no TOTP or TOTP upgrade failed), store encrypted credentials
try {
const res = await fetch(`/api/auth/session?slot=${cookieSlot}`, {
const res = await apiFetch(`/api/auth/session?slot=${cookieSlot}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }),
@@ -607,7 +607,7 @@ export const useAuthStore = create<AuthState>()(
: 0;
const slot = pendingSlot >= 0 && pendingSlot <= 4 ? pendingSlot : accountStore.getNextCookieSlot();
const tokenRes = await fetch(`/api/auth/token?slot=${slot}`, {
const tokenRes = await apiFetch(`/api/auth/token?slot=${slot}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, code_verifier: codeVerifier, redirect_uri: redirectUri, slot }),
@@ -718,7 +718,7 @@ export const useAuthStore = create<AuthState>()(
try {
// Server-side SSO: the server holds the PKCE verifier in an encrypted cookie
const ssoRes = await fetch('/api/auth/sso/complete', {
const ssoRes = await apiFetch('/api/auth/sso/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
@@ -841,7 +841,7 @@ export const useAuthStore = create<AuthState>()(
const promise = (async () => {
try {
const res = await fetch(`/api/auth/token?slot=${slot}`, { method: 'PUT' });
const res = await apiFetch(`/api/auth/token?slot=${slot}`, { method: 'PUT' });
if (!res.ok) {
notifyParent('sso:session-expired');
@@ -963,9 +963,9 @@ export const useAuthStore = create<AuthState>()(
}
// Background cookie cleanup for the removed account
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
apiFetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
apiFetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
}
return;
}
@@ -977,9 +977,9 @@ export const useAuthStore = create<AuthState>()(
// Background cookie/token cleanup — keepalive ensures completion during navigation
if (!wasDemoMode) {
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
apiFetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
apiFetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
}
}
@@ -1006,8 +1006,8 @@ export const useAuthStore = create<AuthState>()(
}
// Background cookie/token cleanup
fetch('/api/auth/session?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
fetch('/api/auth/token?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
apiFetch('/api/auth/session?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
apiFetch('/api/auth/token?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
redirectToLogin();
},
@@ -1041,7 +1041,7 @@ export const useAuthStore = create<AuthState>()(
// Client not connected — try to restore
try {
if (targetAccount.authMode === 'oauth') {
const res = await fetch(`/api/auth/token?slot=${targetAccount.cookieSlot}`, { method: 'PUT' });
const res = await apiFetch(`/api/auth/token?slot=${targetAccount.cookieSlot}`, { method: 'PUT' });
if (res.ok) {
const { access_token, expires_in } = await res.json();
const refreshFn = get().refreshAccessToken;
@@ -1058,7 +1058,7 @@ export const useAuthStore = create<AuthState>()(
);
}
} else if (targetAccount.authMode === 'basic' && targetAccount.rememberMe) {
const res = await fetch(`/api/auth/session?slot=${targetAccount.cookieSlot}`, { method: 'PUT' });
const res = await apiFetch(`/api/auth/session?slot=${targetAccount.cookieSlot}`, { method: 'PUT' });
if (res.ok) {
const { serverUrl, username, password } = await res.json();
targetClient = new JMAPClient(serverUrl, username, password);
@@ -1107,7 +1107,7 @@ export const useAuthStore = create<AuthState>()(
// Cannot restore — remove the stale account and redirect to login
evictAccount(accountId);
accountStore.removeAccount(accountId);
fetch(`/api/auth/session?slot=${targetAccount.cookieSlot}`, { method: 'DELETE' }).catch(() => {});
apiFetch(`/api/auth/session?slot=${targetAccount.cookieSlot}`, { method: 'DELETE' }).catch(() => {});
// Restore the previous account if still available
if (state.activeAccountId && state.activeAccountId !== accountId) {
@@ -1210,7 +1210,7 @@ export const useAuthStore = create<AuthState>()(
try {
if (account.authMode === 'oauth') {
const res = await fetch(`/api/auth/token?slot=${account.cookieSlot}`, { method: 'PUT' });
const res = await apiFetch(`/api/auth/token?slot=${account.cookieSlot}`, { method: 'PUT' });
if (res.ok) {
const { access_token, expires_in } = await res.json();
const refreshFn = get().refreshAccessToken;
@@ -1225,7 +1225,7 @@ export const useAuthStore = create<AuthState>()(
throw new Error(`Token refresh failed: ${res.status}`);
}
} else if (account.authMode === 'basic' && account.rememberMe) {
const res = await fetch(`/api/auth/session?slot=${account.cookieSlot}`, { method: 'PUT' });
const res = await apiFetch(`/api/auth/session?slot=${account.cookieSlot}`, { method: 'PUT' });
if (res.ok) {
const { serverUrl, username, password } = await res.json();
const client = new JMAPClient(serverUrl, username, password);
@@ -1255,7 +1255,7 @@ export const useAuthStore = create<AuthState>()(
// again rather than seeing a stale error entry forever.
evictAccount(account.id);
accountStore.removeAccount(account.id);
fetch(`/api/auth/session?slot=${account.cookieSlot}`, { method: 'DELETE' }).catch(() => {});
apiFetch(`/api/auth/session?slot=${account.cookieSlot}`, { method: 'DELETE' }).catch(() => {});
}
}
@@ -1417,7 +1417,7 @@ export const useAuthStore = create<AuthState>()(
if (state.authMode === 'basic') {
set({ isLoading: true, isRateLimited: false, rateLimitUntil: null });
try {
const res = await fetch('/api/auth/session', { method: 'PUT' });
const res = await apiFetch('/api/auth/session', { method: 'PUT' });
if (res.ok) {
const data = await res.json();
if (!data.serverUrl || !data.username || !data.password) {
+2 -1
View File
@@ -7,6 +7,7 @@ import { normalizeAllDayDuration } from '@/lib/calendar-utils';
import { sanitizeOutgoingCalendarEventData } from '@/lib/calendar-event-normalization';
import { expandRecurringEvents } from '@/lib/recurrence-expansion';
import { generateUUID } from '@/lib/utils';
import { apiFetch } from '@/lib/browser-navigation';
export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda' | 'tasks';
@@ -809,7 +810,7 @@ export const useCalendarStore = create<CalendarStore>()(
if (!sub) return;
try {
const response = await fetch('/api/fetch-ical', {
const response = await apiFetch('/api/fetch-ical', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: sub.url }),
+3 -2
View File
@@ -15,6 +15,7 @@ import { loadPlugin, deactivatePlugin, setPluginStoreAccessor, setupAutoDisable
import { setSlotRegistrationBridge } from '@/lib/plugin-api';
import { removeAllPluginHooks } from '@/lib/plugin-hooks';
import { usePolicyStore } from '@/stores/policy-store';
import { apiFetch } from '@/lib/browser-navigation';
// ─── Slot State ──────────────────────────────────────────────
@@ -363,7 +364,7 @@ async function syncServerPlugins(
set: (partial: Partial<PluginStoreState> | ((state: PluginStoreState) => Partial<PluginStoreState>)) => void,
): Promise<void> {
try {
const res = await fetch('/api/plugins');
const res = await apiFetch('/api/plugins');
if (!res.ok) return;
const data: { plugins: ServerPluginInfo[] } = await res.json();
@@ -484,7 +485,7 @@ async function syncServerPlugins(
async function downloadPluginBundle(pluginId: string): Promise<string | null> {
try {
const res = await fetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/bundle`);
const res = await apiFetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/bundle`);
if (!res.ok) return null;
return await res.text();
} catch {
+2 -1
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand';
import type { SettingsPolicy, FeatureGates, SettingRestriction, ThemePolicy } from '@/lib/admin/types';
import { DEFAULT_POLICY, DEFAULT_THEME_POLICY } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
interface PolicyState {
policy: SettingsPolicy;
@@ -25,7 +26,7 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({
fetchPolicy: async () => {
try {
const res = await fetch('/api/admin/policy');
const res = await apiFetch('/api/admin/policy');
if (res.ok) {
const data = await res.json();
set({ policy: data, loaded: true });
+3 -2
View File
@@ -3,6 +3,7 @@ import { persist } from 'zustand/middleware';
import { useThemeStore } from './theme-store';
import { useLocaleStore } from './locale-store';
import type { NotificationSoundChoice } from '@/lib/notification-sound';
import { apiFetch } from '@/lib/browser-navigation';
// Use console directly to avoid circular dependency with lib/debug.ts
// (debug.ts imports useSettingsStore for debugMode check)
@@ -611,7 +612,7 @@ export const useSettingsStore = create<SettingsState>()(
loadFromServer: async (username: string, serverUrl: string) => {
try {
syncLog('Loading settings from server for', username);
const res = await fetch('/api/settings', {
const res = await apiFetch('/api/settings', {
headers: {
'x-settings-username': username,
'x-settings-server': serverUrl,
@@ -747,7 +748,7 @@ if (typeof window !== 'undefined') {
const syncToServer = async (retries = 1): Promise<void> => {
const settings = JSON.parse(useSettingsStore.getState().exportSettings());
syncLog('Syncing settings to server...');
const res = await fetch('/api/settings', {
const res = await apiFetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: syncUsername, serverUrl: syncServerUrl, settings }),
+3 -2
View File
@@ -6,6 +6,7 @@ import { injectThemeCSS, removeThemeCSS, sanitizeThemeCSS } from '@/lib/theme-lo
import { extractTheme } from '@/lib/plugin-validator';
import { BUILTIN_THEMES } from '@/lib/builtin-themes';
import { usePolicyStore } from '@/stores/policy-store';
import { apiFetch } from '@/lib/browser-navigation';
type Theme = 'light' | 'dark' | 'system';
@@ -299,7 +300,7 @@ export const useThemeStore = create<ThemeState>()(
themeSyncPromise = (async () => {
try {
const res = await fetch('/api/plugins');
const res = await apiFetch('/api/plugins');
if (!res.ok) return;
const data: { themes: ServerThemeInfo[] } = await res.json();
@@ -480,7 +481,7 @@ function dedupeInstalledThemes(themes: InstalledTheme[]): InstalledTheme[] {
async function downloadThemeCSS(themeId: string): Promise<string | null> {
try {
const res = await fetch(`/api/admin/themes/${encodeURIComponent(themeId)}/css`);
const res = await apiFetch(`/api/admin/themes/${encodeURIComponent(themeId)}/css`);
if (!res.ok) return null;
return await res.text();
} catch {