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
+2 -2
View File
@@ -10,7 +10,7 @@ import { useAuthStore } from "@/stores/auth-store";
import { useThemeStore } from "@/stores/theme-store"; import { useThemeStore } from "@/stores/theme-store";
import { useShallow } from "zustand/react/shallow"; import { useShallow } from "zustand/react/shallow";
import { useConfig } from "@/hooks/use-config"; import { useConfig } from "@/hooks/use-config";
import { getPathPrefix } from "@/lib/browser-navigation"; import { apiFetch, getPathPrefix } from "@/lib/browser-navigation";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play, Copy } from "lucide-react"; import { AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play, Copy } from "lucide-react";
import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery"; import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
@@ -234,7 +234,7 @@ export default function LoginPage() {
try { try {
const prefix = getPathPrefix(params.locale as string); const prefix = getPathPrefix(params.locale as string);
const redirectUri = `${window.location.origin}${prefix}/${params.locale}/auth/callback`; const redirectUri = `${window.location.origin}${prefix}/${params.locale}/auth/callback`;
const res = await fetch('/api/auth/sso/start', { const res = await apiFetch('/api/auth/sso/start', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
credentials: 'include', credentials: 'include',
+4 -3
View File
@@ -2,6 +2,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Save, Loader2, RotateCcw } from 'lucide-react'; import { Save, Loader2, RotateCcw } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigEntry { interface ConfigEntry {
value: unknown; value: unknown;
@@ -19,7 +20,7 @@ export default function AdminAuthPage() {
async function fetchConfig() { async function fetchConfig() {
setLoading(true); setLoading(true);
const res = await fetch('/api/admin/config'); const res = await apiFetch('/api/admin/config');
if (res.ok) setConfig(await res.json()); if (res.ok) setConfig(await res.json());
setLoading(false); setLoading(false);
} }
@@ -39,7 +40,7 @@ export default function AdminAuthPage() {
setSaving(true); setSaving(true);
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/config', { const res = await apiFetch('/api/admin/config', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(edits), body: JSON.stringify(edits),
@@ -57,7 +58,7 @@ export default function AdminAuthPage() {
} }
async function handleRevert(key: string) { async function handleRevert(key: string) {
const res = await fetch('/api/admin/config', { const res = await apiFetch('/api/admin/config', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }), body: JSON.stringify({ key }),
+6 -5
View File
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { Save, Loader2, RotateCcw, ImageIcon, Upload, Trash2 } from 'lucide-react'; import { Save, Loader2, RotateCcw, ImageIcon, Upload, Trash2 } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigEntry { interface ConfigEntry {
value: unknown; value: unknown;
@@ -38,7 +39,7 @@ export default function AdminBrandingPage() {
async function fetchConfig() { async function fetchConfig() {
setLoading(true); setLoading(true);
const res = await fetch('/api/admin/config'); const res = await apiFetch('/api/admin/config');
if (res.ok) setConfig(await res.json()); if (res.ok) setConfig(await res.json());
setLoading(false); setLoading(false);
} }
@@ -58,7 +59,7 @@ export default function AdminBrandingPage() {
setSaving(true); setSaving(true);
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/config', { const res = await apiFetch('/api/admin/config', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(edits), body: JSON.stringify(edits),
@@ -83,7 +84,7 @@ export default function AdminBrandingPage() {
formData.append('file', file); formData.append('file', file);
formData.append('slot', slot); formData.append('slot', slot);
const res = await fetch('/api/admin/branding', { const res = await apiFetch('/api/admin/branding', {
method: 'POST', method: 'POST',
body: formData, body: formData,
}); });
@@ -112,7 +113,7 @@ export default function AdminBrandingPage() {
async function handleDeleteUpload(slot: string) { async function handleDeleteUpload(slot: string) {
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/branding', { const res = await apiFetch('/api/admin/branding', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ slot }), body: JSON.stringify({ slot }),
@@ -133,7 +134,7 @@ export default function AdminBrandingPage() {
} }
async function handleRevert(key: string) { async function handleRevert(key: string) {
const res = await fetch('/api/admin/config', { const res = await apiFetch('/api/admin/config', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }), body: JSON.stringify({ key }),
+2 -1
View File
@@ -3,6 +3,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { Lock } from 'lucide-react'; import { Lock } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
export default function ChangePasswordPage() { export default function ChangePasswordPage() {
const router = useRouter(); const router = useRouter();
@@ -28,7 +29,7 @@ export default function ChangePasswordPage() {
} }
setLoading(true); setLoading(true);
const res = await fetch('/api/admin/change-password', { const res = await apiFetch('/api/admin/change-password', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ currentPassword, newPassword }), body: JSON.stringify({ currentPassword, newPassword }),
+4 -3
View File
@@ -27,6 +27,7 @@ import { useThemeStore } from '@/stores/theme-store';
import { getActiveAccountSlotHeaders } from '@/lib/auth/active-account-slot'; import { getActiveAccountSlotHeaders } from '@/lib/auth/active-account-slot';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { apiFetch } from '@/lib/browser-navigation';
const NAV_GROUPS = [ const NAV_GROUPS = [
{ {
@@ -85,7 +86,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
async function checkAuth() { async function checkAuth() {
try { try {
const jmapHeaders = getJmapHeaders(); const jmapHeaders = getJmapHeaders();
const res = await fetch('/api/admin/auth', { headers: jmapHeaders }); const res = await apiFetch('/api/admin/auth', { headers: jmapHeaders });
const data = await res.json(); const data = await res.json();
const stalwartAdmin = data.stalwartAdmin === true; const stalwartAdmin = data.stalwartAdmin === true;
@@ -104,7 +105,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
// If Stalwart admin but not yet authenticated, auto-login // If Stalwart admin but not yet authenticated, auto-login
if (stalwartAdmin) { if (stalwartAdmin) {
const loginRes = await fetch('/api/admin/auth', { const loginRes = await apiFetch('/api/admin/auth', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', ...jmapHeaders }, headers: { 'Content-Type': 'application/json', ...jmapHeaders },
body: JSON.stringify({ stalwartAuth: true }), body: JSON.stringify({ stalwartAuth: true }),
@@ -122,7 +123,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
} }
async function handleLogout() { async function handleLogout() {
await fetch('/api/admin/auth', { method: 'DELETE' }); await apiFetch('/api/admin/auth', { method: 'DELETE' });
router.replace('/admin/login'); router.replace('/admin/login');
} }
+2 -1
View File
@@ -5,6 +5,7 @@ import { useRouter } from 'next/navigation';
import { Shield } from 'lucide-react'; import { Shield } from 'lucide-react';
import { useConfig } from '@/hooks/use-config'; import { useConfig } from '@/hooks/use-config';
import { useThemeStore } from '@/stores/theme-store'; import { useThemeStore } from '@/stores/theme-store';
import { apiFetch } from '@/lib/browser-navigation';
export default function AdminLoginPage() { export default function AdminLoginPage() {
const router = useRouter(); const router = useRouter();
@@ -21,7 +22,7 @@ export default function AdminLoginPage() {
setLoading(true); setLoading(true);
try { try {
const res = await fetch('/api/admin/auth', { const res = await apiFetch('/api/admin/auth', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }), body: JSON.stringify({ password }),
+2 -1
View File
@@ -3,6 +3,7 @@
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback } from 'react';
import { RefreshCw } from 'lucide-react'; import { RefreshCw } from 'lucide-react';
import type { AuditEntry } from '@/lib/admin/types'; import type { AuditEntry } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
export default function AdminLogsPage() { export default function AdminLogsPage() {
const [entries, setEntries] = useState<AuditEntry[]>([]); const [entries, setEntries] = useState<AuditEntry[]>([]);
@@ -17,7 +18,7 @@ export default function AdminLogsPage() {
const params = new URLSearchParams({ page: String(page), limit: String(limit) }); const params = new URLSearchParams({ page: String(page), limit: String(limit) });
if (actionFilter) params.set('action', actionFilter); if (actionFilter) params.set('action', actionFilter);
const res = await fetch(`/api/admin/audit?${params}`); const res = await apiFetch(`/api/admin/audit?${params}`);
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setEntries(data.entries || []); setEntries(data.entries || []);
+3 -2
View File
@@ -2,6 +2,7 @@
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback } from 'react';
import { Search, Download, Check, Loader2, Store, Puzzle, SwatchBook, Star, Filter } from 'lucide-react'; import { Search, Download, Check, Loader2, Store, Puzzle, SwatchBook, Star, Filter } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
interface Extension { interface Extension {
slug: string; slug: string;
@@ -57,7 +58,7 @@ export default function AdminMarketplacePage() {
params.set('perPage', String(perPage)); params.set('perPage', String(perPage));
params.set('sort', 'newest'); params.set('sort', 'newest');
const res = await fetch(`/api/admin/marketplace?${params}`); const res = await apiFetch(`/api/admin/marketplace?${params}`);
if (!res.ok) { if (!res.ok) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
setError(data.error || 'Failed to connect to extension directory'); setError(data.error || 'Failed to connect to extension directory');
@@ -95,7 +96,7 @@ export default function AdminMarketplacePage() {
setMessage(null); setMessage(null);
try { try {
const res = await fetch('/api/admin/marketplace', { const res = await apiFetch('/api/admin/marketplace', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
+9 -8
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { AlertTriangle } from 'lucide-react'; import { AlertTriangle } from 'lucide-react';
import { SettingsSection, SettingItem, ToggleSwitch } from '@/components/settings/settings-section'; import { SettingsSection, SettingItem, ToggleSwitch } from '@/components/settings/settings-section';
import type { AuditEntry } from '@/lib/admin/types'; import type { AuditEntry } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
interface AdminStatus { interface AdminStatus {
enabled: boolean; enabled: boolean;
@@ -38,13 +39,13 @@ export default function AdminDashboardPage() {
async function fetchDashboardData() { async function fetchDashboardData() {
const [statusRes, auditRes, configRes, adminConfigRes, pluginRes, themeRes, policyRes] = await Promise.all([ const [statusRes, auditRes, configRes, adminConfigRes, pluginRes, themeRes, policyRes] = await Promise.all([
fetch('/api/admin/auth'), apiFetch('/api/admin/auth'),
fetch('/api/admin/audit?limit=10'), apiFetch('/api/admin/audit?limit=10'),
fetch('/api/config'), apiFetch('/api/config'),
fetch('/api/admin/config'), apiFetch('/api/admin/config'),
fetch('/api/admin/plugins').catch(() => null), apiFetch('/api/admin/plugins').catch(() => null),
fetch('/api/admin/themes').catch(() => null), apiFetch('/api/admin/themes').catch(() => null),
fetch('/api/admin/policy').catch(() => null), apiFetch('/api/admin/policy').catch(() => null),
]); ]);
if (statusRes.ok) setStatus(await statusRes.json()); if (statusRes.ok) setStatus(await statusRes.json());
@@ -75,7 +76,7 @@ export default function AdminDashboardPage() {
if (configData?.jmapServerUrl) { if (configData?.jmapServerUrl) {
try { try {
const jmapRes = await fetch('/api/config'); const jmapRes = await apiFetch('/api/config');
setJmapHealth(jmapRes.ok ? 'ok' : 'error'); setJmapHealth(jmapRes.ok ? 'ok' : 'error');
} catch { } catch {
setJmapHealth('error'); setJmapHealth('error');
+5 -4
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation'; import { useParams } from 'next/navigation';
import { Puzzle, ArrowLeft, Loader2, Eye, EyeOff } from 'lucide-react'; import { Puzzle, ArrowLeft, Loader2, Eye, EyeOff } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigField { interface ConfigField {
type: 'string' | 'secret' | 'boolean' | 'number' | 'select'; type: 'string' | 'secret' | 'boolean' | 'number' | 'select';
@@ -68,8 +69,8 @@ export default function PluginConfigPage() {
setLoading(true); setLoading(true);
try { try {
const [pluginsRes, configRes] = await Promise.all([ const [pluginsRes, configRes] = await Promise.all([
fetch('/api/admin/plugins'), apiFetch('/api/admin/plugins'),
fetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/config`), apiFetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/config`),
]); ]);
if (pluginsRes.ok) { if (pluginsRes.ok) {
@@ -117,7 +118,7 @@ export default function PluginConfigPage() {
// Delete if clearing a non-required field // Delete if clearing a non-required field
if (!newVal && !field.required) { if (!newVal && !field.required) {
const res = await fetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/config`, { const res = await apiFetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/config`, {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }), body: JSON.stringify({ key }),
@@ -130,7 +131,7 @@ export default function PluginConfigPage() {
continue; continue;
} }
const res = await fetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/config`, { const res = await apiFetch(`/api/admin/plugins/${encodeURIComponent(pluginId)}/config`, {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value }), body: JSON.stringify({ key, value }),
+10 -9
View File
@@ -5,6 +5,7 @@ import Link from 'next/link';
import { Upload, Trash2, Power, PowerOff, AlertTriangle, Loader2, Package, Save, Shield, Lock, LockOpen, Settings } from 'lucide-react'; import { Upload, Trash2, Power, PowerOff, AlertTriangle, Loader2, Package, Save, Shield, Lock, LockOpen, Settings } from 'lucide-react';
import type { SettingsPolicy } from '@/lib/admin/types'; import type { SettingsPolicy } from '@/lib/admin/types';
import { DEFAULT_POLICY } from '@/lib/admin/types'; import { DEFAULT_POLICY } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
interface PluginEntry { interface PluginEntry {
id: string; id: string;
@@ -34,7 +35,7 @@ export default function AdminPluginsPage() {
async function fetchPolicy() { async function fetchPolicy() {
try { try {
const res = await fetch('/api/admin/policy'); const res = await apiFetch('/api/admin/policy');
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setPolicy(data); setPolicy(data);
@@ -73,7 +74,7 @@ export default function AdminPluginsPage() {
setSavingPolicy(true); setSavingPolicy(true);
setMessage(null); setMessage(null);
try { try {
const res = await fetch('/api/admin/policy', { const res = await apiFetch('/api/admin/policy', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(policy), body: JSON.stringify(policy),
@@ -95,7 +96,7 @@ export default function AdminPluginsPage() {
async function fetchPlugins() { async function fetchPlugins() {
setLoading(true); setLoading(true);
try { try {
const res = await fetch('/api/admin/plugins'); const res = await apiFetch('/api/admin/plugins');
if (res.ok) setPlugins(await res.json()); if (res.ok) setPlugins(await res.json());
} finally { } finally {
setLoading(false); setLoading(false);
@@ -113,7 +114,7 @@ export default function AdminPluginsPage() {
formData.append('file', file); formData.append('file', file);
try { try {
const res = await fetch('/api/admin/plugins', { const res = await apiFetch('/api/admin/plugins', {
method: 'POST', method: 'POST',
body: formData, body: formData,
}); });
@@ -136,7 +137,7 @@ export default function AdminPluginsPage() {
async function togglePlugin(id: string, enabled: boolean) { async function togglePlugin(id: string, enabled: boolean) {
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/plugins', { const res = await apiFetch('/api/admin/plugins', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id, enabled }), body: JSON.stringify({ id, enabled }),
@@ -156,7 +157,7 @@ export default function AdminPluginsPage() {
const body: Record<string, unknown> = { id, forceEnabled }; const body: Record<string, unknown> = { id, forceEnabled };
if (forceEnabled) body.enabled = true; if (forceEnabled) body.enabled = true;
const res = await fetch('/api/admin/plugins', { const res = await apiFetch('/api/admin/plugins', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body), body: JSON.stringify(body),
@@ -190,7 +191,7 @@ export default function AdminPluginsPage() {
} }
let failed = 0; let failed = 0;
for (const p of disabled) { for (const p of disabled) {
const res = await fetch('/api/admin/plugins', { const res = await apiFetch('/api/admin/plugins', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: p.id, enabled: true }), body: JSON.stringify({ id: p.id, enabled: true }),
@@ -216,7 +217,7 @@ export default function AdminPluginsPage() {
} }
let failed = 0; let failed = 0;
for (const p of enabled) { for (const p of enabled) {
const res = await fetch('/api/admin/plugins', { const res = await apiFetch('/api/admin/plugins', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: p.id, enabled: false }), body: JSON.stringify({ id: p.id, enabled: false }),
@@ -236,7 +237,7 @@ export default function AdminPluginsPage() {
if (!confirm(`Remove plugin "${name}"? This cannot be undone.`)) return; if (!confirm(`Remove plugin "${name}"? This cannot be undone.`)) return;
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/plugins', { const res = await apiFetch('/api/admin/plugins', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id }), body: JSON.stringify({ id }),
+3 -2
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { Save, Loader2, Lock } from 'lucide-react'; import { Save, Loader2, Lock } from 'lucide-react';
import type { SettingsPolicy, FeatureGates } from '@/lib/admin/types'; import type { SettingsPolicy, FeatureGates } from '@/lib/admin/types';
import { DEFAULT_FEATURE_GATES, DEFAULT_POLICY } from '@/lib/admin/types'; import { DEFAULT_FEATURE_GATES, DEFAULT_POLICY } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
// Feature gates managed on their own admin pages (excluded from this list) // Feature gates managed on their own admin pages (excluded from this list)
const EXCLUDED_FEATURE_GATES: (keyof FeatureGates)[] = ['pluginsEnabled', 'pluginsUploadEnabled', 'themesEnabled', 'userThemesEnabled']; const EXCLUDED_FEATURE_GATES: (keyof FeatureGates)[] = ['pluginsEnabled', 'pluginsUploadEnabled', 'themesEnabled', 'userThemesEnabled'];
@@ -54,7 +55,7 @@ export default function AdminPolicyPage() {
async function fetchPolicy() { async function fetchPolicy() {
setLoading(true); setLoading(true);
try { try {
const res = await fetch('/api/admin/policy'); const res = await apiFetch('/api/admin/policy');
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setPolicy(data); setPolicy(data);
@@ -106,7 +107,7 @@ export default function AdminPolicyPage() {
setSaving(true); setSaving(true);
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/policy', { const res = await apiFetch('/api/admin/policy', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(policy), body: JSON.stringify(policy),
+4 -3
View File
@@ -2,6 +2,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Save, RotateCcw, Loader2 } from 'lucide-react'; import { Save, RotateCcw, Loader2 } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigEntry { interface ConfigEntry {
value: unknown; value: unknown;
@@ -21,7 +22,7 @@ export default function AdminSettingsPage() {
async function fetchConfig() { async function fetchConfig() {
setLoading(true); setLoading(true);
const res = await fetch('/api/admin/config'); const res = await apiFetch('/api/admin/config');
if (res.ok) { if (res.ok) {
setConfig(await res.json()); setConfig(await res.json());
} }
@@ -43,7 +44,7 @@ export default function AdminSettingsPage() {
setSaving(true); setSaving(true);
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/config', { const res = await apiFetch('/api/admin/config', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(edits), body: JSON.stringify(edits),
@@ -61,7 +62,7 @@ export default function AdminSettingsPage() {
} }
async function handleRevert(key: string) { async function handleRevert(key: string) {
const res = await fetch('/api/admin/config', { const res = await apiFetch('/api/admin/config', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }), body: JSON.stringify({ key }),
+10 -9
View File
@@ -4,6 +4,7 @@ import { useEffect, useState, useRef } from 'react';
import { Upload, Trash2, Power, PowerOff, Loader2, Palette, Save, Shield, Lock, LockOpen } from 'lucide-react'; import { Upload, Trash2, Power, PowerOff, Loader2, Palette, Save, Shield, Lock, LockOpen } from 'lucide-react';
import type { SettingsPolicy } from '@/lib/admin/types'; import type { SettingsPolicy } from '@/lib/admin/types';
import { DEFAULT_POLICY, DEFAULT_THEME_POLICY } from '@/lib/admin/types'; import { DEFAULT_POLICY, DEFAULT_THEME_POLICY } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
const BUILTIN_THEME_OPTIONS = [ const BUILTIN_THEME_OPTIONS = [
{ id: 'builtin-nord', name: 'Nord' }, { id: 'builtin-nord', name: 'Nord' },
@@ -38,7 +39,7 @@ export default function AdminThemesPage() {
async function fetchPolicy() { async function fetchPolicy() {
try { try {
const res = await fetch('/api/admin/policy'); const res = await apiFetch('/api/admin/policy');
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setPolicy({ setPolicy({
@@ -122,7 +123,7 @@ export default function AdminThemesPage() {
setSavingPolicy(true); setSavingPolicy(true);
setMessage(null); setMessage(null);
try { try {
const res = await fetch('/api/admin/policy', { const res = await apiFetch('/api/admin/policy', {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(policy), body: JSON.stringify(policy),
@@ -144,7 +145,7 @@ export default function AdminThemesPage() {
async function fetchThemes() { async function fetchThemes() {
setLoading(true); setLoading(true);
try { try {
const res = await fetch('/api/admin/themes'); const res = await apiFetch('/api/admin/themes');
if (res.ok) setThemes(await res.json()); if (res.ok) setThemes(await res.json());
} finally { } finally {
setLoading(false); setLoading(false);
@@ -162,7 +163,7 @@ export default function AdminThemesPage() {
formData.append('file', file); formData.append('file', file);
try { try {
const res = await fetch('/api/admin/themes', { const res = await apiFetch('/api/admin/themes', {
method: 'POST', method: 'POST',
body: formData, body: formData,
}); });
@@ -185,7 +186,7 @@ export default function AdminThemesPage() {
async function toggleTheme(id: string, enabled: boolean) { async function toggleTheme(id: string, enabled: boolean) {
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/themes', { const res = await apiFetch('/api/admin/themes', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id, enabled }), body: JSON.stringify({ id, enabled }),
@@ -204,7 +205,7 @@ export default function AdminThemesPage() {
const body: Record<string, unknown> = { id, forceEnabled }; const body: Record<string, unknown> = { id, forceEnabled };
if (forceEnabled) body.enabled = true; if (forceEnabled) body.enabled = true;
const res = await fetch('/api/admin/themes', { const res = await apiFetch('/api/admin/themes', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body), body: JSON.stringify(body),
@@ -237,7 +238,7 @@ export default function AdminThemesPage() {
} }
let failed = 0; let failed = 0;
for (const t of disabled) { for (const t of disabled) {
const res = await fetch('/api/admin/themes', { const res = await apiFetch('/api/admin/themes', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: t.id, enabled: true }), body: JSON.stringify({ id: t.id, enabled: true }),
@@ -262,7 +263,7 @@ export default function AdminThemesPage() {
} }
let failed = 0; let failed = 0;
for (const t of enabled) { for (const t of enabled) {
const res = await fetch('/api/admin/themes', { const res = await apiFetch('/api/admin/themes', {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: t.id, enabled: false }), body: JSON.stringify({ id: t.id, enabled: false }),
@@ -282,7 +283,7 @@ export default function AdminThemesPage() {
if (!confirm(`Remove theme "${name}"? This cannot be undone.`)) return; if (!confirm(`Remove theme "${name}"? This cannot be undone.`)) return;
setMessage(null); setMessage(null);
const res = await fetch('/api/admin/themes', { const res = await apiFetch('/api/admin/themes', {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id }), body: JSON.stringify({ id }),
+2 -1
View File
@@ -11,6 +11,7 @@ import { getEventStartDate } from "@/lib/calendar-utils";
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import { useSettingsStore } from "@/stores/settings-store"; import { useSettingsStore } from "@/stores/settings-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import { apiFetch } from "@/lib/browser-navigation";
interface ICalImportModalProps { interface ICalImportModalProps {
calendars: Calendar[]; calendars: Calendar[];
@@ -126,7 +127,7 @@ export function ICalImportModal({ calendars, client, onClose }: ICalImportModalP
setIsParsing(true); setIsParsing(true);
try { try {
const response = await fetch("/api/fetch-ical", { const response = await apiFetch("/api/fetch-ical", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: trimmed }), body: JSON.stringify({ url: trimmed }),
+3 -2
View File
@@ -22,6 +22,7 @@ import { getInitials } from "@/lib/account-utils";
import { cn, formatFileSize } from "@/lib/utils"; import { cn, formatFileSize } from "@/lib/utils";
import { PluginSlot } from "@/components/plugins/plugin-slot"; import { PluginSlot } from "@/components/plugins/plugin-slot";
import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal"; import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal";
import { apiFetch } from "@/lib/browser-navigation";
interface NavItem { interface NavItem {
id: string; id: string;
@@ -222,13 +223,13 @@ export function NavigationRail({
let cancelled = false; let cancelled = false;
const headers = getActiveAccountSlotHeaders(); const headers = getActiveAccountSlotHeaders();
if (!headers['X-JMAP-Cookie-Slot']) return; if (!headers['X-JMAP-Cookie-Slot']) return;
fetch('/api/admin/stalwart-check', { headers }) apiFetch('/api/admin/stalwart-check', { headers })
.then(res => res.json()) .then(res => res.json())
.then(data => { .then(data => {
if (!cancelled && data.isStalwartAdmin) { if (!cancelled && data.isStalwartAdmin) {
setIsStalwartAdmin(true); setIsStalwartAdmin(true);
// Pre-create admin session so /admin works even after full page navigation // Pre-create admin session so /admin works even after full page navigation
fetch('/api/admin/auth', { apiFetch('/api/admin/auth', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers }, headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify({ stalwartAuth: true }), body: JSON.stringify({ stalwartAuth: true }),
@@ -12,6 +12,7 @@ import { cn, formatDateTime } from '@/lib/utils';
import { ICalImportModal } from '@/components/calendar/ical-import-modal'; import { ICalImportModal } from '@/components/calendar/ical-import-modal';
import { ICalSubscriptionModal } from '@/components/calendar/ical-subscription-modal'; import { ICalSubscriptionModal } from '@/components/calendar/ical-subscription-modal';
import { useSettingsStore } from '@/stores/settings-store'; import { useSettingsStore } from '@/stores/settings-store';
import { apiFetch } from '@/lib/browser-navigation';
const CALENDAR_COLORS = [ const CALENDAR_COLORS = [
"#3b82f6", // blue "#3b82f6", // blue
@@ -202,7 +203,7 @@ export function CalendarManagementSettings() {
const controller = new AbortController(); const controller = new AbortController();
fetch('/api/caldav/discover', { apiFetch('/api/caldav/discover', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
+2 -1
View File
@@ -2,6 +2,7 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { usePolicyStore } from '@/stores/policy-store'; import { usePolicyStore } from '@/stores/policy-store';
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigData { interface ConfigData {
appName: string; appName: string;
@@ -50,7 +51,7 @@ export async function fetchConfig(): Promise<ConfigData> {
} }
// Start a new fetch // Start a new fetch
configPromise = fetch('/api/config') configPromise = apiFetch('/api/config')
.then((res) => { .then((res) => {
if (!res.ok) { if (!res.ok) {
throw new Error('Failed to fetch config'); throw new Error('Failed to fetch config');
+29
View File
@@ -36,6 +36,35 @@ export function getPathPrefix(locale?: string): string {
return '/' + segments.slice(0, localeIndex).join('/'); return '/' + segments.slice(0, localeIndex).join('/');
} }
/**
* Mount-prefix-aware wrapper around `fetch()`.
*
* When Bulwark is served behind a reverse proxy at a sub-path (e.g. `/bulwark`),
* `fetch('/api/foo')` would target the browser origin at `/api/foo`, which the
* proxy doesn't route. `apiFetch` detects the mount prefix from
* `window.location.pathname` via `getPathPrefix()` at call time, so the same
* built bundle works at any mount point without rebuilding.
*
* Only rewrites absolute paths that start with a single `/`. Protocol-relative
* URLs (`//cdn.example.com/foo`) and absolute URLs (`https://...`) pass
* through unchanged.
*
* Server code (route handlers, layout files running at SSR) should keep using
* the raw Fetch API — the mount prefix is a browser-only concept.
*
* @example
* await apiFetch('/api/jmap', { method: 'POST', body })
* // Browser at /webmail/en/inbox → /webmail/api/jmap
* // Browser at /en/inbox → /api/jmap
*/
export function apiFetch(input: string, init?: RequestInit): Promise<Response> {
if (input.startsWith('/') && !input.startsWith('//')) {
return fetch(getPathPrefix() + input, init);
}
return fetch(input, init);
}
/** /**
* Extracts the locale from the current URL, skipping any mount prefix. * Extracts the locale from the current URL, skipping any mount prefix.
* Falls back to 'en' when no known locale segment is found. * Falls back to 'en' when no known locale segment is found.
+5 -4
View File
@@ -26,6 +26,7 @@ import {
} from './plugin-hooks'; } from './plugin-hooks';
import { toast as appToast } from '@/stores/toast-store'; import { toast as appToast } from '@/stores/toast-store';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { apiFetch } from '@/lib/browser-navigation';
// --- Permission helpers -------------------------------------- // --- Permission helpers --------------------------------------
@@ -682,20 +683,20 @@ export function createPluginAPI(plugin: InstalledPlugin): PluginAPI {
admin: { admin: {
getConfig: async (key: string) => { getConfig: async (key: string) => {
requirePermission(plugin, 'admin:config'); requirePermission(plugin, 'admin:config');
const res = await fetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`); const res = await apiFetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`);
if (!res.ok) return null; if (!res.ok) return null;
const data = await res.json(); const data = await res.json();
return data[key] ?? null; return data[key] ?? null;
}, },
getAllConfig: async () => { getAllConfig: async () => {
requirePermission(plugin, 'admin:config'); requirePermission(plugin, 'admin:config');
const res = await fetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`); const res = await apiFetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`);
if (!res.ok) return {}; if (!res.ok) return {};
return res.json(); return res.json();
}, },
setConfig: async (key: string, value: unknown) => { setConfig: async (key: string, value: unknown) => {
requirePermission(plugin, 'admin:config'); requirePermission(plugin, 'admin:config');
await fetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`, { await apiFetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`, {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value }), body: JSON.stringify({ key, value }),
@@ -703,7 +704,7 @@ export function createPluginAPI(plugin: InstalledPlugin): PluginAPI {
}, },
deleteConfig: async (key: string) => { deleteConfig: async (key: string) => {
requirePermission(plugin, 'admin:config'); requirePermission(plugin, 'admin:config');
await fetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`, { await apiFetch(`/api/admin/plugins/${encodeURIComponent(plugin.id)}/config`, {
method: 'DELETE', method: 'DELETE',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }), body: JSON.stringify({ key }),
+12 -11
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand'; import { create } from 'zustand';
import { debug } from '@/lib/debug'; import { debug } from '@/lib/debug';
import { getActiveAccountSlotHeaders } from '@/lib/auth/active-account-slot'; import { getActiveAccountSlotHeaders } from '@/lib/auth/active-account-slot';
import { apiFetch } from '@/lib/browser-navigation';
interface AccountSecurityState { interface AccountSecurityState {
// Detection // Detection
@@ -66,7 +67,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
probe: async () => { probe: async () => {
set({ isProbing: true }); set({ isProbing: true });
try { try {
const response = await fetch('/api/account/stalwart/probe', { const response = await apiFetch('/api/account/stalwart/probe', {
headers: getApiHeaders(), headers: getApiHeaders(),
}); });
const data = await response.json(); const data = await response.json();
@@ -83,7 +84,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
fetchAuthInfo: async () => { fetchAuthInfo: async () => {
set({ isLoadingAuth: true, error: null }); set({ isLoadingAuth: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/auth', { const response = await apiFetch('/api/account/stalwart/auth', {
headers: getApiHeaders(), headers: getApiHeaders(),
}); });
if (!response.ok) throw new Error(`HTTP ${response.status}`); if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -105,7 +106,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
fetchCryptoInfo: async () => { fetchCryptoInfo: async () => {
set({ isLoadingCrypto: true, error: null }); set({ isLoadingCrypto: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/crypto', { const response = await apiFetch('/api/account/stalwart/crypto', {
headers: getApiHeaders(), headers: getApiHeaders(),
}); });
if (!response.ok) throw new Error(`HTTP ${response.status}`); if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -126,7 +127,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
fetchPrincipal: async () => { fetchPrincipal: async () => {
set({ isLoadingPrincipal: true, error: null }); set({ isLoadingPrincipal: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/principal', { const response = await apiFetch('/api/account/stalwart/principal', {
headers: getApiHeaders(), headers: getApiHeaders(),
}); });
if (!response.ok) { if (!response.ok) {
@@ -169,7 +170,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
changePassword: async (currentPassword, newPassword) => { changePassword: async (currentPassword, newPassword) => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/password', { const response = await apiFetch('/api/account/stalwart/password', {
method: 'POST', method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ currentPassword, newPassword }), body: JSON.stringify({ currentPassword, newPassword }),
@@ -193,7 +194,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
updateDisplayName: async (displayName) => { updateDisplayName: async (displayName) => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/principal', { const response = await apiFetch('/api/account/stalwart/principal', {
method: 'PATCH', method: 'PATCH',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([ body: JSON.stringify([
@@ -219,7 +220,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
enableTotp: async () => { enableTotp: async () => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/auth', { const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST', method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'enableOtpAuth' }]), body: JSON.stringify([{ type: 'enableOtpAuth' }]),
@@ -245,7 +246,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
disableTotp: async () => { disableTotp: async () => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/auth', { const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST', method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'disableOtpAuth' }]), body: JSON.stringify([{ type: 'disableOtpAuth' }]),
@@ -269,7 +270,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
addAppPassword: async (name, password) => { addAppPassword: async (name, password) => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/auth', { const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST', method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'addAppPassword', name, password }]), body: JSON.stringify([{ type: 'addAppPassword', name, password }]),
@@ -295,7 +296,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
removeAppPassword: async (name) => { removeAppPassword: async (name) => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/auth', { const response = await apiFetch('/api/account/stalwart/auth', {
method: 'POST', method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify([{ type: 'removeAppPassword', name }]), body: JSON.stringify([{ type: 'removeAppPassword', name }]),
@@ -321,7 +322,7 @@ export const useAccountSecurityStore = create<AccountSecurityState>()((set, get)
updateEncryption: async (settings) => { updateEncryption: async (settings) => {
set({ isSaving: true, error: null }); set({ isSaving: true, error: null });
try { try {
const response = await fetch('/api/account/stalwart/crypto', { const response = await apiFetch('/api/account/stalwart/crypto', {
method: 'POST', method: 'POST',
headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, headers: { ...getApiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(settings), body: JSON.stringify(settings),
+20 -20
View File
@@ -12,7 +12,7 @@ import { useAccountStore } from './account-store';
import { fetchConfig } from '@/hooks/use-config'; import { fetchConfig } from '@/hooks/use-config';
import { debug } from '@/lib/debug'; import { debug } from '@/lib/debug';
import { generateAccountId } from '@/lib/account-utils'; 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 { notifyParent } from '@/lib/iframe-bridge';
import { snapshotAccount, restoreAccount, clearAllStores, evictAccount, evictAll } from '@/lib/account-state-manager'; import { snapshotAccount, restoreAccount, clearAllStores, evictAccount, evictAll } from '@/lib/account-state-manager';
import type { Identity } from '@/lib/jmap/types'; import type { Identity } from '@/lib/jmap/types';
@@ -95,7 +95,7 @@ async function syncStalwartAuthContext(
slot: number, slot: number,
): Promise<void> { ): Promise<void> {
try { try {
const response = await fetch('/api/auth/stalwart-context', { const response = await apiFetch('/api/auth/stalwart-context', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverUrl, username, authHeader, slot }), body: JSON.stringify({ serverUrl, username, authHeader, slot }),
@@ -403,7 +403,7 @@ export const useAuthStore = create<AuthState>()(
if (totp) { if (totp) {
try { try {
const tokenRes = await fetch('/api/auth/totp-token-exchange', { const tokenRes = await apiFetch('/api/auth/totp-token-exchange', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }), body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }),
@@ -470,7 +470,7 @@ export const useAuthStore = create<AuthState>()(
if (rememberMe && !upgradedToOAuth) { if (rememberMe && !upgradedToOAuth) {
// For basic auth (no TOTP or TOTP upgrade failed), store encrypted credentials // For basic auth (no TOTP or TOTP upgrade failed), store encrypted credentials
try { try {
const res = await fetch(`/api/auth/session?slot=${cookieSlot}`, { const res = await apiFetch(`/api/auth/session?slot=${cookieSlot}`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }), body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }),
@@ -607,7 +607,7 @@ export const useAuthStore = create<AuthState>()(
: 0; : 0;
const slot = pendingSlot >= 0 && pendingSlot <= 4 ? pendingSlot : accountStore.getNextCookieSlot(); 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', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, code_verifier: codeVerifier, redirect_uri: redirectUri, slot }), body: JSON.stringify({ code, code_verifier: codeVerifier, redirect_uri: redirectUri, slot }),
@@ -718,7 +718,7 @@ export const useAuthStore = create<AuthState>()(
try { try {
// Server-side SSO: the server holds the PKCE verifier in an encrypted cookie // 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', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
credentials: 'include', credentials: 'include',
@@ -841,7 +841,7 @@ export const useAuthStore = create<AuthState>()(
const promise = (async () => { const promise = (async () => {
try { 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) { if (!res.ok) {
notifyParent('sso:session-expired'); notifyParent('sso:session-expired');
@@ -963,9 +963,9 @@ export const useAuthStore = create<AuthState>()(
} }
// Background cookie cleanup for the removed account // 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) { 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; return;
} }
@@ -977,9 +977,9 @@ export const useAuthStore = create<AuthState>()(
// Background cookie/token cleanup — keepalive ensures completion during navigation // Background cookie/token cleanup — keepalive ensures completion during navigation
if (!wasDemoMode) { 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) { 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 // Background cookie/token cleanup
fetch('/api/auth/session?all=true', { method: 'DELETE', keepalive: true }).catch(() => {}); apiFetch('/api/auth/session?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
fetch('/api/auth/token?all=true', { method: 'DELETE', keepalive: true }).catch(() => {}); apiFetch('/api/auth/token?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
redirectToLogin(); redirectToLogin();
}, },
@@ -1041,7 +1041,7 @@ export const useAuthStore = create<AuthState>()(
// Client not connected — try to restore // Client not connected — try to restore
try { try {
if (targetAccount.authMode === 'oauth') { 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) { if (res.ok) {
const { access_token, expires_in } = await res.json(); const { access_token, expires_in } = await res.json();
const refreshFn = get().refreshAccessToken; const refreshFn = get().refreshAccessToken;
@@ -1058,7 +1058,7 @@ export const useAuthStore = create<AuthState>()(
); );
} }
} else if (targetAccount.authMode === 'basic' && targetAccount.rememberMe) { } 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) { if (res.ok) {
const { serverUrl, username, password } = await res.json(); const { serverUrl, username, password } = await res.json();
targetClient = new JMAPClient(serverUrl, username, password); 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 // Cannot restore — remove the stale account and redirect to login
evictAccount(accountId); evictAccount(accountId);
accountStore.removeAccount(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 // Restore the previous account if still available
if (state.activeAccountId && state.activeAccountId !== accountId) { if (state.activeAccountId && state.activeAccountId !== accountId) {
@@ -1210,7 +1210,7 @@ export const useAuthStore = create<AuthState>()(
try { try {
if (account.authMode === 'oauth') { 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) { if (res.ok) {
const { access_token, expires_in } = await res.json(); const { access_token, expires_in } = await res.json();
const refreshFn = get().refreshAccessToken; const refreshFn = get().refreshAccessToken;
@@ -1225,7 +1225,7 @@ export const useAuthStore = create<AuthState>()(
throw new Error(`Token refresh failed: ${res.status}`); throw new Error(`Token refresh failed: ${res.status}`);
} }
} else if (account.authMode === 'basic' && account.rememberMe) { } 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) { if (res.ok) {
const { serverUrl, username, password } = await res.json(); const { serverUrl, username, password } = await res.json();
const client = new JMAPClient(serverUrl, username, password); 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. // again rather than seeing a stale error entry forever.
evictAccount(account.id); evictAccount(account.id);
accountStore.removeAccount(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') { if (state.authMode === 'basic') {
set({ isLoading: true, isRateLimited: false, rateLimitUntil: null }); set({ isLoading: true, isRateLimited: false, rateLimitUntil: null });
try { try {
const res = await fetch('/api/auth/session', { method: 'PUT' }); const res = await apiFetch('/api/auth/session', { method: 'PUT' });
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
if (!data.serverUrl || !data.username || !data.password) { 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 { sanitizeOutgoingCalendarEventData } from '@/lib/calendar-event-normalization';
import { expandRecurringEvents } from '@/lib/recurrence-expansion'; import { expandRecurringEvents } from '@/lib/recurrence-expansion';
import { generateUUID } from '@/lib/utils'; import { generateUUID } from '@/lib/utils';
import { apiFetch } from '@/lib/browser-navigation';
export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda' | 'tasks'; export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda' | 'tasks';
@@ -809,7 +810,7 @@ export const useCalendarStore = create<CalendarStore>()(
if (!sub) return; if (!sub) return;
try { try {
const response = await fetch('/api/fetch-ical', { const response = await apiFetch('/api/fetch-ical', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: sub.url }), 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 { setSlotRegistrationBridge } from '@/lib/plugin-api';
import { removeAllPluginHooks } from '@/lib/plugin-hooks'; import { removeAllPluginHooks } from '@/lib/plugin-hooks';
import { usePolicyStore } from '@/stores/policy-store'; import { usePolicyStore } from '@/stores/policy-store';
import { apiFetch } from '@/lib/browser-navigation';
// ─── Slot State ────────────────────────────────────────────── // ─── Slot State ──────────────────────────────────────────────
@@ -363,7 +364,7 @@ async function syncServerPlugins(
set: (partial: Partial<PluginStoreState> | ((state: PluginStoreState) => Partial<PluginStoreState>)) => void, set: (partial: Partial<PluginStoreState> | ((state: PluginStoreState) => Partial<PluginStoreState>)) => void,
): Promise<void> { ): Promise<void> {
try { try {
const res = await fetch('/api/plugins'); const res = await apiFetch('/api/plugins');
if (!res.ok) return; if (!res.ok) return;
const data: { plugins: ServerPluginInfo[] } = await res.json(); const data: { plugins: ServerPluginInfo[] } = await res.json();
@@ -484,7 +485,7 @@ async function syncServerPlugins(
async function downloadPluginBundle(pluginId: string): Promise<string | null> { async function downloadPluginBundle(pluginId: string): Promise<string | null> {
try { 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; if (!res.ok) return null;
return await res.text(); return await res.text();
} catch { } catch {
+2 -1
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand'; import { create } from 'zustand';
import type { SettingsPolicy, FeatureGates, SettingRestriction, ThemePolicy } from '@/lib/admin/types'; import type { SettingsPolicy, FeatureGates, SettingRestriction, ThemePolicy } from '@/lib/admin/types';
import { DEFAULT_POLICY, DEFAULT_THEME_POLICY } from '@/lib/admin/types'; import { DEFAULT_POLICY, DEFAULT_THEME_POLICY } from '@/lib/admin/types';
import { apiFetch } from '@/lib/browser-navigation';
interface PolicyState { interface PolicyState {
policy: SettingsPolicy; policy: SettingsPolicy;
@@ -25,7 +26,7 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({
fetchPolicy: async () => { fetchPolicy: async () => {
try { try {
const res = await fetch('/api/admin/policy'); const res = await apiFetch('/api/admin/policy');
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
set({ policy: data, loaded: true }); set({ policy: data, loaded: true });
+3 -2
View File
@@ -3,6 +3,7 @@ import { persist } from 'zustand/middleware';
import { useThemeStore } from './theme-store'; import { useThemeStore } from './theme-store';
import { useLocaleStore } from './locale-store'; import { useLocaleStore } from './locale-store';
import type { NotificationSoundChoice } from '@/lib/notification-sound'; import type { NotificationSoundChoice } from '@/lib/notification-sound';
import { apiFetch } from '@/lib/browser-navigation';
// Use console directly to avoid circular dependency with lib/debug.ts // Use console directly to avoid circular dependency with lib/debug.ts
// (debug.ts imports useSettingsStore for debugMode check) // (debug.ts imports useSettingsStore for debugMode check)
@@ -611,7 +612,7 @@ export const useSettingsStore = create<SettingsState>()(
loadFromServer: async (username: string, serverUrl: string) => { loadFromServer: async (username: string, serverUrl: string) => {
try { try {
syncLog('Loading settings from server for', username); syncLog('Loading settings from server for', username);
const res = await fetch('/api/settings', { const res = await apiFetch('/api/settings', {
headers: { headers: {
'x-settings-username': username, 'x-settings-username': username,
'x-settings-server': serverUrl, 'x-settings-server': serverUrl,
@@ -747,7 +748,7 @@ if (typeof window !== 'undefined') {
const syncToServer = async (retries = 1): Promise<void> => { const syncToServer = async (retries = 1): Promise<void> => {
const settings = JSON.parse(useSettingsStore.getState().exportSettings()); const settings = JSON.parse(useSettingsStore.getState().exportSettings());
syncLog('Syncing settings to server...'); syncLog('Syncing settings to server...');
const res = await fetch('/api/settings', { const res = await apiFetch('/api/settings', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: syncUsername, serverUrl: syncServerUrl, settings }), 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 { extractTheme } from '@/lib/plugin-validator';
import { BUILTIN_THEMES } from '@/lib/builtin-themes'; import { BUILTIN_THEMES } from '@/lib/builtin-themes';
import { usePolicyStore } from '@/stores/policy-store'; import { usePolicyStore } from '@/stores/policy-store';
import { apiFetch } from '@/lib/browser-navigation';
type Theme = 'light' | 'dark' | 'system'; type Theme = 'light' | 'dark' | 'system';
@@ -299,7 +300,7 @@ export const useThemeStore = create<ThemeState>()(
themeSyncPromise = (async () => { themeSyncPromise = (async () => {
try { try {
const res = await fetch('/api/plugins'); const res = await apiFetch('/api/plugins');
if (!res.ok) return; if (!res.ok) return;
const data: { themes: ServerThemeInfo[] } = await res.json(); const data: { themes: ServerThemeInfo[] } = await res.json();
@@ -480,7 +481,7 @@ function dedupeInstalledThemes(themes: InstalledTheme[]): InstalledTheme[] {
async function downloadThemeCSS(themeId: string): Promise<string | null> { async function downloadThemeCSS(themeId: string): Promise<string | null> {
try { 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; if (!res.ok) return null;
return await res.text(); return await res.text();
} catch { } catch {