Merge dev into main - version 1.4.7

This commit is contained in:
Linus Rath
2026-03-21 20:46:33 +01:00
72 changed files with 4350 additions and 638 deletions
+4 -1
View File
@@ -64,7 +64,10 @@ JMAP_SERVER_URL=https://your-jmap-server.com
# SETTINGS_SYNC_ENABLED=true
# Directory for storing encrypted settings files (default: ./data/settings).
# For Docker, mount a persistent volume at this path.
# For Docker, the working directory is /app, so the default resolves to
# /app/data/settings — mount a persistent volume there:
# volumes:
# - bulwark-settings:/app/data/settings
# SETTINGS_DATA_DIR=./data/settings
# =============================================================================
+21
View File
@@ -1,5 +1,26 @@
# Changelog
## 1.4.7 (2026-03-21)
### Features
- **Calendar**: Add task management features with task creation, editing, and status tracking
- **Calendar**: Add option to show week numbers in mini-calendar
- **Email**: Add resizable image component and rich text editor with image upload support
- **Files**: Support uploading folders via drag-and-drop and toolbar button
- **Filters**: Add expanded visual view for filter rules
- **Auth**: Add non-interactive SSO login flow for embedded/iframe deployments (#69)
- **DevOps**: Add separate Docker build workflow for releases and dev branch images
### Fixes
- **Calendar**: Handle updates and deletions for synthetic JMAP IDs in calendar events with fallback to destroy and recreate
- **Security**: Extend CryptoEngine to support legacy algorithms and integrate with LinerEngine for decryption
- **Auth**: Refactor logout to use synchronous flow with full page redirect
- **Email**: Update iframe sandbox attributes to allow popups to escape sandbox
- **i18n**: Add missing translation keys across all locales
- **Docker**: Update .env.example to clarify Docker volume mounting for settings data directory
## 1.4.6 (2026-03-21)
### Features
+1 -1
View File
@@ -12,7 +12,7 @@ A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.ar
Built with Next.js and the JMAP protocol.
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-1.4.6-green.svg)](CHANGELOG.md)
[![Version](https://img.shields.io/badge/version-1.4.7-green.svg)](CHANGELOG.md)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fbulwarkmail%2Fwebmail-blue)](https://ghcr.io/bulwarkmail/webmail)
</div>
+1 -1
View File
@@ -1 +1 @@
1.4.6
1.4.7
+61 -34
View File
@@ -13,7 +13,7 @@ function OAuthCallbackInner() {
const params = useParams();
const searchParams = useSearchParams();
const t = useTranslations("login");
const { loginWithOAuth } = useAuthStore();
const { loginWithOAuth, loginWithServerSso } = useAuthStore();
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -32,44 +32,71 @@ function OAuthCallbackInner() {
}
const savedState = sessionStorage.getItem("oauth_state");
if (!state || state !== savedState) {
setError("invalid_state");
return;
}
const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
const serverUrl = sessionStorage.getItem("oauth_server_url");
if (savedState) {
// Classic flow — sessionStorage has the PKCE state (same-tab OAuth)
if (!state || state !== savedState) {
setError("invalid_state");
return;
}
if (!codeVerifier || !serverUrl) {
setError("missing_params");
return;
}
const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
const serverUrl = sessionStorage.getItem("oauth_server_url");
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
if (!codeVerifier || !serverUrl) {
setError("missing_params");
return;
}
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
.then((success) => {
if (success) {
sessionStorage.removeItem("oauth_state");
sessionStorage.removeItem("oauth_code_verifier");
sessionStorage.removeItem("oauth_server_url");
sessionStorage.removeItem("oauth_add_account_mode");
let redirectTo = `/${params.locale}`;
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* sessionStorage may be unavailable */ }
router.push(redirectTo);
} else {
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
.then((success) => {
if (success) {
sessionStorage.removeItem("oauth_state");
sessionStorage.removeItem("oauth_code_verifier");
sessionStorage.removeItem("oauth_server_url");
sessionStorage.removeItem("oauth_add_account_mode");
let redirectTo = `/${params.locale}`;
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* sessionStorage may be unavailable */ }
router.push(redirectTo);
} else {
setError("token_exchange_failed");
}
})
.catch(() => {
setError("token_exchange_failed");
}
})
.catch(() => {
setError("token_exchange_failed");
});
});
} else if (state) {
// Server-side SSO flow — state was stored in encrypted httpOnly cookie
loginWithServerSso(code, state)
.then((success) => {
if (success) {
let redirectTo = `/${params.locale}`;
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* sessionStorage may be unavailable */ }
router.push(redirectTo);
} else {
setError("token_exchange_failed");
}
})
.catch(() => {
setError("token_exchange_failed");
});
} else {
setError("invalid_state");
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
if (error) {
+128 -8
View File
@@ -11,7 +11,7 @@ import {
} from "date-fns";
import { useCalendarStore } from "@/stores/calendar-store";
import { isCalendarViewMode } from "@/stores/calendar-store";
import { useAuthStore } from "@/stores/auth-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store";
import { useIdentityStore } from "@/stores/identity-store";
@@ -23,6 +23,9 @@ import { CalendarMonthView } from "@/components/calendar/calendar-month-view";
import { CalendarWeekView } from "@/components/calendar/calendar-week-view";
import { CalendarDayView } from "@/components/calendar/calendar-day-view";
import { CalendarAgendaView } from "@/components/calendar/calendar-agenda-view";
import { TaskListView } from "@/components/calendar/task-list-view";
import { TaskToolbar } from "@/components/calendar/task-toolbar";
import { TaskModal } from "@/components/calendar/task-modal";
import { MiniCalendar } from "@/components/calendar/mini-calendar";
import { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-panel";
import { EventModal, type PendingEventPreview } from "@/components/calendar/event-modal";
@@ -35,6 +38,7 @@ import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
import { InlineAppView } from "@/components/layout/inline-app-view";
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { useTaskStore } from "@/stores/task-store";
import { cn } from "@/lib/utils";
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
import { getUserParticipantId } from "@/lib/calendar-participants";
@@ -63,7 +67,8 @@ export default function CalendarPage() {
setSelectedDate, setViewMode, toggleCalendarVisibility, updateCalendar,
refreshAllSubscriptions,
} = useCalendarStore();
const { firstDayOfWeek, timeFormat } = useSettingsStore();
const { firstDayOfWeek, timeFormat, showWeekNumbers, enableCalendarTasks, showTasksOnCalendar } = useSettingsStore();
const taskStore = useTaskStore();
const { identities } = useIdentityStore();
const normalizedViewMode = isCalendarViewMode(viewMode) ? viewMode : "month";
@@ -83,6 +88,8 @@ export default function CalendarPage() {
const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null);
const [detailAnchorRect, setDetailAnchorRect] = useState<DOMRect | null>(null);
const [pendingPreview, setPendingPreview] = useState<PendingEventPreview | null>(null);
const [showTaskModal, setShowTaskModal] = useState(false);
const [editTask, setEditTask] = useState<import("@/lib/jmap/types").CalendarTask | null>(null);
const hasFetched = useRef(false);
// Sidebar resize state
@@ -105,7 +112,7 @@ export default function CalendarPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login");
redirectToLogin();
} else if (client && !supportsCalendar) {
router.push("/");
}
@@ -166,9 +173,18 @@ export default function CalendarPage() {
end: format(addDays(agendaStart, 30), "yyyy-MM-dd'T'23:59:59"),
};
}
case "tasks":
return null;
}
}, [selectedDate, normalizedViewMode, firstDayOfWeek]);
// Fetch tasks when tasks view is active or when tasks are shown on calendar grid
useEffect(() => {
if (client && enableCalendarTasks && (normalizedViewMode === "tasks" || showTasksOnCalendar)) {
taskStore.fetchTasks(client);
}
}, [client, enableCalendarTasks, normalizedViewMode, showTasksOnCalendar]);
useEffect(() => {
if (client && calendars.length > 0 && dateRange) {
fetchEvents(client, dateRange.start, dateRange.end);
@@ -182,6 +198,7 @@ export default function CalendarPage() {
case "week": next = subWeeks(selectedDate, 1); break;
case "day": next = subDays(selectedDate, 1); break;
case "agenda": next = subMonths(selectedDate, 1); break;
case "tasks": return;
}
setSelectedDate(next);
setMiniMonth(next);
@@ -194,6 +211,7 @@ export default function CalendarPage() {
case "week": next = addWeeks(selectedDate, 1); break;
case "day": next = addDays(selectedDate, 1); break;
case "agenda": next = addMonths(selectedDate, 1); break;
case "tasks": return;
}
setSelectedDate(next);
setMiniMonth(next);
@@ -254,6 +272,34 @@ export default function CalendarPage() {
setShowEventModal(true);
}, []);
const openCreateTaskModal = useCallback(() => {
setEditTask(null);
setShowTaskModal(true);
}, []);
const openEditTaskModal = useCallback((task: import("@/lib/jmap/types").CalendarTask) => {
setEditTask(task);
setShowTaskModal(true);
}, []);
const handleSaveTask = useCallback(async (data: Partial<import("@/lib/jmap/types").CalendarTask>) => {
if (!client) return;
if (editTask) {
await taskStore.updateTask(client, editTask.id, data);
} else {
await taskStore.createTask(client, data);
}
setShowTaskModal(false);
setEditTask(null);
}, [client, editTask, taskStore]);
const handleDeleteTask = useCallback(async (id: string) => {
if (!client) return;
await taskStore.deleteTask(client, id);
setShowTaskModal(false);
setEditTask(null);
}, [client, taskStore]);
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeDetail = useCallback(() => {
@@ -424,9 +470,22 @@ export default function CalendarPage() {
try {
if (type === "edit" && updates) {
switch (scope) {
case "this":
await updateEvent(client, event.id, updates, sendScheduling);
case "this": {
// Synthetic IDs (from expandRecurrences) can't be updated directly.
// Patch the master event's recurrenceOverrides instead.
const master = await findMasterEvent(event);
if (master && event.recurrenceId) {
const patchUpdates: Record<string, unknown> = {};
for (const [key, value] of Object.entries(updates)) {
if (['id', 'uid', '@type', 'calendarIds', 'recurrenceRules', 'recurrenceOverrides', 'excludedRecurrenceRules'].includes(key)) continue;
patchUpdates[`recurrenceOverrides/${event.recurrenceId}/${key}`] = value;
}
await updateEvent(client, master.id, patchUpdates as Partial<CalendarEvent>, sendScheduling);
} else {
await updateEvent(client, event.id, updates, sendScheduling);
}
break;
}
case "this_and_future": {
const result = await truncateRecurrenceAtEvent(event);
if (!result) {
@@ -484,9 +543,20 @@ export default function CalendarPage() {
toast.success(t("notifications.event_updated"));
} else {
switch (scope) {
case "this":
await deleteEvent(client, event.id, sendScheduling);
case "this": {
// Synthetic IDs (from expandRecurrences) can't be destroyed directly.
// Exclude the instance via recurrenceOverrides on the master event.
const delMaster = await findMasterEvent(event);
if (delMaster && event.recurrenceId) {
await updateEvent(
client, delMaster.id,
{ [`recurrenceOverrides/${event.recurrenceId}`]: { excluded: true } } as Partial<CalendarEvent>,
);
} else {
await deleteEvent(client, event.id, sendScheduling);
}
break;
}
case "this_and_future": {
const result = await truncateRecurrenceAtEvent(event);
if (!result) {
@@ -598,6 +668,7 @@ export default function CalendarPage() {
const handleKey = (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return;
if (target.getAttribute("contenteditable") === "true") return;
if (showEventModal || detailEvent) return;
switch (e.key) {
@@ -608,6 +679,7 @@ export default function CalendarPage() {
case "w": setViewMode("week"); break;
case "d": setViewMode("day"); break;
case "a": setViewMode("agenda"); break;
case "k": if (enableCalendarTasks) setViewMode("tasks"); break;
case "n": openCreateModal(); break;
}
};
@@ -668,6 +740,8 @@ export default function CalendarPage() {
timeFormat={timeFormat}
isMobile={isMobile}
pendingPreview={pendingPreview}
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
/>
);
case "day":
@@ -683,6 +757,8 @@ export default function CalendarPage() {
timeFormat={timeFormat}
isMobile={isMobile}
pendingPreview={pendingPreview}
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
/>
);
case "agenda":
@@ -697,6 +773,33 @@ export default function CalendarPage() {
timeFormat={timeFormat}
/>
);
case "tasks":
return (
<div className="flex flex-col h-full">
<TaskToolbar
filter={taskStore.filter}
showCompleted={taskStore.showCompleted}
onFilterChange={taskStore.setFilter}
onShowCompletedChange={taskStore.setShowCompleted}
onCreateTask={openCreateTaskModal}
/>
<TaskListView
tasks={taskStore.tasks}
calendars={calendars}
selectedCalendarIds={selectedCalendarIds}
filter={taskStore.filter}
showCompleted={taskStore.showCompleted}
onSelectTask={openEditTaskModal}
onToggleComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
selectedTaskId={taskStore.selectedTaskId}
onQuickCreate={(title) => {
if (client) {
taskStore.createTask(client, { "@type": "Task", title, progress: "needs-action", calendarIds: { [calendars[0]?.id ?? ""]: true } });
}
}}
/>
</div>
);
}
})();
@@ -721,7 +824,7 @@ export default function CalendarPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
@@ -751,6 +854,7 @@ export default function CalendarPage() {
onChangeMonth={handleMiniMonthChange}
events={events}
firstDayOfWeek={firstDayOfWeek}
showWeekNumbers={showWeekNumbers}
/>
<CalendarSidebarPanel
calendars={calendars}
@@ -791,6 +895,7 @@ export default function CalendarPage() {
calendars={calendars}
selectedCalendarIds={selectedCalendarIds}
onToggleVisibility={toggleCalendarVisibility}
enableCalendarTasks={enableCalendarTasks}
/>
<div
@@ -822,6 +927,21 @@ export default function CalendarPage() {
</div>
)}
{/* Desktop task panel */}
{!isMobile && showTaskModal && (
<div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden">
<TaskModal
key={editTask?.id ?? 'new-task'}
task={editTask}
calendars={calendars}
onSave={handleSaveTask}
onDelete={handleDeleteTask}
onClose={() => { setShowTaskModal(false); setEditTask(null); }}
isMobile={false}
/>
</div>
)}
{/* Floating Create Event Button (mobile) */}
{isMobile && (
<Button
+4 -6
View File
@@ -1,7 +1,6 @@
"use client";
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl";
import { ArrowLeft, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -16,7 +15,7 @@ import { ContactsSidebar, type ContactCategory } from "@/components/contacts/con
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
import { exportContacts } from "@/components/contacts/contact-export";
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
import { useAuthStore } from "@/stores/auth-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { toast } from "@/stores/toast-store";
import { cn } from "@/lib/utils";
@@ -39,7 +38,6 @@ type View =
| "bulk-add-to-group";
export default function ContactsPage() {
const router = useRouter();
const t = useTranslations("contacts");
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
@@ -109,9 +107,9 @@ export default function ContactsPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login");
redirectToLogin();
}
}, [initialCheckDone, isAuthenticated, authLoading, router]);
}, [initialCheckDone, isAuthenticated, authLoading]);
useEffect(() => {
if (client && supportsSync && !hasFetched.current) {
@@ -594,7 +592,7 @@ export default function ContactsPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+4 -4
View File
@@ -7,7 +7,7 @@ import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
import { useAuthStore } from "@/stores/auth-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { useFileStore } from "@/stores/file-store";
import { toast } from "@/stores/toast-store";
@@ -112,9 +112,9 @@ export default function FilesPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login");
redirectToLogin();
}
}, [initialCheckDone, isAuthenticated, authLoading, router]);
}, [initialCheckDone, isAuthenticated, authLoading]);
// Initialize JMAP files client
useEffect(() => {
@@ -357,7 +357,7 @@ export default function FilesPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+6 -3
View File
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
import { IntlProvider } from "@/components/providers/intl-provider";
import { ThemeProvider } from "@/components/providers/theme-provider";
import { CalendarAlertProvider } from "@/components/providers/calendar-alert-provider";
import { EmbeddedBridgeProvider } from "@/components/providers/embedded-bridge-provider";
import { TourProvider } from "@/components/tour/tour-provider";
import { locales } from "@/i18n/routing";
@@ -27,9 +28,11 @@ export default async function LocaleLayout({
<IntlProvider locale={locale} messages={messages}>
<ThemeProvider>
<CalendarAlertProvider>
<TourProvider>
{children}
</TourProvider>
<EmbeddedBridgeProvider>
<TourProvider>
{children}
</TourProvider>
</EmbeddedBridgeProvider>
</CalendarAlertProvider>
</ThemeProvider>
</IntlProvider>
+59 -2
View File
@@ -16,7 +16,7 @@ import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
const APP_VERSION = "1.4.6";
const APP_VERSION = "1.4.7";
const THEME_OPTIONS = [
{ value: "light" as const, icon: Sun, label: "Light" },
@@ -32,7 +32,7 @@ export default function LoginPage() {
const isAddAccountMode = searchParams.get("mode") === "add-account";
const { login, loginDemo, isLoading, error, clearError, isAuthenticated } = useAuthStore();
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError } = useConfig();
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode } = useConfig();
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
const [formData, setFormData] = useState({
@@ -173,6 +173,63 @@ export default function LoginPage() {
});
}, [oauthEnabled, serverUrl, oauthIssuerUrl]);
// Auto-SSO: when enabled with OAUTH_ONLY, skip the login page entirely
const ssoError = searchParams.get("sso_error");
const autoSsoTriggered = useRef(false);
const startServerSideSso = useCallback(async () => {
setOauthLoading(true);
try {
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
const res = await fetch('/api/auth/sso/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ redirect_uri: redirectUri, locale: params.locale }),
});
if (!res.ok) {
setOauthLoading(false);
return;
}
const { authorize_url } = await res.json();
// Navigate to the authorize URL
const isIframe = (() => { try { return window.self !== window.top; } catch { return true; } })();
if (isIframe) {
// In an iframe, try top-level navigation
try {
window.top!.location.href = authorize_url;
} catch {
// Cross-origin restriction — fall back to current frame
window.location.href = authorize_url;
}
} else {
window.location.href = authorize_url;
}
} catch {
setOauthLoading(false);
}
}, [params.locale]);
useEffect(() => {
if (!autoSsoEnabled || !oauthOnly || !oauthDiscoveryDone || !oauthMetadata) return;
if (ssoError || isAddAccountMode || isAuthenticated) return;
if (autoSsoTriggered.current) return;
// Guard against redirect loops
try {
if (sessionStorage.getItem("sso_attempted")) return;
sessionStorage.setItem("sso_attempted", "1");
// Clear the flag after 30 seconds so retries are possible
setTimeout(() => { try { sessionStorage.removeItem("sso_attempted"); } catch { /* ignore */ } }, 30000);
} catch { /* sessionStorage unavailable */ }
autoSsoTriggered.current = true;
startServerSideSso();
}, [autoSsoEnabled, oauthOnly, oauthDiscoveryDone, oauthMetadata, ssoError, isAddAccountMode, isAuthenticated, startServerSideSso]);
const handleThemeSelect = useCallback((newTheme: "light" | "dark" | "system") => {
setTheme(newTheme);
setShowThemeMenu(false);
+4 -11
View File
@@ -1,7 +1,6 @@
"use client";
import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl";
import { Sidebar } from "@/components/layout/sidebar";
import { EmailList } from "@/components/email/email-list";
@@ -13,7 +12,7 @@ import { MobileHeader, MobileViewerHeader } from "@/components/layout/mobile-hea
import { ThreadGroup, Email } from "@/lib/jmap/types";
import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal";
import { useEmailStore } from "@/stores/email-store";
import { useAuthStore } from "@/stores/auth-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useSettingsStore } from "@/stores/settings-store";
import { useIdentityStore } from "@/stores/identity-store";
import { useUIStore } from "@/stores/ui-store";
@@ -48,7 +47,6 @@ import { Button } from "@/components/ui/button";
import { useConfig } from "@/hooks/use-config";
export default function Home() {
const router = useRouter();
const t = useTranslations();
const tCommon = useTranslations('common');
const { appName } = useConfig();
@@ -285,9 +283,9 @@ export default function Home() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push('/login');
redirectToLogin();
}
}, [initialCheckDone, isAuthenticated, authLoading, router]);
}, [initialCheckDone, isAuthenticated, authLoading]);
// Load mailboxes and emails when authenticated (only if not already loaded)
useEffect(() => {
@@ -768,12 +766,7 @@ export default function Home() {
}
};
const handleLogout = () => {
logout();
if (!useAuthStore.getState().isAuthenticated) {
router.push('/login');
}
};
const handleLogout = logout;
const handleSearch = async (query: string) => {
if (!client) return;
+5 -5
View File
@@ -44,7 +44,7 @@ import { FilesSettingsComponent } from '@/components/settings/files-settings';
import { ContactsSettings } from '@/components/settings/contacts-settings';
import { SmimeSettings } from '@/components/settings/smime-settings';
import { SidebarAppsSettings } from '@/components/settings/sidebar-apps-settings';
import { useAuthStore } from '@/stores/auth-store';
import { useAuthStore, redirectToLogin } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store';
import { useIsDesktop } from '@/hooks/use-media-query';
import { NavigationRail } from '@/components/layout/navigation-rail';
@@ -122,9 +122,9 @@ export default function SettingsPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push('/login');
redirectToLogin();
}
}, [initialCheckDone, isAuthenticated, authLoading, router]);
}, [initialCheckDone, isAuthenticated, authLoading]);
if (!isAuthenticated) {
return null;
@@ -286,7 +286,7 @@ export default function SettingsPage() {
{/* Logout */}
<div className="border-t border-border px-5 py-3">
<button
onClick={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onClick={logout}
className="w-full flex items-center gap-3 py-2.5 text-sm text-destructive hover:bg-muted rounded-md px-2 transition-colors duration-150"
>
<LogOut className="w-4 h-4" />
@@ -317,7 +317,7 @@ export default function SettingsPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+2 -4
View File
@@ -3,12 +3,10 @@ import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
...getCookieOptions(),
maxAge: SESSION_COOKIE_MAX_AGE,
};
+80
View File
@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptPayload } from '@/lib/auth/crypto';
import { exchangeCodeForTokens } from '@/lib/oauth/token-exchange';
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const SSO_PENDING_COOKIE = 'sso_pending';
const SSO_PENDING_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes
export async function POST(request: NextRequest) {
const cookieStore = await cookies();
try {
const { code, state } = await request.json();
if (!code || !state) {
return NextResponse.json({ error: 'Missing code or state' }, { status: 400 });
}
// Read and decrypt the pending SSO cookie
const pendingCookie = cookieStore.get(SSO_PENDING_COOKIE)?.value;
if (!pendingCookie) {
logger.warn('SSO complete: no pending cookie found');
return NextResponse.json({ error: 'No pending SSO session. Please start the login flow again.' }, { status: 400 });
}
const pending = decryptPayload(pendingCookie);
if (!pending) {
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'Invalid SSO session' }, { status: 400 });
}
// Validate state
if (pending.state !== state) {
logger.warn('SSO complete: state mismatch');
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'State mismatch' }, { status: 400 });
}
// Validate TTL
const createdAt = pending.created_at as number;
if (!createdAt || Date.now() - createdAt > SSO_PENDING_MAX_AGE_MS) {
logger.warn('SSO complete: pending session expired');
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'SSO session expired. Please try again.' }, { status: 400 });
}
const codeVerifier = pending.code_verifier as string;
const redirectUri = pending.redirect_uri as string;
if (!codeVerifier || !redirectUri) {
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'Invalid SSO session data' }, { status: 400 });
}
// Exchange code for tokens
const tokens = await exchangeCodeForTokens(code, codeVerifier, redirectUri);
// Store refresh token
if (tokens.refresh_token) {
const cookieName = refreshTokenCookieName(0);
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
}
// Delete pending cookie
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({
access_token: tokens.access_token,
expires_in: tokens.expires_in,
});
} catch (error) {
// Clean up pending cookie on any error
cookieStore.delete(SSO_PENDING_COOKIE);
logger.error('SSO complete error', { error: error instanceof Error ? error.message : 'Unknown error' });
return NextResponse.json({ error: 'Token exchange failed' }, { status: 401 });
}
}
+88
View File
@@ -0,0 +1,88 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { encryptPayload } from '@/lib/auth/crypto';
import { generateCodeVerifierServer, generateCodeChallengeServer, generateStateServer } from '@/lib/oauth/pkce-server';
import { getRequiredConfig } from '@/lib/oauth/token-exchange';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { OAUTH_SCOPES } from '@/lib/oauth/tokens';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const SSO_PENDING_COOKIE = 'sso_pending';
const SSO_PENDING_MAX_AGE = 300; // 5 minutes
export async function POST(request: NextRequest) {
try {
if (!process.env.SESSION_SECRET) {
return NextResponse.json({ error: 'SESSION_SECRET is required for SSO' }, { status: 500 });
}
const { redirect_uri, locale } = await request.json();
if (!redirect_uri || typeof redirect_uri !== 'string') {
return NextResponse.json({ error: 'Missing redirect_uri' }, { status: 400 });
}
// Validate redirect_uri origin matches the request origin to prevent open redirects
const requestOrigin = request.headers.get('origin') || request.nextUrl.origin;
try {
const redirectOrigin = new URL(redirect_uri).origin;
if (redirectOrigin !== requestOrigin) {
logger.warn('SSO start: redirect_uri origin mismatch', { redirectOrigin, requestOrigin });
return NextResponse.json({ error: 'Invalid redirect_uri' }, { status: 400 });
}
} catch {
return NextResponse.json({ error: 'Invalid redirect_uri' }, { status: 400 });
}
const { clientId, discoveryUrl } = getRequiredConfig();
const metadata = await discoverOAuth(discoveryUrl);
if (!metadata?.authorization_endpoint) {
return NextResponse.json({ error: 'OAuth discovery failed' }, { status: 502 });
}
// Generate PKCE + state server-side
const codeVerifier = generateCodeVerifierServer();
const codeChallenge = generateCodeChallengeServer(codeVerifier);
const state = generateStateServer();
// Encrypt and store in httpOnly cookie
const pendingData = {
state,
code_verifier: codeVerifier,
redirect_uri,
created_at: Date.now(),
};
const encrypted = encryptPayload(pendingData);
const cookieStore = await cookies();
const baseCookieOpts = getCookieOptions();
cookieStore.set(SSO_PENDING_COOKIE, encrypted, {
...baseCookieOpts,
maxAge: SSO_PENDING_MAX_AGE,
});
// Build authorize URL
const authUrl = new URL(metadata.authorization_endpoint);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', clientId);
authUrl.searchParams.set('redirect_uri', redirect_uri);
authUrl.searchParams.set('scope', OAUTH_SCOPES);
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
if (locale) {
authUrl.searchParams.set('ui_locales', locale);
}
return NextResponse.json({
authorize_url: authUrl.toString(),
state,
});
} catch (error) {
logger.error('SSO start error', { error: error instanceof Error ? error.message : 'Unknown error' });
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+6 -78
View File
@@ -1,18 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
const COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
import { exchangeCodeForTokens, buildOAuthParams, getMetadata, getTokenEndpoint } from '@/lib/oauth/token-exchange';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
function getSlot(request: NextRequest): number {
const raw = request.nextUrl.searchParams.get('slot');
@@ -22,44 +13,6 @@ function getSlot(request: NextRequest): number {
return slot;
}
function getRequiredConfig() {
const clientId = process.env.OAUTH_CLIENT_ID;
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
const issuerUrl = process.env.OAUTH_ISSUER_URL;
if (!clientId || !serverUrl) {
throw new Error(`OAuth misconfigured: ${[!clientId && 'OAUTH_CLIENT_ID', !serverUrl && 'JMAP_SERVER_URL'].filter(Boolean).join(', ')} not set`);
}
const discoveryUrl = issuerUrl?.trim() || serverUrl;
if (issuerUrl !== undefined && !issuerUrl.trim()) {
logger.warn('OAUTH_ISSUER_URL is set but empty, falling back to JMAP_SERVER_URL for discovery');
}
return { clientId, serverUrl, discoveryUrl };
}
async function getTokenEndpoint(): Promise<string> {
const { discoveryUrl } = getRequiredConfig();
const metadata = await discoverOAuth(discoveryUrl);
if (!metadata?.token_endpoint) {
throw new Error('OAuth token endpoint not found');
}
return metadata.token_endpoint;
}
async function getMetadata(): Promise<import('@/lib/oauth/discovery').OAuthMetadata | null> {
const { discoveryUrl } = getRequiredConfig();
return discoverOAuth(discoveryUrl);
}
function buildOAuthParams(base: Record<string, string>): URLSearchParams {
const { clientId } = getRequiredConfig();
const params = new URLSearchParams({ ...base, client_id: clientId });
if (CLIENT_SECRET) {
params.set('client_secret', CLIENT_SECRET);
}
return params;
}
export async function POST(request: NextRequest) {
try {
const { code, code_verifier, redirect_uri, slot: bodySlot } = await request.json();
@@ -69,43 +22,18 @@ export async function POST(request: NextRequest) {
}
const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
const tokenEndpoint = await getTokenEndpoint();
const params = buildOAuthParams({
grant_type: 'authorization_code',
code,
redirect_uri,
code_verifier,
});
const tokenResponse = await fetch(tokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params.toString(),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
logger.error('Token exchange failed', { status: tokenResponse.status, error: errorText });
return NextResponse.json({ error: 'Token exchange failed' }, { status: 401 });
}
const tokens = await tokenResponse.json();
if (!tokens.access_token) {
logger.error('Token response missing access_token', { response: JSON.stringify(tokens).substring(0, 500) });
return NextResponse.json({ error: 'Invalid token response' }, { status: 502 });
}
const tokens = await exchangeCodeForTokens(code, code_verifier, redirect_uri);
const response = NextResponse.json({
access_token: tokens.access_token,
expires_in: tokens.expires_in || 3600,
expires_in: tokens.expires_in,
});
if (tokens.refresh_token) {
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies();
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
}
return response;
@@ -154,7 +82,7 @@ export async function PUT(request: NextRequest) {
}
if (tokens.refresh_token) {
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
}
return NextResponse.json({
+3
View File
@@ -36,5 +36,8 @@ export async function GET() {
loginPrivacyPolicyUrl: process.env.LOGIN_PRIVACY_POLICY_URL || '',
loginWebsiteUrl: process.env.LOGIN_WEBSITE_URL || '',
demoMode: process.env.DEMO_MODE === 'true',
autoSsoEnabled: process.env.AUTO_SSO_ENABLED === 'true',
embeddedMode: !!process.env.ALLOWED_FRAME_ANCESTORS && process.env.ALLOWED_FRAME_ANCESTORS !== "'none'",
parentOrigin: process.env.NEXT_PUBLIC_PARENT_ORIGIN || '',
});
}
+92
View File
@@ -496,3 +496,95 @@ body {
-webkit-backdrop-filter: none !important;
}
}
/* TipTap Rich Text Editor */
.tiptap {
outline: none;
}
.tiptap p {
margin: 0.25rem 0;
}
.tiptap h1 {
font-size: 1.5rem;
font-weight: 700;
margin: 0.5rem 0;
}
.tiptap h2 {
font-size: 1.25rem;
font-weight: 600;
margin: 0.5rem 0;
}
.tiptap ul {
list-style-type: disc;
padding-left: 1.5rem;
margin: 0.25rem 0;
}
.tiptap ol {
list-style-type: decimal;
padding-left: 1.5rem;
margin: 0.25rem 0;
}
.tiptap li {
margin: 0.125rem 0;
}
.tiptap blockquote {
border-left: 3px solid var(--color-border);
padding-left: 1rem;
margin: 0.5rem 0;
color: var(--color-muted-foreground);
}
.tiptap pre {
background-color: var(--color-muted);
border: 1px solid var(--color-border);
border-radius: 0.375rem;
padding: 0.75rem;
font-family: monospace;
font-size: 0.875rem;
overflow-x: auto;
margin: 0.5rem 0;
}
.tiptap code {
background-color: var(--color-muted);
padding: 0.125rem 0.25rem;
border-radius: 0.25rem;
font-family: monospace;
font-size: 0.875rem;
}
.tiptap a {
color: var(--color-primary);
text-decoration: underline;
cursor: pointer;
}
.tiptap img {
max-width: 100%;
height: auto;
}
.tiptap hr {
border: none;
border-top: 1px solid var(--color-border);
margin: 1rem 0;
}
.tiptap p.is-editor-empty:first-child::before {
content: attr(data-placeholder);
float: left;
color: var(--color-muted-foreground);
pointer-events: none;
height: 0;
}
.tiptap .ProseMirror-selectednode img {
outline: none;
}
+4
View File
@@ -31,10 +31,14 @@ export default async function RootLayout({
}) {
const locale = await getLocale();
const nonce = (await headers()).get("x-nonce") ?? "";
const parentOrigin = process.env.NEXT_PUBLIC_PARENT_ORIGIN || "";
return (
<html lang={locale} suppressHydrationWarning>
<head>
{parentOrigin && (
<meta name="parent-origin" content={parentOrigin} />
)}
<script
nonce={nonce}
suppressHydrationWarning
+72 -19
View File
@@ -4,10 +4,11 @@ import { useMemo, useEffect, useRef, useState } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { format, isSameDay, isToday, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input";
import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types";
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
import type { PendingEventPreview } from "./event-modal";
@@ -22,6 +23,8 @@ interface CalendarDayViewProps {
timeFormat?: "12h" | "24h";
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
tasks?: CalendarTask[];
onToggleTaskComplete?: (task: CalendarTask) => void;
}
const HOUR_HEIGHT = 64;
@@ -38,6 +41,8 @@ export function CalendarDayView({
timeFormat = "24h",
isMobile,
pendingPreview,
tasks,
onToggleTaskComplete,
}: CalendarDayViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -68,6 +73,16 @@ export function CalendarDayView({
return { timedEvents: timed, allDayEvents: allDay };
}, [events, selectedDate]);
const dayTasks = useMemo(() => {
if (!tasks?.length) return [];
return tasks.filter(task => {
if (!task.due) return false;
try {
return isSameDay(parseISO(task.due), selectedDate);
} catch { return false; }
});
}, [tasks, selectedDate]);
useEffect(() => {
if (scrollRef.current) {
const now = new Date();
@@ -125,25 +140,63 @@ export function CalendarDayView({
</h3>
</div>
{allDayEvents.length > 0 && (
{(allDayEvents.length > 0 || dayTasks.length > 0) && (
<div className="px-4 py-2 border-b border-border">
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
<div className="space-y-1">
{allDayEvents.map((ev) => {
const calId = getPrimaryCalendarId(ev);
return (
<EventCard
key={ev.id}
event={ev}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="chip"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
onMouseLeave={onHoverLeave}
/>
);
})}
</div>
{allDayEvents.length > 0 && (
<>
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
<div className="space-y-1">
{allDayEvents.map((ev) => {
const calId = getPrimaryCalendarId(ev);
return (
<EventCard
key={ev.id}
event={ev}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="chip"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
onMouseLeave={onHoverLeave}
/>
);
})}
</div>
</>
)}
{dayTasks.length > 0 && (
<>
<div className={cn("text-[10px] text-muted-foreground mb-1", allDayEvents.length > 0 && "mt-2")}>{t("tasks.label")}</div>
<div className="space-y-0.5">
{dayTasks.map((task) => {
const isCompleted = task.progress === "completed";
const cal = calendars.find(c => task.calendarIds[c.id]);
const color = cal?.color || "#3b82f6";
return (
<div
key={task.id}
className="flex items-center gap-1.5 px-1.5 py-0.5 rounded text-xs cursor-pointer hover:bg-muted/50 transition-colors"
style={{ borderLeft: `3px solid ${color}` }}
>
<button
onClick={(e) => { e.stopPropagation(); onToggleTaskComplete?.(task); }}
className={cn(
"flex-shrink-0 w-3.5 h-3.5 rounded-full border flex items-center justify-center",
isCompleted
? "bg-green-500 border-green-500 text-white"
: "border-muted-foreground/40 hover:border-primary"
)}
>
{isCompleted && <Check className="h-2.5 w-2.5" />}
</button>
<span className={cn("truncate", isCompleted && "line-through text-muted-foreground")}>
{task.title || t("tasks.no_title")}
</span>
</div>
);
})}
</div>
</>
)}
</div>
)}
+26 -1
View File
@@ -2,12 +2,13 @@
import { useState, useRef, useEffect, useMemo } from "react";
import { useTranslations } from "next-intl";
import { Globe, Plus, RefreshCw, Share2, Trash2 } from "lucide-react";
import { Globe, ListTodo, Plus, RefreshCw, Share2, Trash2 } from "lucide-react";
import { cn, formatDateTime } from "@/lib/utils";
import type { Calendar } from "@/lib/jmap/types";
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
import { useCalendarStore } from "@/stores/calendar-store";
import { useSettingsStore } from "@/stores/settings-store";
import { useTaskStore } from "@/stores/task-store";
import { toast } from "@/stores/toast-store";
import type { IJMAPClient } from '@/lib/jmap/client-interface';
@@ -35,6 +36,15 @@ export function CalendarSidebarPanel({
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription);
const timeFormat = useSettingsStore((s) => s.timeFormat);
const enableCalendarTasks = useSettingsStore((s) => s.enableCalendarTasks);
const tasks = useTaskStore((s) => s.tasks);
const setViewMode = useCalendarStore((s) => s.setViewMode);
const pendingTaskCount = useMemo(() => tasks.filter(t => t.progress !== 'completed' && t.progress !== 'cancelled').length, [tasks]);
const overdueTaskCount = useMemo(() => {
const now = new Date();
return tasks.filter(t => t.progress !== 'completed' && t.progress !== 'cancelled' && t.due && new Date(t.due) < now).length;
}, [tasks]);
const [colorPickerId, setColorPickerId] = useState<string | null>(null);
const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
@@ -209,6 +219,21 @@ export function CalendarSidebarPanel({
return (
<div className="mt-4">
{enableCalendarTasks && (
<button
onClick={() => setViewMode('tasks')}
className="flex items-center gap-2 w-full px-1.5 py-1.5 mb-3 rounded-md text-sm hover:bg-muted transition-colors"
>
<ListTodo className="w-4 h-4 text-muted-foreground" />
<span>{t('tasks.label')}</span>
{pendingTaskCount > 0 && (
<span className="ml-auto text-xs text-muted-foreground">{pendingTaskCount}</span>
)}
{overdueTaskCount > 0 && (
<span className="text-xs text-destructive font-medium">{overdueTaskCount} {t('tasks.filter_overdue').toLowerCase()}</span>
)}
</button>
)}
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1">
{t("my_calendars")}
</h3>
+8 -2
View File
@@ -3,7 +3,7 @@
import { useState, useRef, useEffect } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight, Plus, Upload, CalendarDays, Globe, ChevronDown } from "lucide-react";
import { ChevronLeft, ChevronRight, Plus, Upload, CalendarDays, Globe, ChevronDown, ListTodo } from "lucide-react";
import { addDays, startOfWeek } from "date-fns";
import { cn } from "@/lib/utils";
import type { CalendarViewMode } from "@/stores/calendar-store";
@@ -25,6 +25,7 @@ interface CalendarToolbarProps {
calendars?: Calendar[];
selectedCalendarIds?: string[];
onToggleVisibility?: (id: string) => void;
enableCalendarTasks?: boolean;
}
export function CalendarToolbar({
@@ -42,10 +43,13 @@ export function CalendarToolbar({
calendars,
selectedCalendarIds,
onToggleVisibility,
enableCalendarTasks,
}: CalendarToolbarProps) {
const t = useTranslations("calendar");
const formatter = useFormatter();
const views: CalendarViewMode[] = ["month", "week", "day", "agenda"];
const views: CalendarViewMode[] = enableCalendarTasks
? ["month", "week", "day", "agenda", "tasks"]
: ["month", "week", "day", "agenda"];
const [showCalendarDropdown, setShowCalendarDropdown] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
@@ -86,6 +90,8 @@ export function CalendarToolbar({
return isMobile
? formatter.dateTime(selectedDate, { month: "short", year: "numeric" })
: formatter.dateTime(selectedDate, { month: "long", year: "numeric" });
case "tasks":
return t("views.tasks");
}
};
+80 -5
View File
@@ -6,10 +6,11 @@ import {
startOfWeek, addDays, format, isSameDay, isToday, parseISO,
} from "date-fns";
import { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input";
import { buildWeekSegments, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types";
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
import type { PendingEventPreview } from "./event-modal";
@@ -26,6 +27,8 @@ interface CalendarWeekViewProps {
timeFormat?: "12h" | "24h";
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
tasks?: CalendarTask[];
onToggleTaskComplete?: (task: CalendarTask) => void;
}
const HOUR_HEIGHT = 60;
@@ -44,6 +47,8 @@ export function CalendarWeekView({
timeFormat = "24h",
isMobile,
pendingPreview,
tasks,
onToggleTaskComplete,
}: CalendarWeekViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -96,9 +101,36 @@ export function CalendarWeekView({
return allDaySegments.reduce((maxRows, segment) => Math.max(maxRows, segment.row + 1), 0);
}, [allDaySegments]);
// Tasks grouped by day for the week
const tasksByDay = useMemo(() => {
if (!tasks?.length) return new Map<string, CalendarTask[]>();
const map = new Map<string, CalendarTask[]>();
for (const task of tasks) {
if (!task.due) continue;
try {
const key = format(parseISO(task.due), "yyyy-MM-dd");
const existing = map.get(key) || [];
existing.push(task);
map.set(key, existing);
} catch { /* skip */ }
}
return map;
}, [tasks]);
// Max tasks on any single day in this week
const taskRowCount = useMemo(() => {
let max = 0;
for (const day of weekDays) {
const key = format(day, "yyyy-MM-dd");
const count = tasksByDay.get(key)?.length ?? 0;
if (count > max) max = count;
}
return max;
}, [tasksByDay, weekDays]);
const hasAllDay = useMemo(() => {
return allDaySegments.length > 0;
}, [allDaySegments]);
return allDaySegments.length > 0 || taskRowCount > 0;
}, [allDaySegments, taskRowCount]);
useEffect(() => {
if (scrollRef.current) {
@@ -151,13 +183,13 @@ export function CalendarWeekView({
<div className="flex border-b border-border">
<div
className={cn("flex-shrink-0 text-[10px] text-muted-foreground p-1 text-right", isMobile ? "w-10" : "w-14")}
style={{ minHeight: Math.max(28, allDayRowCount * 24 + 4) }}
style={{ minHeight: Math.max(28, (allDayRowCount + taskRowCount) * 24 + 4) }}
>
{t("events.all_day")}
</div>
<div
className={cn("flex-1 relative grid gap-px bg-border", isMobile ? "grid-cols-3" : "grid-cols-7")}
style={{ minHeight: Math.max(28, allDayRowCount * 24 + 4) }}
style={{ minHeight: Math.max(28, (allDayRowCount + taskRowCount) * 24 + 4) }}
>
{weekDays.map((day) => (
<div key={format(day, "yyyy-MM-dd")} className="bg-background min-h-[28px]" />
@@ -191,6 +223,49 @@ export function CalendarWeekView({
);
})}
</div>
{/* Task chips in all-day area */}
{taskRowCount > 0 && (
<div className="absolute inset-x-0 pointer-events-none" style={{ top: allDayRowCount * 24 + 2 }}>
{weekDays.map((day, dayIndex) => {
const key = format(day, "yyyy-MM-dd");
const dayTasks = tasksByDay.get(key) || [];
return dayTasks.map((task, taskIndex) => {
const isCompleted = task.progress === "completed";
const cal = calendars.find(c => task.calendarIds[c.id]);
const color = cal?.color || "#3b82f6";
return (
<div
key={`task-${task.id}`}
className="absolute px-0.5 pointer-events-auto"
style={{
left: `calc(${(dayIndex / colCount) * 100}% + 1px)`,
width: `calc(${(1 / colCount) * 100}% - 2px)`,
top: taskIndex * 24,
height: 20,
}}
>
<div
className="h-full rounded text-[10px] leading-[20px] font-medium px-1.5 truncate flex items-center gap-1 cursor-pointer hover:opacity-80"
style={{ backgroundColor: `${color}20`, borderLeft: `3px solid ${color}` }}
onClick={() => onToggleTaskComplete?.(task)}
>
<span className={cn(
"w-2.5 h-2.5 rounded-full border flex-shrink-0 flex items-center justify-center",
isCompleted ? "bg-green-500 border-green-500" : "border-current"
)}>
{isCompleted && <Check className="h-2 w-2 text-white" />}
</span>
<span className={cn("truncate", isCompleted && "line-through text-muted-foreground")}>
{task.title}
</span>
</div>
</div>
);
});
})}
</div>
)}
</div>
</div>
)}
@@ -192,6 +192,10 @@ export function EventDetailPopover({
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
const target = e.target as HTMLElement;
const tag = target?.tagName?.toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select") return;
if (target?.getAttribute("contenteditable") === "true") return;
if (e.key === "e" && !noteExpanded) {
e.preventDefault();
onEdit();
+46 -19
View File
@@ -1,12 +1,12 @@
"use client";
import { useState, useMemo } from "react";
import { useState, useMemo, Fragment } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react";
import {
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
addMonths, subMonths, addYears, subYears, setMonth, setYear,
eachDayOfInterval, getMonth, getYear,
eachDayOfInterval, getMonth, getYear, getISOWeek, getWeek,
isSameDay, isSameMonth, isToday, format,
} from "date-fns";
import { cn } from "@/lib/utils";
@@ -26,6 +26,7 @@ interface MiniCalendarProps {
onChangeMonth: (date: Date) => void;
events?: CalendarEvent[];
firstDayOfWeek?: number;
showWeekNumbers?: boolean;
}
export function MiniCalendar({
@@ -35,6 +36,7 @@ export function MiniCalendar({
onChangeMonth,
events = [],
firstDayOfWeek = 1,
showWeekNumbers = false,
}: MiniCalendarProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -61,6 +63,17 @@ export function MiniCalendar({
? ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const
: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
// Compute week numbers for each row (one per 7-day chunk)
const weekNumbers = useMemo(() => {
if (!showWeekNumbers) return [];
const nums: number[] = [];
for (let i = 0; i < days.length; i += 7) {
// Use the first day of each row to determine the week number
nums.push(weekStart === 1 ? getISOWeek(days[i]) : getWeek(days[i], { weekStartsOn: 0 }));
}
return nums;
}, [days, showWeekNumbers, weekStart]);
const currentYear = getYear(displayMonth);
const currentMonth = getMonth(displayMonth);
const decadeStart = Math.floor(currentYear / 10) * 10;
@@ -135,35 +148,49 @@ export function MiniCalendar({
</div>
{pickerView === "days" && (
<div className="grid grid-cols-7 gap-0">
<div className={cn("grid gap-0", showWeekNumbers ? "grid-cols-[auto_repeat(7,1fr)]" : "grid-cols-7")}>
{showWeekNumbers && (
<div className="text-center text-[10px] font-medium text-muted-foreground py-1 w-5" />
)}
{dayHeaders.map((d) => (
<div key={d} className="text-center text-[10px] font-medium text-muted-foreground py-1">
{t(`days.${d}`)}
</div>
))}
{days.map((day) => {
{days.map((day, index) => {
const inMonth = isSameMonth(day, displayMonth);
const selected = isSameDay(day, selectedDate);
const today = isToday(day);
const hasEvent = eventDates.has(format(day, "yyyy-MM-dd"));
const isFirstDayOfRow = index % 7 === 0;
return (
<button
key={day.toISOString()}
onClick={() => onSelectDate(day)}
className={cn(
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
!inMonth && "text-muted-foreground/40",
inMonth && !selected && "hover:bg-muted",
today && !selected && "font-bold text-primary",
selected && "bg-primary text-primary-foreground"
<Fragment key={day.toISOString()}>
{showWeekNumbers && isFirstDayOfRow && (
<div
key={`wk-${index}`}
className="flex items-center justify-center w-5 text-[9px] text-muted-foreground/60 font-medium"
>
{weekNumbers[index / 7]}
</div>
)}
>
{format(day, "d")}
{hasEvent && !selected && (
<span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary" />
)}
</button>
<button
key={`day-${day.toISOString()}`}
onClick={() => onSelectDate(day)}
className={cn(
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
!inMonth && "text-muted-foreground/40",
inMonth && !selected && "hover:bg-muted",
today && !selected && "font-bold text-primary",
selected && "bg-primary text-primary-foreground"
)}
>
{format(day, "d")}
{hasEvent && !selected && (
<span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary" />
)}
</button>
</Fragment>
);
})}
</div>
+50 -5
View File
@@ -1,9 +1,9 @@
"use client";
import { useMemo, useCallback } from "react";
import { useMemo, useCallback, useState } from "react";
import { useTranslations } from "next-intl";
import { format, parseISO, isPast, isToday, isTomorrow } from "date-fns";
import { Check, Circle, Flag, CalendarDays, ListTodo } from "lucide-react";
import { Check, Circle, Flag, CalendarDays, ListTodo, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import type { CalendarTask, Calendar } from "@/lib/jmap/types";
import type { TaskViewFilter } from "@/stores/task-store";
@@ -18,6 +18,7 @@ interface TaskListViewProps {
onSelectTask: (task: CalendarTask) => void;
onToggleComplete: (task: CalendarTask) => void;
selectedTaskId?: string | null;
onQuickCreate?: (title: string) => void;
}
function getTaskPriorityIcon(priority: number) {
@@ -69,9 +70,11 @@ export function TaskListView({
onSelectTask,
onToggleComplete,
selectedTaskId,
onQuickCreate,
}: TaskListViewProps) {
const t = useTranslations("calendar");
const timeFormat = useSettingsStore((s) => s.timeFormat);
const [quickAddTitle, setQuickAddTitle] = useState("");
const filteredTasks = useMemo(() => {
let result = tasks.filter(task => {
@@ -128,15 +131,57 @@ export function TaskListView({
if (filteredTasks.length === 0) {
return (
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground py-12">
<ListTodo className="h-12 w-12 mb-3 opacity-30" />
<p className="text-sm">{t("tasks.no_tasks")}</p>
<div className="flex flex-col flex-1">
{onQuickCreate && (
<div className="px-4 py-2 border-b border-border">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<input
type="text"
value={quickAddTitle}
onChange={(e) => setQuickAddTitle(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && quickAddTitle.trim()) {
onQuickCreate(quickAddTitle.trim());
setQuickAddTitle("");
}
}}
placeholder={t("tasks.quick_add_placeholder")}
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
</div>
</div>
)}
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground py-12">
<ListTodo className="h-12 w-12 mb-3 opacity-30" />
<p className="text-sm">{t("tasks.no_tasks")}</p>
</div>
</div>
);
}
return (
<div className="flex-1 overflow-y-auto">
{onQuickCreate && (
<div className="px-4 py-2 border-b border-border">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<input
type="text"
value={quickAddTitle}
onChange={(e) => setQuickAddTitle(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && quickAddTitle.trim()) {
onQuickCreate(quickAddTitle.trim());
setQuickAddTitle("");
}
}}
placeholder={t("tasks.quick_add_placeholder")}
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
</div>
</div>
)}
<div className="divide-y divide-border">
{filteredTasks.map(task => {
const cal = calendars.find(c => task.calendarIds[c.id]);
+321
View File
@@ -0,0 +1,321 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { X, Trash2, CalendarDays, Bell, Flag } from "lucide-react";
import { format, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import type { CalendarTask, Calendar, CalendarEventAlert } from "@/lib/jmap/types";
interface TaskModalProps {
task?: CalendarTask | null;
calendars: Calendar[];
onSave: (data: Partial<CalendarTask>) => void | Promise<void>;
onDelete?: (id: string) => void;
onClose: () => void;
isMobile?: boolean;
}
type PriorityLevel = "none" | "high" | "medium" | "low";
type AlertOption = "none" | "at_time" | "5" | "15" | "30" | "60" | "1440";
function priorityToLevel(p: number): PriorityLevel {
if (p >= 1 && p <= 4) return "high";
if (p === 5) return "medium";
if (p >= 6 && p <= 9) return "low";
return "none";
}
function levelToPriority(l: PriorityLevel): number {
switch (l) {
case "high": return 1;
case "medium": return 5;
case "low": return 9;
default: return 0;
}
}
export function TaskModal({
task,
calendars,
onSave,
onDelete,
onClose,
isMobile,
}: TaskModalProps) {
const t = useTranslations("calendar");
const isEdit = !!task;
const titleRef = useRef<HTMLInputElement>(null);
const writableCalendars = calendars.filter(c => !c.isShared || c.myRights?.mayWriteAll || c.myRights?.mayWriteOwn);
const defaultCalendarId = writableCalendars[0]?.id ?? calendars[0]?.id ?? "";
const [title, setTitle] = useState(task?.title ?? "");
const [description, setDescription] = useState(task?.description ?? "");
const [dueDate, setDueDate] = useState(task?.due ? format(parseISO(task.due), "yyyy-MM-dd") : "");
const [dueTime, setDueTime] = useState(task?.due && !task.showWithoutTime ? format(parseISO(task.due), "HH:mm") : "");
const [showTime, setShowTime] = useState(task?.due ? !task.showWithoutTime : false);
const [priority, setPriority] = useState<PriorityLevel>(priorityToLevel(task?.priority ?? 0));
const [progress, setProgress] = useState<CalendarTask["progress"]>(task?.progress ?? "needs-action");
const [calendarId, setCalendarId] = useState(() => {
if (task) {
const ids = Object.keys(task.calendarIds);
return ids[0] ?? defaultCalendarId;
}
return defaultCalendarId;
});
const [alertOption, setAlertOption] = useState<AlertOption>(() => {
if (!task?.alerts) return "none";
const first = Object.values(task.alerts)[0];
if (!first || first.trigger["@type"] !== "OffsetTrigger") return "none";
const offset = first.trigger.offset;
if (offset === "PT0S") return "at_time";
const m = offset.match(/-?PT?(\d+)M$/);
if (m) return m[1] as AlertOption;
const h = offset.match(/-?PT?(\d+)H$/);
if (h) return String(parseInt(h[1]) * 60) as AlertOption;
const d = offset.match(/-?P(\d+)D/);
if (d) return String(parseInt(d[1]) * 1440) as AlertOption;
return "none";
});
const [saving, setSaving] = useState(false);
useEffect(() => {
titleRef.current?.focus();
}, []);
const handleSave = useCallback(async () => {
if (!title.trim()) return;
setSaving(true);
try {
let due: string | null = null;
let showWithoutTime = true;
if (dueDate) {
if (showTime && dueTime) {
due = `${dueDate}T${dueTime}:00`;
showWithoutTime = false;
} else {
due = `${dueDate}T00:00:00`;
showWithoutTime = true;
}
}
let alerts: Record<string, CalendarEventAlert> | null = null;
if (alertOption !== "none") {
const offset = alertOption === "at_time" ? "PT0S" : `-PT${alertOption}M`;
alerts = {
"default-alert": {
"@type": "Alert",
trigger: { "@type": "OffsetTrigger", offset, relativeTo: "start" },
action: "display",
acknowledged: null,
relatedTo: null,
},
};
}
const data: Partial<CalendarTask> = {
"@type": "Task",
title: title.trim(),
description: description.trim() || "",
due,
showWithoutTime,
priority: levelToPriority(priority),
progress,
calendarIds: { [calendarId]: true },
alerts,
};
if (isEdit && task) {
data.id = task.id;
}
await onSave(data);
onClose();
} finally {
setSaving(false);
}
}, [title, description, dueDate, dueTime, showTime, priority, progress, calendarId, alertOption, isEdit, task, onSave, onClose]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
onClose();
}
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
e.preventDefault();
handleSave();
}
}, [onClose, handleSave]);
return (
<div className="flex flex-col h-full bg-background" onKeyDown={handleKeyDown}>
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-border">
<h2 className="text-sm font-semibold">
{isEdit ? t("tasks.edit") : t("tasks.create")}
</h2>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={onClose}>
<X className="h-4 w-4" />
</Button>
</div>
{/* Body */}
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{/* Title */}
<Input
ref={titleRef}
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder={t("tasks.title_placeholder")}
className="text-base font-medium"
/>
{/* Description */}
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder={t("tasks.description_placeholder")}
rows={3}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring resize-none"
/>
{/* Due Date */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<CalendarDays className="h-3.5 w-3.5" />
{t("tasks.due_date")}
</label>
<div className="flex items-center gap-2">
<input
type="date"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm"
/>
{dueDate && (
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
checked={showTime}
onChange={(e) => setShowTime(e.target.checked)}
className="rounded"
/>
{t("tasks.include_time")}
</label>
)}
{showTime && (
<input
type="time"
value={dueTime}
onChange={(e) => setDueTime(e.target.value)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm"
/>
)}
</div>
</div>
{/* Priority */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<Flag className="h-3.5 w-3.5" />
{t("tasks.priority")}
</label>
<select
value={priority}
onChange={(e) => setPriority(e.target.value as PriorityLevel)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
<option value="none">{t("tasks.priority_none")}</option>
<option value="high">{t("tasks.priority_high")}</option>
<option value="medium">{t("tasks.priority_medium")}</option>
<option value="low">{t("tasks.priority_low")}</option>
</select>
</div>
{/* Progress */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
{t("tasks.progress")}
</label>
<select
value={progress}
onChange={(e) => setProgress(e.target.value as CalendarTask["progress"])}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
<option value="needs-action">{t("tasks.progress_needs_action")}</option>
<option value="in-process">{t("tasks.progress_in_process")}</option>
<option value="completed">{t("tasks.progress_completed")}</option>
<option value="cancelled">{t("tasks.progress_cancelled")}</option>
</select>
</div>
{/* Calendar */}
{writableCalendars.length > 1 && (
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
{t("tasks.calendar")}
</label>
<select
value={calendarId}
onChange={(e) => setCalendarId(e.target.value)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
{writableCalendars.map((cal) => (
<option key={cal.id} value={cal.id}>{cal.name}</option>
))}
</select>
</div>
)}
{/* Alert */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<Bell className="h-3.5 w-3.5" />
{t("tasks.alert")}
</label>
<select
value={alertOption}
onChange={(e) => setAlertOption(e.target.value as AlertOption)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
<option value="none">{t("tasks.alert_none")}</option>
<option value="at_time">{t("tasks.alert_at_time")}</option>
<option value="5">{t("tasks.alert_5min")}</option>
<option value="15">{t("tasks.alert_15min")}</option>
<option value="30">{t("tasks.alert_30min")}</option>
<option value="60">{t("tasks.alert_1hr")}</option>
<option value="1440">{t("tasks.alert_1day")}</option>
</select>
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between px-4 py-3 border-t border-border">
<div>
{isEdit && onDelete && task && (
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() => onDelete(task.id)}
>
<Trash2 className="h-4 w-4 mr-1" />
{t("tasks.delete")}
</Button>
)}
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={onClose}>
{t("tasks.cancel")}
</Button>
<Button size="sm" onClick={handleSave} disabled={!title.trim() || saving}>
{t("tasks.save")}
</Button>
</div>
</div>
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
"use client";
import { useTranslations } from "next-intl";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { TaskViewFilter } from "@/stores/task-store";
interface TaskToolbarProps {
filter: TaskViewFilter;
showCompleted: boolean;
onFilterChange: (filter: TaskViewFilter) => void;
onShowCompletedChange: (show: boolean) => void;
onCreateTask: () => void;
}
const FILTERS: TaskViewFilter[] = ["all", "pending", "completed", "overdue"];
export function TaskToolbar({
filter,
showCompleted,
onFilterChange,
onShowCompletedChange,
onCreateTask,
}: TaskToolbarProps) {
const t = useTranslations("calendar");
return (
<div className="flex items-center gap-2 px-4 py-2 border-b border-border flex-wrap">
<div className="flex border border-border rounded-md overflow-hidden">
{FILTERS.map((f) => (
<button
key={f}
onClick={() => onFilterChange(f)}
className={cn(
"px-3 py-1.5 text-xs font-medium transition-colors",
f === filter
? "bg-primary text-primary-foreground"
: "hover:bg-muted text-muted-foreground"
)}
>
{t(`tasks.filter_${f}`)}
</button>
))}
</div>
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none ml-2">
<input
type="checkbox"
checked={showCompleted}
onChange={(e) => onShowCompletedChange(e.target.checked)}
className="rounded border-border"
/>
{t("tasks.show_completed")}
</label>
<div className="flex-1" />
<Button size="sm" onClick={onCreateTask}>
<Plus className="w-4 h-4 mr-1" />
{t("tasks.create")}
</Button>
</div>
);
}
+62 -97
View File
@@ -28,6 +28,14 @@ import { TemplatePicker } from "@/components/templates/template-picker";
import { TemplateForm } from "@/components/templates/template-form";
import type { EmailTemplate } from "@/lib/template-types";
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
import { RichTextEditor } from "@/components/email/rich-text-editor";
/** Strip HTML tags and decode entities to get a plain-text version */
function htmlToPlainText(html: string): string {
const tmp = document.createElement('div');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || '';
}
export interface ComposerDraftData {
to: string;
@@ -125,23 +133,28 @@ export function EmailComposer({
};
const getInitialBody = () => {
const prefix = initialDraftText || "";
const prefix = initialDraftText ? `<p>${initialDraftText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</p>` : "";
if (!replyTo?.body && !replyTo?.htmlBody) return prefix;
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : "";
const from = replyTo.from?.[0];
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
// When HTML body is available, don't include quoted text in the textarea
// The HTML original will be shown separately below the textarea
// Build quoted content as HTML
if (replyTo.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
return prefix;
const quoteHeader = mode === 'forward'
? `---------- Forwarded message ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>`
: `On ${date}, ${fromStr} wrote:<br>`;
return `${prefix}<br><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote>`;
}
if (mode === 'forward') {
return `${prefix}\n\n---------- Forwarded message ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ""}\n\n${replyTo.body}`;
} else if (mode === 'reply' || mode === 'replyAll') {
return `${prefix}\n\nOn ${date}, ${fromStr} wrote:\n> ${(replyTo.body || '').split('\n').join('\n> ')}`;
if (replyTo.body) {
const escapedOriginal = replyTo.body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
if (mode === 'forward') {
return `${prefix}<br><br>---------- Forwarded message ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>${escapedOriginal}`;
} else if (mode === 'reply' || mode === 'replyAll') {
return `${prefix}<br><br>On ${date}, ${fromStr} wrote:<br><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${escapedOriginal}</blockquote>`;
}
}
return prefix;
};
@@ -157,18 +170,6 @@ export function EmailComposer({
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const lastSavedDataRef = useRef<string>("");
const textareaRef = useRef<HTMLTextAreaElement>(null);
const autoResizeTextarea = useCallback(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
}, []);
useEffect(() => {
autoResizeTextarea();
}, [body, autoResizeTextarea]);
const [attachments, setAttachments] = useState<Array<{ file: File; blobId?: string; uploading?: boolean; error?: boolean; abortController?: AbortController }>>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
const [validationErrors, setValidationErrors] = useState<{ to?: boolean; subject?: boolean; body?: boolean }>({});
@@ -367,9 +368,12 @@ export function EmailComposer({
? substitutePlaceholders(template.body, filledValues)
: template.body;
// Convert template plain text body to HTML for the rich text editor
const htmlBody = `<p>${filledBody.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</p>`;
if (mode === 'compose') {
setSubject(filledSubject);
setBody(filledBody);
setBody(htmlBody);
if (template.defaultRecipients?.to?.length) {
setTo(template.defaultRecipients.to.join(', ') + ', ');
}
@@ -382,7 +386,7 @@ export function EmailComposer({
setShowBcc(true);
}
} else {
setBody((prev) => filledBody + prev);
setBody((prev) => htmlBody + prev);
}
if (template.identityId) {
@@ -394,8 +398,10 @@ export function EmailComposer({
useEffect(() => {
const handleTemplateKey = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement)?.tagName?.toLowerCase();
const target = e.target as HTMLElement;
const tag = target?.tagName?.toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
if (target?.getAttribute('contenteditable') === 'true') return;
if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
setShowTemplatePicker(true);
@@ -445,6 +451,18 @@ export function EmailComposer({
}
}, [client, t]);
const handleImageUpload = useCallback(async (file: File): Promise<string | null> => {
if (!client) return null;
try {
const { blobId } = await client.uploadBlob(file);
return await client.fetchBlobAsObjectUrl(blobId, file.name, file.type);
} catch (error) {
debug.error(`Failed to upload inline image ${file.name}:`, error);
toast.error(t('upload_failed', { filename: file.name }));
return null;
}
}, [client, t]);
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files) return;
await addFiles(Array.from(event.target.files));
@@ -511,7 +529,7 @@ export function EmailComposer({
const ccAddresses = cc.split(",").map(e => e.trim()).filter(Boolean);
const bccAddresses = bcc.split(",").map(e => e.trim()).filter(Boolean);
if (!toAddresses.length && !subject && !body) {
if (!toAddresses.length && !subject && !htmlToPlainText(body).trim()) {
return null;
}
@@ -547,7 +565,7 @@ export function EmailComposer({
const savedDraftId = await client.createDraft(
toAddresses,
subject || t('no_subject'),
body,
htmlToPlainText(body),
ccAddresses,
bccAddresses,
currentIdentity?.id,
@@ -611,7 +629,8 @@ export function EmailComposer({
}, []);
const toAddresses = to.split(",").map(e => e.trim()).filter(Boolean);
const hasContent = body || attachments.some(att => att.blobId && !att.uploading);
const bodyPlainText = htmlToPlainText(body).trim();
const hasContent = bodyPlainText || attachments.some(att => att.blobId && !att.uploading);
const canSend = toAddresses.length > 0 && !!subject && hasContent;
const getSendTooltip = (): string | undefined => {
@@ -660,26 +679,8 @@ export function EmailComposer({
: currentIdentity.email
: undefined;
// Append signature from the selected identity
let finalBody = appendPlainTextSignature(body, currentIdentity);
// Append quoted original text for the plain text part in reply/forward
if (replyTo && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
const originalText = replyTo.body || '';
if (originalText) {
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : '';
const fromAddr = replyTo.from?.[0];
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
if (mode === 'forward') {
finalBody += `\n\n---------- ${t('prefix.forward')} ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ''}\n\n${originalText}`;
} else {
finalBody += `\n\nOn ${date}, ${fromStr} wrote:\n> ${originalText.split('\n').join('\n> ')}`;
}
}
}
// Build HTML signature block (prefer htmlSignature, fall back to escaped textSignature)
// Body is already HTML from the rich text editor.
// Build HTML signature block
const buildSignatureHtml = (): string => {
if (currentIdentity?.htmlSignature) {
return `<br><br>-- <br>${sanitizeEmailHtml(currentIdentity.htmlSignature)}`;
@@ -690,26 +691,13 @@ export function EmailComposer({
return '';
};
// Build HTML body
let finalHtmlBody: string | undefined;
const signatureHtml = buildSignatureHtml();
if (replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
// Reply/forward with original HTML content
const escapedBody = body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : '';
const fromAddr = replyTo.from?.[0];
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
const quoteHeader = mode === 'forward'
? `---------- ${t('prefix.forward')} ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>`
: `On ${date}, ${fromStr} wrote:<br>`;
// Build final HTML body: editor content + signature
const finalHtmlBody = `<div>${body}</div>${signatureHtml}`;
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}<br><div><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote></div>`;
} else if (signatureHtml) {
// New compose or plain-text reply — include HTML body with signature
const escapedBody = body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}`;
}
// Generate plain text version from the HTML body for multipart/alternative
const finalBody = appendPlainTextSignature(htmlToPlainText(body), currentIdentity);
try {
// S/MIME send pipeline: build raw MIME → sign → encrypt → sendRawEmail
@@ -1107,23 +1095,17 @@ export function EmailComposer({
</div>
</div>
{/* Body */}
<div className="px-4 py-3">
<textarea
ref={textareaRef}
className={cn(
"w-full resize-none outline-none text-sm bg-transparent text-foreground placeholder:text-muted-foreground rounded min-h-[100px] overflow-hidden",
validationErrors.body && "ring-2 ring-red-500 dark:ring-red-400"
)}
placeholder={t('body_placeholder')}
value={body}
onChange={(e) => {
setBody(e.target.value);
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
}}
aria-invalid={validationErrors.body || undefined}
/>
</div>
{/* Body - Rich Text Editor */}
<RichTextEditor
content={body}
onChange={(html) => {
setBody(html);
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
}}
onImageUpload={handleImageUpload}
placeholder={t('body_placeholder')}
hasError={validationErrors.body}
/>
{composerSignatureHtml && (
<div
@@ -1131,23 +1113,6 @@ export function EmailComposer({
dangerouslySetInnerHTML={{ __html: `<div>-- </div>${composerSignatureHtml}` }}
/>
)}
{/* Quoted original HTML */}
{replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward') && (
<div className="border-t border-border">
<div className="px-4 py-2 text-xs text-muted-foreground">
{mode === 'forward'
? `---------- ${t('prefix.forward')} ----------`
: `${replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : ''}, ${replyTo.from?.[0]?.name || replyTo.from?.[0]?.email || tCommon('unknown')}:`
}
</div>
<div
className="email-reply-quote px-4 pb-3 border-l-2 border-muted-foreground/30 ml-4 max-w-none rounded"
style={{ backgroundColor: '#ffffff', color: '#1a1a1a', fontSize: '14px' }}
dangerouslySetInnerHTML={{ __html: sanitizeEmailHtml(replyTo.htmlBody) }}
/>
</div>
)}
</div>
{/* Attachments */}
+1 -1
View File
@@ -4449,7 +4449,7 @@ export function EmailViewer({
<iframe
ref={iframeRef}
srcDoc={emailIframeSrcDoc}
sandbox="allow-same-origin allow-popups"
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
title="Email content"
className="w-full border-0 rounded"
style={{ minHeight: '100px', colorScheme: isDark && emailHasNativeDarkMode ? 'light dark' : 'light' }}
+135
View File
@@ -0,0 +1,135 @@
"use client";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Node, mergeAttributes } from "@tiptap/core";
import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
function ResizableImageView({ node, updateAttributes, selected }: NodeViewProps) {
const imgRef = useRef<HTMLImageElement>(null);
const [resizing, setResizing] = useState(false);
const startState = useRef<{ x: number; y: number; width: number; height: number; handle: string }>({
x: 0, y: 0, width: 0, height: 0, handle: "",
});
const onMouseDown = useCallback((e: React.MouseEvent, handle: string) => {
e.preventDefault();
e.stopPropagation();
const img = imgRef.current;
if (!img) return;
startState.current = {
x: e.clientX,
y: e.clientY,
width: img.offsetWidth,
height: img.offsetHeight,
handle,
};
setResizing(true);
}, []);
useEffect(() => {
if (!resizing) return;
const onMouseMove = (e: MouseEvent) => {
const { x, width, handle } = startState.current;
const dx = e.clientX - x;
let newWidth: number;
if (handle === "right" || handle === "bottom-right" || handle === "top-right") {
newWidth = Math.max(50, width + dx);
} else {
newWidth = Math.max(50, width - dx);
}
updateAttributes({ width: Math.round(newWidth) });
};
const onMouseUp = () => {
setResizing(false);
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
return () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
};
}, [resizing, updateAttributes]);
const width = node.attrs.width;
const style: React.CSSProperties = {
...(width ? { width: `${width}px` } : {}),
maxWidth: "100%",
};
return (
<NodeViewWrapper as="span" className="inline-block relative" draggable data-drag-handle>
<span
className={`relative inline-block group ${selected ? "ring-2 ring-primary rounded" : ""}`}
style={style}
>
<img
ref={imgRef}
src={node.attrs.src}
alt={node.attrs.alt || ""}
title={node.attrs.title || undefined}
style={{ width: "100%", height: "auto", display: "block" }}
draggable={false}
/>
{selected && (
<>
{/* Resize handle: right */}
<span
onMouseDown={(e) => onMouseDown(e, "right")}
className="absolute top-1/2 -right-1.5 -translate-y-1/2 w-3 h-8 bg-primary rounded cursor-ew-resize"
/>
{/* Resize handle: left */}
<span
onMouseDown={(e) => onMouseDown(e, "left")}
className="absolute top-1/2 -left-1.5 -translate-y-1/2 w-3 h-8 bg-primary rounded cursor-ew-resize"
/>
{/* Resize handle: bottom-right corner */}
<span
onMouseDown={(e) => onMouseDown(e, "bottom-right")}
className="absolute -bottom-1.5 -right-1.5 w-3 h-3 bg-primary rounded cursor-nwse-resize"
/>
</>
)}
</span>
</NodeViewWrapper>
);
}
export const ResizableImage = Node.create({
name: "image",
group: "inline",
inline: true,
draggable: true,
selectable: true,
addAttributes() {
return {
src: { default: null },
alt: { default: null },
title: { default: null },
width: { default: null },
};
},
parseHTML() {
return [{ tag: "img[src]" }];
},
renderHTML({ HTMLAttributes }) {
const attrs: Record<string, string> = { ...HTMLAttributes };
if (attrs.width) {
attrs.style = `width: ${attrs.width}px; max-width: 100%;`;
delete attrs.width;
}
return ["img", mergeAttributes(attrs)];
},
addNodeView() {
return ReactNodeViewRenderer(ResizableImageView);
},
});
+337
View File
@@ -0,0 +1,337 @@
"use client";
import React, { useEffect, useCallback } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import Link from "@tiptap/extension-link";
import TextAlign from "@tiptap/extension-text-align";
import { TextStyle } from "@tiptap/extension-text-style";
import Color from "@tiptap/extension-color";
import { ResizableImage } from "@/components/email/resizable-image";
import Placeholder from "@tiptap/extension-placeholder";
import { cn } from "@/lib/utils";
import {
Bold,
Italic,
Underline as UnderlineIcon,
Strikethrough,
List,
ListOrdered,
AlignLeft,
AlignCenter,
AlignRight,
Link as LinkIcon,
Undo,
Redo,
Quote,
Code,
RemoveFormatting,
Heading1,
Heading2,
} from "lucide-react";
interface RichTextEditorProps {
content: string;
onChange: (html: string) => void;
onImageUpload?: (file: File) => Promise<string | null>;
placeholder?: string;
className?: string;
hasError?: boolean;
}
function ToolbarButton({
active,
onClick,
children,
title,
disabled,
}: {
active?: boolean;
onClick: () => void;
children: React.ReactNode;
title: string;
disabled?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
title={title}
className={cn(
"p-1.5 rounded hover:bg-accent transition-colors",
active && "bg-accent text-accent-foreground",
disabled && "opacity-40 cursor-not-allowed"
)}
>
{children}
</button>
);
}
function ToolbarSeparator() {
return <div className="w-px h-5 bg-border mx-0.5" />;
}
export function RichTextEditor({
content,
onChange,
onImageUpload,
placeholder,
className,
hasError,
}: RichTextEditorProps) {
const onImageUploadRef = React.useRef(onImageUpload);
onImageUploadRef.current = onImageUpload;
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: { levels: [1, 2] },
}),
Underline,
Link.configure({
openOnClick: false,
HTMLAttributes: { rel: "noopener noreferrer nofollow" },
}),
TextAlign.configure({
types: ["heading", "paragraph"],
}),
TextStyle,
Color,
ResizableImage,
Placeholder.configure({
placeholder,
}),
],
content,
editorProps: {
attributes: {
class: "tiptap min-h-[100px] px-4 py-3 text-sm text-foreground",
},
handleDrop: (view, event) => {
const upload = onImageUploadRef.current;
if (!upload || !event.dataTransfer?.files?.length) return false;
const imageFiles = Array.from(event.dataTransfer.files).filter(f =>
f.type.startsWith("image/")
);
if (imageFiles.length === 0) return false;
event.preventDefault();
for (const file of imageFiles) {
upload(file).then((url) => {
if (url) {
const { state } = view;
const pos = view.posAtCoords({ left: event.clientX, top: event.clientY });
const node = state.schema.nodes.image.create({ src: url, alt: file.name });
const tr = state.tr.insert(pos?.pos ?? state.selection.anchor, node);
view.dispatch(tr);
}
});
}
return true;
},
handlePaste: (view, event) => {
const upload = onImageUploadRef.current;
if (!upload || !event.clipboardData?.files?.length) return false;
const imageFiles = Array.from(event.clipboardData.files).filter(f =>
f.type.startsWith("image/")
);
if (imageFiles.length === 0) return false;
event.preventDefault();
for (const file of imageFiles) {
upload(file).then((url) => {
if (url) {
const { state } = view;
const node = state.schema.nodes.image.create({ src: url, alt: file.name });
const tr = state.tr.replaceSelectionWith(node);
view.dispatch(tr);
}
});
}
return true;
},
},
onUpdate: ({ editor }) => {
onChange(editor.getHTML());
},
immediatelyRender: false,
});
// Sync external content changes (e.g. template application)
useEffect(() => {
if (editor && content !== editor.getHTML()) {
editor.commands.setContent(content, { emitUpdate: false });
}
}, [content, editor]);
const addLink = useCallback(() => {
if (!editor) return;
const previousUrl = editor.getAttributes("link").href;
const url = window.prompt("URL", previousUrl);
if (url === null) return;
if (url === "") {
editor.chain().focus().extendMarkRange("link").unsetLink().run();
return;
}
editor
.chain()
.focus()
.extendMarkRange("link")
.setLink({ href: url })
.run();
}, [editor]);
if (!editor) {
return (
<div className={cn("min-h-[100px]", className)} />
);
}
return (
<div className={cn("flex flex-col", hasError && "ring-2 ring-red-500 dark:ring-red-400 rounded", className)}>
{/* Toolbar */}
<div className="flex flex-wrap items-center gap-0.5 px-3 py-1.5 border-b border-border/50 bg-muted/30">
<ToolbarButton
active={editor.isActive("bold")}
onClick={() => editor.chain().focus().toggleBold().run()}
title="Bold"
>
<Bold className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("italic")}
onClick={() => editor.chain().focus().toggleItalic().run()}
title="Italic"
>
<Italic className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("underline")}
onClick={() => editor.chain().focus().toggleUnderline().run()}
title="Underline"
>
<UnderlineIcon className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("strike")}
onClick={() => editor.chain().focus().toggleStrike().run()}
title="Strikethrough"
>
<Strikethrough className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive("heading", { level: 1 })}
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
title="Heading 1"
>
<Heading1 className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("heading", { level: 2 })}
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
title="Heading 2"
>
<Heading2 className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive("bulletList")}
onClick={() => editor.chain().focus().toggleBulletList().run()}
title="Bullet List"
>
<List className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("orderedList")}
onClick={() => editor.chain().focus().toggleOrderedList().run()}
title="Ordered List"
>
<ListOrdered className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("blockquote")}
onClick={() => editor.chain().focus().toggleBlockquote().run()}
title="Quote"
>
<Quote className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("codeBlock")}
onClick={() => editor.chain().focus().toggleCodeBlock().run()}
title="Code Block"
>
<Code className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive({ textAlign: "left" })}
onClick={() => editor.chain().focus().setTextAlign("left").run()}
title="Align Left"
>
<AlignLeft className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive({ textAlign: "center" })}
onClick={() => editor.chain().focus().setTextAlign("center").run()}
title="Align Center"
>
<AlignCenter className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive({ textAlign: "right" })}
onClick={() => editor.chain().focus().setTextAlign("right").run()}
title="Align Right"
>
<AlignRight className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive("link")}
onClick={addLink}
title="Link"
>
<LinkIcon className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
onClick={() => editor.chain().focus().clearNodes().unsetAllMarks().run()}
title="Clear Formatting"
>
<RemoveFormatting className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
onClick={() => editor.chain().focus().undo().run()}
disabled={!editor.can().undo()}
title="Undo"
>
<Undo className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
onClick={() => editor.chain().focus().redo().run()}
disabled={!editor.can().redo()}
title="Redo"
>
<Redo className="w-4 h-4" />
</ToolbarButton>
</div>
{/* Editor */}
<EditorContent editor={editor} />
</div>
);
}
+31 -8
View File
@@ -21,6 +21,7 @@ import { loadFilesSettings } from "@/components/files/files-settings-dialog";
import type { FolderLayout } from "@/components/files/files-settings-dialog";
import { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
import type { FileResource } from "@/stores/file-store";
type SortKey = "name" | "size" | "modified";
@@ -624,16 +625,20 @@ export function FileBrowser({
e.stopPropagation();
setIsDraggingOver(false);
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
setIsUploading(true);
try {
await onUploadFiles(files);
} finally {
setIsUploading(false);
setIsUploading(true);
try {
const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
if (files.length > 0) {
if (hasDirectories) {
await onUploadFolder(files);
} else {
await onUploadFiles(files);
}
}
} finally {
setIsUploading(false);
}
}, [onUploadFiles]);
}, [onUploadFiles, onUploadFolder]);
const handleFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
@@ -945,6 +950,16 @@ export function FileBrowser({
>
<Upload className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => folderInputRef.current?.click()}
title={t("upload_folder")}
disabled={isUploading}
>
<FolderUp className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
@@ -1195,6 +1210,14 @@ export function FileBrowser({
setIsUploading(false);
}
}}
onUploadFolder={async (files: File[]) => {
setIsUploading(true);
try {
await onUploadFolder(files);
} finally {
setIsUploading(false);
}
}}
onCreateFolder={() => setShowNewFolder(true)}
onCreateTextFile={() => setShowNewTextFile(true)}
/>
+11 -5
View File
@@ -2,16 +2,18 @@
import { useCallback, useState } from "react";
import { useTranslations } from "next-intl";
import { Upload, FolderPlus, FilePlus } from "lucide-react";
import { Upload, FolderPlus, FilePlus, FolderUp } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
interface FileUploadAreaProps {
onUpload: (files: File[]) => Promise<void>;
onUploadFolder?: (files: File[]) => Promise<void>;
onCreateFolder: () => void;
onCreateTextFile?: () => void;
}
export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
export function FileUploadArea({ onUpload, onUploadFolder, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
const t = useTranslations("files");
const [isDragging, setIsDragging] = useState(false);
@@ -32,11 +34,15 @@ export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: F
e.stopPropagation();
setIsDragging(false);
const files = Array.from(e.dataTransfer.files);
const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
if (files.length > 0) {
await onUpload(files);
if (hasDirectories && onUploadFolder) {
await onUploadFolder(files);
} else {
await onUpload(files);
}
}
}, [onUpload]);
}, [onUpload, onUploadFolder]);
return (
<div className="flex items-center justify-center h-full p-8">
+5 -1
View File
@@ -42,7 +42,11 @@ export function ImagePreviewModal({ name, onClose, onDownload, getImageUrl }: Im
}, [name, getImageUrl]);
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
if (e.key === "Escape") { onClose(); return; }
const target = e.target as HTMLElement;
const tag = target?.tagName?.toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select") return;
if (target?.getAttribute("contenteditable") === "true") return;
if (e.key === "+" || e.key === "=") setZoom((z) => Math.min(z + 0.25, 5));
if (e.key === "-") setZoom((z) => Math.max(z - 0.25, 0.25));
if (e.key === "r") setRotation((r) => r + 90);
-4
View File
@@ -101,15 +101,11 @@ export function AccountSwitcher({ variant = "rail", className }: AccountSwitcher
const handleLogout = () => {
setOpen(false);
logout();
if (useAccountStore.getState().accounts.length === 0) {
router.push("/login" as never);
}
};
const handleLogoutAll = () => {
setOpen(false);
logoutAll();
router.push("/login" as never);
};
const handleSetDefault = (accountId: string) => {
@@ -0,0 +1,34 @@
"use client";
import { useEffect } from "react";
import { isEmbedded, listenFromParent } from "@/lib/iframe-bridge";
import { useAuthStore } from "@/stores/auth-store";
import { useConfig } from "@/hooks/use-config";
export function EmbeddedBridgeProvider({ children }: { children: React.ReactNode }) {
const { parentOrigin, embeddedMode } = useConfig();
const logout = useAuthStore((s) => s.logout);
useEffect(() => {
if (!embeddedMode || !isEmbedded()) return;
const unsubscribe = listenFromParent((msg) => {
switch (msg.type) {
case "sso:trigger-login": {
// Navigate to login page to start SSO flow
const segments = window.location.pathname.split("/").filter(Boolean);
const locale = segments[0] || "en";
window.location.href = `/${locale}/login`;
break;
}
case "sso:trigger-logout":
logout();
break;
}
}, parentOrigin || undefined);
return unsubscribe;
}, [embeddedMode, parentOrigin, logout]);
return <>{children}</>;
}
+35
View File
@@ -15,9 +15,12 @@ export function CalendarSettings() {
timeFormat,
firstDayOfWeek,
showTimeInMonthView,
showWeekNumbers,
calendarNotificationsEnabled,
calendarNotificationSound,
calendarInvitationParsingEnabled,
enableCalendarTasks,
showTasksOnCalendar,
updateSetting,
} = useSettingsStore();
@@ -68,6 +71,38 @@ export function CalendarSettings() {
/>
</SettingItem>
<SettingItem
label={t('show_week_numbers')}
description={t('show_week_numbers_desc')}
>
<ToggleSwitch
checked={showWeekNumbers}
onChange={(checked) => updateSetting('showWeekNumbers', checked)}
/>
</SettingItem>
<SettingItem
label={t('enable_tasks')}
description={t('enable_tasks_desc')}
>
<ToggleSwitch
checked={enableCalendarTasks}
onChange={(checked) => updateSetting('enableCalendarTasks', checked)}
/>
</SettingItem>
{enableCalendarTasks && (
<SettingItem
label={t('show_tasks_on_calendar')}
description={t('show_tasks_on_calendar_desc')}
>
<ToggleSwitch
checked={showTasksOnCalendar}
onChange={(checked) => updateSetting('showTasksOnCalendar', checked)}
/>
</SettingItem>
)}
<SettingItem
label={t('notifications_enabled')}
description={t('notifications_enabled_desc')}
+118 -31
View File
@@ -9,6 +9,7 @@ import { SieveEditorModal } from "@/components/filters/sieve-editor-modal";
import { useFilterStore } from "@/stores/filter-store";
import { useAuthStore } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store";
import { toast } from "@/stores/toast-store";
import type { FilterRule } from "@/lib/jmap/sieve-types";
import {
@@ -25,31 +26,98 @@ import {
function RuleSummary({ rule }: { rule: FilterRule }) {
const t = useTranslations("settings.filters");
const conditionSummary = rule.conditions
.slice(0, 2)
.map((c) => {
const field = t(`condition_fields.${c.field}`);
const comparator = t(`comparators.${c.comparator}`);
return `${field} ${comparator} "${c.value}"`;
})
.join(rule.matchType === "all" ? ` ${t("and")} ` : ` ${t("or")} `);
const conditions = rule.conditions.slice(0, 2).map((c) => {
const field = t(`condition_fields.${c.field}`);
const comparator = t(`comparators.${c.comparator}`);
return `${field} ${comparator} "${c.value}"`;
});
const joiner = rule.matchType === "all" ? t("and") : t("or");
const extra = rule.conditions.length > 2
? ` (+${rule.conditions.length - 2})`
: "";
const actionSummary = rule.actions
.slice(0, 2)
.map((a) => {
const action = t(`action_types.${a.type}`);
return a.value ? `${action} "${a.value}"` : action;
})
.join(", ");
const actions = rule.actions.slice(0, 2).map((a) => {
const action = t(`action_types.${a.type}`);
return a.value ? `${action} "${a.value}"` : action;
});
return (
<span className="text-xs text-muted-foreground truncate">
{conditionSummary}{extra} {actionSummary}
</span>
<div className="text-xs text-muted-foreground break-words">
<span className="inline">
{conditions.map((cond, i) => (
<span key={i}>
{i > 0 && <span className="italic opacity-70"> {joiner} </span>}
{cond}
</span>
))}
{extra}
</span>
<span className="mx-1 opacity-50"></span>
<span className="inline">
{actions.map((act, i) => (
<span key={i}>
{i > 0 && ", "}
{act}
</span>
))}
</span>
</div>
);
}
function VisualRuleSummary({ rule }: { rule: FilterRule }) {
const t = useTranslations("settings.filters");
const joiner = rule.matchType === "all" ? t("and") : t("or");
const matchLabel = rule.matchType === "all" ? t("match_all_conditions") : t("match_any_condition");
return (
<div className="mt-1.5 space-y-1 text-xs">
<div className="flex items-baseline gap-1.5 flex-wrap">
<span className="text-[10px] font-semibold uppercase tracking-wider text-blue-500 dark:text-blue-400">
{t("if")}
</span>
{rule.conditions.map((c, i) => {
const field = t(`condition_fields.${c.field}`);
const comparator = t(`comparators.${c.comparator}`);
return (
<span key={i} className="contents">
{i > 0 && (
<span className="text-[10px] text-muted-foreground/70 italic">{joiner}</span>
)}
<span className="inline-flex items-baseline gap-1 px-1.5 py-px rounded-sm bg-muted/60 text-foreground">
<span className="font-medium text-blue-600 dark:text-blue-400">{field}</span>
<span className="text-muted-foreground">{comparator}</span>
<span className="text-foreground">{c.value}</span>
</span>
</span>
);
})}
<span className="text-[10px] text-muted-foreground/60 italic">({matchLabel})</span>
</div>
<div className="flex items-baseline gap-1.5 flex-wrap">
<span className="text-[10px] font-semibold uppercase tracking-wider text-emerald-500 dark:text-emerald-400">
{t("then")}
</span>
{rule.actions.map((a, i) => {
const action = t(`action_types.${a.type}`);
return (
<span key={i} className="contents">
{i > 0 && (
<span className="text-muted-foreground/50"></span>
)}
<span className="inline-flex items-baseline gap-1 px-1.5 py-px rounded-sm bg-muted/60 text-foreground">
<span className="font-medium text-emerald-600 dark:text-emerald-400">{action}</span>
{a.value && <span className="text-muted-foreground">{a.value}</span>}
</span>
</span>
);
})}
</div>
</div>
);
}
@@ -58,6 +126,8 @@ export function FilterSettings() {
const tNotifications = useTranslations("notifications");
const { client } = useAuthStore();
const mailboxes = useEmailStore((s) => s.mailboxes);
const expandedFilterView = useSettingsStore((s) => s.expandedFilterView);
const updateSetting = useSettingsStore((s) => s.updateSetting);
const {
rules,
@@ -337,23 +407,25 @@ export function FilterSettings() {
onDragOver={(e) => handleDragOver(e, index)}
onDrop={(e) => handleDrop(e, index)}
onDragEnd={handleDragEnd}
className={`flex items-center gap-3 p-3 rounded-md border transition-colors ${
className={`flex items-start gap-3 p-3 rounded-md border transition-colors ${
dragOverIndex === index
? "border-primary bg-primary/5"
: "border-border hover:bg-muted/50"
} ${!rule.enabled ? "opacity-60" : ""}`}
>
<div
className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground"
className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground pt-0.5"
aria-label={t("drag_to_reorder")}
>
<GripVertical className="w-4 h-4" />
</div>
<ToggleSwitch
checked={rule.enabled}
onChange={() => handleToggle(rule.id)}
/>
<div className="pt-0.5">
<ToggleSwitch
checked={rule.enabled}
onChange={() => handleToggle(rule.id)}
/>
</div>
<div
className="flex-1 min-w-0 cursor-pointer"
@@ -374,7 +446,11 @@ export function FilterSettings() {
<p className="text-sm font-medium text-foreground truncate">
{rule.name}
</p>
<RuleSummary rule={rule} />
{expandedFilterView ? (
<VisualRuleSummary rule={rule} />
) : (
<RuleSummary rule={rule} />
)}
</div>
{deleteConfirmId === rule.id ? (
@@ -435,12 +511,23 @@ export function FilterSettings() {
</Button>
</div>
{isSaving && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" />
{t("saving")}
</div>
)}
<div className="flex items-center gap-3">
{isSaving && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" />
{t("saving")}
</div>
)}
{!isOpaque && rules.length > 0 && (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{t("expanded_view")}</span>
<ToggleSwitch
checked={expandedFilterView}
onChange={(v) => updateSetting("expandedFilterView", v)}
/>
</div>
)}
</div>
</div>
{showRuleModal && (
+34 -2
View File
@@ -5,9 +5,10 @@ import { useTranslations, useLocale } from 'next-intl';
import { useAuthStore } from '@/stores/auth-store';
import { useCalendarStore } from '@/stores/calendar-store';
import { useSettingsStore } from '@/stores/settings-store';
import { useTaskStore } from '@/stores/task-store';
import { useCalendarNotificationStore } from '@/stores/calendar-notification-store';
import { useToastStore } from '@/stores/toast-store';
import { getPendingAlerts, buildAlertKey } from '@/lib/calendar-alerts';
import { getPendingAlerts, getPendingTaskAlerts, buildAlertKey } from '@/lib/calendar-alerts';
import { playNotificationSound } from '@/lib/notification-sound';
import type { CalendarEvent } from '@/lib/jmap/types';
@@ -18,7 +19,8 @@ const PROACTIVE_THROTTLE_MS = CHECK_INTERVAL_MS * 5;
export function useCalendarAlerts() {
const { isAuthenticated, client } = useAuthStore();
const { events, calendars, supportsCalendar } = useCalendarStore();
const { calendarNotificationsEnabled, calendarNotificationSound } = useSettingsStore();
const { calendarNotificationsEnabled, calendarNotificationSound, enableCalendarTasks } = useSettingsStore();
const { tasks: storeTasks } = useTaskStore();
const { acknowledgedAlerts, acknowledgeAlert, cleanupStaleAlerts } = useCalendarNotificationStore();
const addToast = useToastStore((s) => s.addToast);
const t = useTranslations('calendar.notifications');
@@ -69,6 +71,36 @@ export function useCalendarAlerts() {
},
});
}
// Task alerts
if (enableCalendarTasks && storeTasks.length > 0) {
const pendingTaskAlerts = getPendingTaskAlerts(storeTasks, calendars, acknowledgedKeys, now);
for (const taskAlert of pendingTaskAlerts) {
const key = buildAlertKey(taskAlert.taskId, taskAlert.alertId, taskAlert.fireTimeMs);
if (shownKeysRef.current.has(key)) continue;
shownKeysRef.current.add(key);
acknowledgeAlert(key, taskAlert.fireTimeMs);
if (calendarNotificationSound) {
playNotificationSound();
}
const taskMsg = taskAlert.calendarName
? `${t('task_due')} · ${taskAlert.calendarName}`
: t('task_due');
addToast({
type: 'info',
title: taskAlert.task.title || t('alert_title'),
message: taskMsg,
duration: 15000,
onClick: () => {
window.location.href = `/${locale}/calendar`;
},
});
}
}
} catch {
// Silently ignore alert evaluation errors
}
+12
View File
@@ -23,6 +23,9 @@ interface ConfigData {
loginPrivacyPolicyUrl: string;
loginWebsiteUrl: string;
demoMode: boolean;
autoSsoEnabled: boolean;
embeddedMode: boolean;
parentOrigin: string;
}
interface AppConfig extends ConfigData {
@@ -93,6 +96,9 @@ export function useConfig(): AppConfig {
loginPrivacyPolicyUrl: configCache?.loginPrivacyPolicyUrl || '',
loginWebsiteUrl: configCache?.loginWebsiteUrl || '',
demoMode: configCache?.demoMode || false,
autoSsoEnabled: configCache?.autoSsoEnabled || false,
embeddedMode: configCache?.embeddedMode || false,
parentOrigin: configCache?.parentOrigin || '',
isLoading: !configCache,
error: null,
});
@@ -121,6 +127,9 @@ export function useConfig(): AppConfig {
loginPrivacyPolicyUrl: configCache.loginPrivacyPolicyUrl,
loginWebsiteUrl: configCache.loginWebsiteUrl,
demoMode: configCache.demoMode,
autoSsoEnabled: configCache.autoSsoEnabled,
embeddedMode: configCache.embeddedMode,
parentOrigin: configCache.parentOrigin,
isLoading: false,
error: null,
});
@@ -150,6 +159,9 @@ export function useConfig(): AppConfig {
loginPrivacyPolicyUrl: data.loginPrivacyPolicyUrl,
loginWebsiteUrl: data.loginWebsiteUrl,
demoMode: data.demoMode,
autoSsoEnabled: data.autoSsoEnabled,
embeddedMode: data.embeddedMode,
parentOrigin: data.parentOrigin,
isLoading: false,
error: null,
});
+8 -3
View File
@@ -122,10 +122,15 @@ describe('JMAPClient contact methods', () => {
describe('getContacts', () => {
it('should return contacts from server', async () => {
const client = createClient();
mockFetch({
const spy = vi.spyOn(globalThis, 'fetch');
mockFetchOnce(spy, {
methodResponses: [
['ContactCard/query', { ids: ['contact-1'] }, '0'],
['ContactCard/get', { list: [mockContact] }, '1'],
['ContactCard/query', { ids: ['contact-1'] }, 'q'],
],
});
mockFetchOnce(spy, {
methodResponses: [
['ContactCard/get', { list: [mockContact] }, 'g'],
],
});
+35
View File
@@ -48,3 +48,38 @@ export function decryptSession(token: string): { serverUrl: string; username: st
return null;
}
}
export function encryptPayload(payload: Record<string, unknown>): string {
const key = getKey();
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv);
const json = JSON.stringify(payload);
const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]).toString('base64');
}
export function decryptPayload(token: string): Record<string, unknown> | null {
try {
const key = getKey();
const data = Buffer.from(token, 'base64');
if (data.length < IV_LENGTH + TAG_LENGTH) return null;
const iv = data.subarray(0, IV_LENGTH);
const tag = data.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
const encrypted = data.subarray(IV_LENGTH + TAG_LENGTH);
const decipher = createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return JSON.parse(decrypted.toString('utf8'));
} catch (error) {
logger.warn('Payload decryption failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return null;
}
}
+66
View File
@@ -4,6 +4,7 @@ import type {
CalendarOffsetTrigger,
CalendarAbsoluteTrigger,
Calendar,
CalendarTask,
} from '@/lib/jmap/types';
export interface PendingAlert {
@@ -121,3 +122,68 @@ export function getPendingAlerts(
return pending;
}
export interface PendingTaskAlert {
taskId: string;
alertId: string;
fireTimeMs: number;
task: CalendarTask;
calendarName: string | null;
}
export function computeTaskFireTime(
task: CalendarTask,
trigger: CalendarOffsetTrigger | CalendarAbsoluteTrigger
): number | null {
if (trigger['@type'] === 'AbsoluteTrigger') {
const t = new Date(trigger.when).getTime();
return Number.isNaN(t) ? null : t;
}
const offsetMs = parseAlertOffset(trigger.offset);
if (offsetMs === null) return null;
if (!task.due) return null;
const baseTime = new Date(task.due).getTime();
if (Number.isNaN(baseTime)) return null;
return baseTime + offsetMs;
}
export function getPendingTaskAlerts(
tasks: CalendarTask[],
calendars: Calendar[],
acknowledgedKeys: Set<string>,
now: number
): PendingTaskAlert[] {
const pending: PendingTaskAlert[] = [];
for (const task of tasks) {
if (!task.alerts) continue;
if (task.progress === 'completed' || task.progress === 'cancelled') continue;
const calendar = calendars.find(c => c.id === Object.keys(task.calendarIds)[0]) ?? null;
for (const [alertId, alert] of Object.entries(task.alerts)) {
if (alert.action !== 'display') continue;
if (alert.acknowledged) continue;
const fireTimeMs = computeTaskFireTime(task, alert.trigger);
if (fireTimeMs === null) continue;
if (fireTimeMs > now) continue;
if (fireTimeMs <= now - STALE_THRESHOLD_MS) continue;
const key = buildAlertKey(task.id, alertId, fireTimeMs);
if (acknowledgedKeys.has(key)) continue;
pending.push({
taskId: task.id,
alertId,
fireTimeMs,
task,
calendarName: calendar?.name ?? null,
});
}
}
return pending;
}
+50 -1
View File
@@ -1,5 +1,5 @@
import type { IJMAPClient } from '@/lib/jmap/client-interface';
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, FileNode } from '@/lib/jmap/types';
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, CalendarTask, FileNode } from '@/lib/jmap/types';
import type { SieveScript, SieveCapabilities } from '@/lib/jmap/sieve-types';
import { getDemoData, type DemoData } from './demo-data';
import { generateDemoId } from './demo-utils';
@@ -621,6 +621,55 @@ export class DemoJMAPClient implements IJMAPClient {
return []; // no-op in demo
}
// ── Calendar Tasks ────────────────────────────────────────────
async getCalendarTasks(calendarIds?: string[]): Promise<CalendarTask[]> {
let tasks = this.data.calendarTasks || [];
if (calendarIds) {
tasks = tasks.filter(t => Object.keys(t.calendarIds).some(id => calendarIds.includes(id)));
}
return [...tasks];
}
async createCalendarTask(task: Partial<CalendarTask>): Promise<CalendarTask> {
const full: CalendarTask = {
id: generateDemoId('task'),
uid: generateDemoId('task-uid'),
'@type': 'Task',
calendarIds: task.calendarIds || { [this.data.calendars[0]?.id || 'cal-1']: true },
title: task.title || '',
description: task.description || '',
due: task.due || null,
start: task.start || null,
duration: task.duration || null,
timeZone: task.timeZone || null,
showWithoutTime: task.showWithoutTime ?? true,
progress: task.progress || 'needs-action',
progressUpdated: null,
priority: task.priority || 0,
privacy: task.privacy || 'public',
keywords: task.keywords || null,
categories: task.categories || null,
color: task.color || null,
created: new Date().toISOString(),
updated: new Date().toISOString(),
recurrenceRules: task.recurrenceRules || null,
alerts: task.alerts || null,
relatedTo: task.relatedTo || null,
};
this.data.calendarTasks.push(full);
return full;
}
async updateCalendarTask(taskId: string, updates: Partial<CalendarTask>): Promise<void> {
const task = this.data.calendarTasks.find(t => t.id === taskId);
if (task) Object.assign(task, updates, { updated: new Date().toISOString() });
}
async deleteCalendarTask(taskId: string): Promise<void> {
this.data.calendarTasks = this.data.calendarTasks.filter(t => t.id !== taskId);
}
// ── Sieve / Filters ──────────────────────────────────────────
getSieveAccountId(): string { return 'demo-account'; }
+4 -1
View File
@@ -3,12 +3,13 @@ import { createDemoMailboxes } from './fixtures/mailboxes';
import { createDemoEmails } from './fixtures/emails';
import { createDemoContacts, createDemoAddressBooks } from './fixtures/contacts';
import { createDemoCalendars, createDemoCalendarEvents } from './fixtures/calendars';
import { createDemoCalendarTasks } from './fixtures/tasks';
import { createDemoIdentities } from './fixtures/identities';
import { createDemoSieveScripts, createDemoSieveCapabilities, createDemoSieveContent } from './fixtures/filters';
import { createDemoFileNodes } from './fixtures/files';
import { createDemoVacationResponse } from './fixtures/vacation';
import type { Email, Mailbox, ContactCard, AddressBook, Calendar, CalendarEvent, Identity, VacationResponse, FileNode } from '@/lib/jmap/types';
import type { Email, Mailbox, ContactCard, AddressBook, Calendar, CalendarEvent, CalendarTask, Identity, VacationResponse, FileNode } from '@/lib/jmap/types';
import type { SieveScript, SieveCapabilities } from '@/lib/jmap/sieve-types';
export interface DemoData {
@@ -18,6 +19,7 @@ export interface DemoData {
addressBooks: AddressBook[];
calendars: Calendar[];
calendarEvents: CalendarEvent[];
calendarTasks: CalendarTask[];
identities: Identity[];
sieveScripts: SieveScript[];
sieveCapabilities: SieveCapabilities;
@@ -35,6 +37,7 @@ export function getDemoData(): DemoData {
addressBooks: createDemoAddressBooks(),
calendars: createDemoCalendars(),
calendarEvents: createDemoCalendarEvents(),
calendarTasks: createDemoCalendarTasks(),
identities: createDemoIdentities(),
sieveScripts: createDemoSieveScripts(),
sieveCapabilities: createDemoSieveCapabilities(),
+140
View File
@@ -0,0 +1,140 @@
import type { CalendarTask } from '@/lib/jmap/types';
import { demoDate } from '../demo-utils';
export function createDemoCalendarTasks(): CalendarTask[] {
return [
{
id: 'demo-task-1',
calendarIds: { 'demo-calendar-personal': true },
'@type': 'Task',
uid: 'demo-task-uid-1',
title: 'Buy groceries',
description: 'Milk, bread, eggs, and vegetables',
due: demoDate(0, 2),
start: null,
duration: null,
timeZone: null,
showWithoutTime: false,
progress: 'needs-action',
progressUpdated: null,
priority: 0,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-3),
updated: demoDate(-1),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
{
id: 'demo-task-2',
calendarIds: { 'demo-calendar-work': true },
'@type': 'Task',
uid: 'demo-task-uid-2',
title: 'Prepare quarterly report',
description: 'Compile Q4 metrics and send to team',
due: demoDate(1, 4),
start: null,
duration: null,
timeZone: null,
showWithoutTime: false,
progress: 'in-process',
progressUpdated: demoDate(-1),
priority: 1,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-5),
updated: demoDate(0),
recurrenceRules: null,
alerts: {
'demo-alert-1': {
'@type': 'Alert',
trigger: { '@type': 'OffsetTrigger', offset: '-PT15M', relativeTo: 'start' },
action: 'display',
acknowledged: null,
relatedTo: null,
},
},
relatedTo: null,
},
{
id: 'demo-task-3',
calendarIds: { 'demo-calendar-personal': true },
'@type': 'Task',
uid: 'demo-task-uid-3',
title: 'Schedule dentist appointment',
description: '',
due: demoDate(3),
start: null,
duration: null,
timeZone: null,
showWithoutTime: true,
progress: 'needs-action',
progressUpdated: null,
priority: 5,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-2),
updated: demoDate(-2),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
{
id: 'demo-task-4',
calendarIds: { 'demo-calendar-work': true },
'@type': 'Task',
uid: 'demo-task-uid-4',
title: 'Review pull requests',
description: 'Review open PRs from the team',
due: demoDate(-1),
start: null,
duration: null,
timeZone: null,
showWithoutTime: true,
progress: 'completed',
progressUpdated: demoDate(0),
priority: 0,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-4),
updated: demoDate(0),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
{
id: 'demo-task-5',
calendarIds: { 'demo-calendar-personal': true },
'@type': 'Task',
uid: 'demo-task-uid-5',
title: 'Pay electricity bill',
description: '',
due: demoDate(-2),
start: null,
duration: null,
timeZone: null,
showWithoutTime: true,
progress: 'needs-action',
progressUpdated: null,
priority: 1,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-7),
updated: demoDate(-7),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
];
}
+40
View File
@@ -0,0 +1,40 @@
const PARENT_ORIGIN = typeof window !== 'undefined'
? (document.querySelector('meta[name="parent-origin"]')?.getAttribute('content') || '')
: '';
export function isEmbedded(): boolean {
try {
return window.self !== window.top;
} catch {
return true;
}
}
export function notifyParent(type: string, payload: Record<string, unknown> = {}) {
if (!isEmbedded()) return;
const targetOrigin = PARENT_ORIGIN || '*';
try {
window.parent.postMessage({ source: 'bulwark', type, ...payload }, targetOrigin);
} catch {
// Cross-origin postMessage may fail in restricted contexts
}
}
export function listenFromParent(
handler: (msg: { type: string; [k: string]: unknown }) => void,
allowedOrigin?: string,
): () => void {
const listener = (event: MessageEvent) => {
// Validate origin if configured
if (allowedOrigin && event.origin !== allowedOrigin) return;
// Only accept messages from the portal
if (!event.data || event.data.source !== 'portal') return;
handler(event.data);
};
window.addEventListener('message', listener);
return () => window.removeEventListener('message', listener);
}
+7 -1
View File
@@ -1,4 +1,4 @@
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, FileNode } from "./types";
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, CalendarTask, FileNode } from "./types";
import type { SieveScript, SieveCapabilities } from "./sieve-types";
/**
@@ -201,6 +201,12 @@ export interface IJMAPClient {
queryAllCalendarEvents(filter: CalendarEventFilter, sort?: Array<{ property: string; isAscending: boolean }>, limit?: number): Promise<CalendarEvent[]>;
parseCalendarEvents(accountId: string, blobId: string): Promise<Partial<CalendarEvent>[]>;
// ── Calendar Tasks ────────────────────────────────────────────
getCalendarTasks(calendarIds?: string[], targetAccountId?: string): Promise<CalendarTask[]>;
createCalendarTask(task: Partial<CalendarTask>, targetAccountId?: string): Promise<CalendarTask>;
updateCalendarTask(taskId: string, updates: Partial<CalendarTask>, targetAccountId?: string): Promise<void>;
deleteCalendarTask(taskId: string, targetAccountId?: string): Promise<void>;
// ── Sieve / Filters ──────────────────────────────────────────
getSieveAccountId(): string;
getSieveCapabilities(): SieveCapabilities | null;
+29 -1
View File
@@ -1,4 +1,4 @@
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, FileNode, FileNodeFilter } from "./types";
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, CalendarTask, FileNode, FileNodeFilter } from "./types";
import type { SieveScript, SieveCapabilities } from "./sieve-types";
import type { IJMAPClient } from "./client-interface";
import { toWildcardQuery } from "./search-utils";
@@ -3173,6 +3173,34 @@ export class JMAPClient implements IJMAPClient {
return { destroyed, notDestroyed };
}
// ─── Calendar Tasks (JSCalendar Task objects via CalendarEvent endpoints) ───
async getCalendarTasks(calendarIds?: string[], targetAccountId?: string): Promise<CalendarTask[]> {
try {
const events = await this.getCalendarEvents(calendarIds, targetAccountId);
return events.filter((e): e is CalendarTask & CalendarEvent =>
(e as unknown as CalendarTask)['@type'] === 'Task'
) as unknown as CalendarTask[];
} catch (error) {
console.error('Failed to get calendar tasks:', error);
return [];
}
}
async createCalendarTask(task: Partial<CalendarTask>, targetAccountId?: string): Promise<CalendarTask> {
const event = { ...task, '@type': 'Task' } as unknown as Partial<CalendarEvent>;
const created = await this.createCalendarEvent(event, false, targetAccountId);
return created as unknown as CalendarTask;
}
async updateCalendarTask(taskId: string, updates: Partial<CalendarTask>, targetAccountId?: string): Promise<void> {
await this.updateCalendarEvent(taskId, updates as unknown as Partial<CalendarEvent>, false, targetAccountId);
}
async deleteCalendarTask(taskId: string, targetAccountId?: string): Promise<void> {
await this.deleteCalendarEvent(taskId, false, targetAccountId);
}
// ─── JMAP FileNode methods (draft-ietf-jmap-filenode) ───
supportsFiles(): boolean {
+11
View File
@@ -0,0 +1,11 @@
const COOKIE_SAME_SITE = (process.env.COOKIE_SAME_SITE || 'lax') as 'lax' | 'none' | 'strict';
export function getCookieOptions() {
return {
httpOnly: true,
secure: COOKIE_SAME_SITE === 'none' ? true : process.env.NODE_ENV === 'production',
sameSite: COOKIE_SAME_SITE,
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
}
+18
View File
@@ -0,0 +1,18 @@
import { randomBytes, createHash } from 'node:crypto';
function base64urlEncode(buffer: Buffer): string {
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function generateCodeVerifierServer(): string {
return base64urlEncode(randomBytes(32));
}
export function generateCodeChallengeServer(verifier: string): string {
const hash = createHash('sha256').update(verifier).digest();
return base64urlEncode(hash);
}
export function generateStateServer(): string {
return base64urlEncode(randomBytes(32));
}
+88
View File
@@ -0,0 +1,88 @@
import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery';
import type { OAuthMetadata } from '@/lib/oauth/discovery';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
export function getRequiredConfig() {
const clientId = process.env.OAUTH_CLIENT_ID;
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
const issuerUrl = process.env.OAUTH_ISSUER_URL;
if (!clientId || !serverUrl) {
throw new Error(`OAuth misconfigured: ${[!clientId && 'OAUTH_CLIENT_ID', !serverUrl && 'JMAP_SERVER_URL'].filter(Boolean).join(', ')} not set`);
}
const discoveryUrl = issuerUrl?.trim() || serverUrl;
if (issuerUrl !== undefined && !issuerUrl.trim()) {
logger.warn('OAUTH_ISSUER_URL is set but empty, falling back to JMAP_SERVER_URL for discovery');
}
return { clientId, serverUrl, discoveryUrl };
}
export async function getTokenEndpoint(): Promise<string> {
const { discoveryUrl } = getRequiredConfig();
const metadata = await discoverOAuth(discoveryUrl);
if (!metadata?.token_endpoint) {
throw new Error('OAuth token endpoint not found');
}
return metadata.token_endpoint;
}
export async function getMetadata(): Promise<OAuthMetadata | null> {
const { discoveryUrl } = getRequiredConfig();
return discoverOAuth(discoveryUrl);
}
export function buildOAuthParams(base: Record<string, string>): URLSearchParams {
const { clientId } = getRequiredConfig();
const params = new URLSearchParams({ ...base, client_id: clientId });
if (CLIENT_SECRET) {
params.set('client_secret', CLIENT_SECRET);
}
return params;
}
export interface TokenResult {
access_token: string;
expires_in: number;
refresh_token?: string;
}
export async function exchangeCodeForTokens(
code: string,
codeVerifier: string,
redirectUri: string,
): Promise<TokenResult> {
const tokenEndpoint = await getTokenEndpoint();
const params = buildOAuthParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
});
const tokenResponse = await fetch(tokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params.toString(),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
logger.error('Token exchange failed', { status: tokenResponse.status, error: errorText });
throw new Error('Token exchange failed');
}
const tokens = await tokenResponse.json();
if (!tokens.access_token) {
logger.error('Token response missing access_token', { response: JSON.stringify(tokens).substring(0, 500) });
throw new Error('Invalid token response');
}
return {
access_token: tokens.access_token,
expires_in: tokens.expires_in || 3600,
refresh_token: tokens.refresh_token,
};
}
+45 -3
View File
@@ -145,11 +145,50 @@ function passwordToBMP(password: ArrayBuffer): Uint8Array {
return bmp;
}
// ── CMS content encryption OIDs (for EnvelopedData decryption) ─────
const OID_DES_EDE3_CBC = '1.2.840.113549.3.7'; // des-EDE3-CBC (3DES)
const OID_DES_CBC = '1.3.14.3.2.7'; // desCBC
const OID_RC2_CBC = '1.2.840.113549.3.2'; // rc2CBC
/**
* Extended CryptoEngine that handles legacy PKCS#12 PBE algorithms.
* Falls through to the base CryptoEngine for everything else.
* Extended CryptoEngine that handles legacy algorithms (3DES, etc.)
* not recognized by pkijs's default CryptoEngine.
*
* - Adds OIDalgorithm mappings for DES-EDE3-CBC so that
* EnvelopedData.decrypt() can process 3DES-encrypted S/MIME messages.
* - Handles legacy PKCS#12 PBE algorithms via custom KDF.
*/
class Pkcs12CryptoEngine extends pkijs.CryptoEngine {
/**
* Extend OIDalgorithm mapping with legacy algorithms that webcrypto-liner
* supports but pkijs does not know about.
*/
getAlgorithmByOID(oid: string, safety?: boolean, target?: string): object {
switch (oid) {
case OID_DES_EDE3_CBC:
return { name: 'DES-EDE3-CBC', length: 192 };
case OID_DES_CBC:
return { name: 'DES-CBC', length: 64 };
case OID_RC2_CBC:
return { name: 'RC2-CBC', length: 128 };
default:
return super.getAlgorithmByOID(oid, safety, target);
}
}
getOIDByAlgorithm(algorithm: { name: string; length?: number }, safety?: boolean, target?: string): string {
switch (algorithm.name.toUpperCase()) {
case 'DES-EDE3-CBC':
return OID_DES_EDE3_CBC;
case 'DES-CBC':
return OID_DES_CBC;
case 'RC2-CBC':
return OID_RC2_CBC;
default:
return super.getOIDByAlgorithm(algorithm, safety, target);
}
}
async decryptEncryptedContentInfo(
parameters: Parameters<pkijs.CryptoEngine['decryptEncryptedContentInfo']>[0],
): Promise<ArrayBuffer> {
@@ -182,9 +221,11 @@ class Pkcs12CryptoEngine extends pkijs.CryptoEngine {
const ivBytes = await pkcs12KDF(bmpPassword, salt, iterations, 2, ivLen);
// Import key via webcrypto-liner (supports DES-EDE3-CBC)
const keyData = new Uint8Array(keyBytes.buffer as ArrayBuffer, keyBytes.byteOffset, keyBytes.byteLength);
const cryptoKey = await this.importKey(
'raw',
new Uint8Array(keyBytes.buffer as ArrayBuffer, keyBytes.byteOffset, keyBytes.byteLength) as unknown as BufferSource,
keyData,
// eslint-disable-next-line no-undef
{ name: algName, length: keyLen * 8 } as Algorithm,
false,
['decrypt'],
@@ -193,6 +234,7 @@ class Pkcs12CryptoEngine extends pkijs.CryptoEngine {
// Decrypt
const ciphertext = parameters.encryptedContentInfo.getEncryptedContent();
return this.decrypt(
// eslint-disable-next-line no-undef
{ name: algName, iv: ivBytes } as Algorithm,
cryptoKey,
ciphertext,
+16 -13
View File
@@ -8,7 +8,7 @@
import * as pkijs from 'pkijs';
import * as asn1js from 'asn1js';
import type { SmimeKeyRecord } from './types';
import { getLinerCryptoEngine } from './crypto-engine';
import { getLinerCryptoEngine, withLinerEngine } from './crypto-engine';
export interface DecryptionInput {
/** Raw CMS EnvelopedData bytes (DER) */
@@ -360,17 +360,20 @@ async function decryptWithKey(
const certAsn1 = asn1js.fromBER(keyRecord.certificate);
const cert = new pkijs.Certificate({ schema: certAsn1.result });
// Use webcrypto-liner engine for legacy algorithm support (e.g. 3DES)
const cryptoEngine = getLinerCryptoEngine();
// Use withLinerEngine to set the global pkijs engine to webcrypto-liner.
// This is required because pkijs internally may use getEngine() for
// OID lookups and crypto operations. Without this, 3DES-encrypted
// messages fail because the default engine doesn't know about DES-EDE3-CBC.
return withLinerEngine(async () => {
const cryptoEngine = getLinerCryptoEngine();
const result = await envelopedData.decrypt(
recipientIndex,
{
recipientCertificate: cert,
recipientPrivateKey: privateKey,
},
cryptoEngine,
);
return result;
return envelopedData.decrypt(
recipientIndex,
{
recipientCertificate: cert,
recipientPrivateKey: privateKey,
},
cryptoEngine,
);
});
}
+126
View File
@@ -0,0 +1,126 @@
/**
* Utilities for handling drag-and-drop of files and folders.
* Uses the File and Directory Entries API (webkitGetAsEntry) to
* recursively read dropped directory trees, preserving relative paths.
*/
interface FileWithPath extends File {
readonly webkitRelativePath: string;
}
/**
* Read all File entries from a FileSystemDirectoryEntry recursively.
* Each returned File has its webkitRelativePath set to the relative path
* within the dropped folder (e.g. "folder/sub/file.txt").
*/
function readDirectoryEntries(dirEntry: FileSystemDirectoryEntry): Promise<FileWithPath[]> {
return new Promise((resolve, reject) => {
const reader = dirEntry.createReader();
const allEntries: FileSystemEntry[] = [];
// readEntries may return results in batches; keep reading until empty
const readBatch = () => {
reader.readEntries(
(entries) => {
if (entries.length === 0) {
resolveFiles(allEntries).then(resolve, reject);
} else {
allEntries.push(...entries);
readBatch();
}
},
reject,
);
};
readBatch();
});
}
function resolveFiles(entries: FileSystemEntry[]): Promise<FileWithPath[]> {
const promises = entries.map((entry) => {
if (entry.isFile) {
return new Promise<FileWithPath[]>((resolve, reject) => {
(entry as FileSystemFileEntry).file(
(file) => {
// Set webkitRelativePath directly on the original File object.
// The property lives on File.prototype as a getter, so defining
// an own data property on the instance safely shadows it.
try {
Object.defineProperty(file, 'webkitRelativePath', {
value: entry.fullPath.replace(/^\//, ''),
writable: false,
configurable: true,
});
} catch {
// Fallback: some environments may prevent overriding.
// The store also falls back to file.name, which still works
// for flat files (though nested paths would be lost).
}
resolve([file as unknown as FileWithPath]);
},
reject,
);
});
} else if (entry.isDirectory) {
return readDirectoryEntries(entry as FileSystemDirectoryEntry);
}
return Promise.resolve([]);
});
return Promise.all(promises).then((arrays) => arrays.flat());
}
/**
* Result of processing a drop event's DataTransfer.
*/
export interface DropResult {
files: File[];
hasDirectories: boolean;
}
/**
* Process a drop event's DataTransfer, detecting folders and recursively
* reading their contents. Returns the list of files and whether any
* directories were found.
*
* Falls back to e.dataTransfer.files when webkitGetAsEntry is unavailable.
*/
export async function getDroppedFilesAndFolders(dataTransfer: DataTransfer): Promise<DropResult> {
const items = dataTransfer.items;
// Check if the browser supports webkitGetAsEntry
if (items && items.length > 0 && typeof items[0].webkitGetAsEntry === 'function') {
const entries: FileSystemEntry[] = [];
for (let i = 0; i < items.length; i++) {
const entry = items[i].webkitGetAsEntry();
if (entry) entries.push(entry);
}
let hasDirectories = false;
const filePromises: Promise<FileWithPath[]>[] = [];
for (const entry of entries) {
if (entry.isDirectory) {
hasDirectories = true;
filePromises.push(readDirectoryEntries(entry as FileSystemDirectoryEntry));
} else if (entry.isFile) {
filePromises.push(
new Promise<FileWithPath[]>((resolve, reject) => {
(entry as FileSystemFileEntry).file(
(file) => resolve([file as FileWithPath]),
reject,
);
}),
);
}
}
const allFiles = (await Promise.all(filePromises)).flat();
return { files: allFiles, hasDirectories };
}
// Fallback: no entry API support
return {
files: Array.from(dataTransfer.files),
hasDirectories: false,
};
}
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "Alle",
"no_icons_found": "Keine Symbole gefunden",
"inline_badge": "Eingebettet",
"tab_badge": "Tab"
"tab_badge": "Tab",
"show_on_mobile": "Auf Mobilgerät anzeigen"
},
"email_list": {
"no_emails": "Keine Nachrichten gefunden",
@@ -691,7 +692,9 @@
"delete": "Schlüsselwort löschen",
"save": "Speichern",
"add": "Hinzufügen",
"cancel": "Abbrechen"
"cancel": "Abbrechen",
"migrating": "Schlüsselwort bei bestehenden E-Mails aktualisieren…",
"migration_error": "Schlüsselwort konnte bei bestehenden E-Mails nicht aktualisiert werden"
},
"language_region": {
"title": "Sprache & Region",
@@ -806,6 +809,17 @@
"close": "Schließen",
"invalid_email": "Bitte geben Sie eine gültige E-Mail-Adresse ein",
"already_added": "Dieser Absender ist bereits vertrauenswürdig"
},
"hover_actions": {
"label": "Schnelle Hover-Aktionen",
"description": "Wählen Sie, welche Schnellaktionen beim Überfahren einer E-Mail in der Liste angezeigt werden",
"delete": "Löschen",
"star": "Markieren / Markierung aufheben",
"mark_read": "Als gelesen / ungelesen markieren",
"archive": "Archivieren",
"tag": "Schlagwort",
"spam": "Als Spam markieren",
"none_selected": "Keine Aktionen ausgewählt"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "Dieses Skript wurde außerhalb des visuellen Builders bearbeitet. Nur die Sieve-Skriptbearbeitung ist verfügbar.",
"open_sieve_editor": "Sieve-Skript-Editor öffnen",
"fetch_error": "Filter konnten nicht geladen werden",
"expanded_view": "Erweiterte Ansicht",
"expanded_view_description": "Filterregeln mit detaillierten Bedingungs- und Aktionsblöcken anzeigen",
"if": "Wenn",
"then": "Dann",
"match_all_conditions": "alle zutreffen",
"match_any_condition": "eine zutrifft",
"and": "und",
"or": "oder",
"cancel": "Abbrechen",
@@ -1842,7 +1862,11 @@
"notification_sound": "Benachrichtigungston",
"notification_sound_desc": "Ton für Kalenderbenachrichtigungen abspielen",
"invitation_parsing": "E-Mail-Einladungen verarbeiten",
"invitation_parsing_desc": "Kalendereinladungen in E-Mail-Anhängen erkennen und Kalenderaktionen anzeigen"
"invitation_parsing_desc": "Kalendereinladungen in E-Mail-Anhängen erkennen und Kalenderaktionen anzeigen",
"show_time_in_month_view": "Zeit in Monatsansicht anzeigen",
"show_time_in_month_view_desc": "Ereigniszeiten in der Monatskalenderansicht anzeigen",
"show_week_numbers": "Kalenderwochen anzeigen",
"show_week_numbers_desc": "Kalenderwochen im Minikalender anzeigen"
},
"days": {
"monday": "Montag",
@@ -2053,7 +2077,7 @@
"file": "Datei",
"parent_directory": "Übergeordnetes Verzeichnis",
"breadcrumb_root": "Startseite",
"drop_files_here": "Dateien hier ablegen zum Hochladen",
"drop_files_here": "Dateien oder Ordner hier ablegen zum Hochladen",
"uploading": "Wird hochgeladen...",
"upload_success": "{count, plural, one {1 Datei hochgeladen} other {# Dateien hochgeladen}}",
"upload_error": "Datei konnte nicht hochgeladen werden",
@@ -2238,8 +2262,14 @@
"settings_desc": "Passen Sie alles an: Design, Dichte, Signaturen, Filter, Tastaturkürzel, Kalender-Standards und mehr.",
"shortcuts_title": "Tastaturkürzel",
"shortcuts_desc": "Für Power-User. Drücken Sie jederzeit ?, um alle verfügbaren Kürzel anzuzeigen.",
"compose_open_title": "Der Editor",
"compose_open_desc": "Dies ist der E-Mail-Editor. Fügen Sie Empfänger hinzu, schreiben Sie Ihre Nachricht, hängen Sie Dateien an und verwenden Sie Rich-Text-Formatierung. Sie können auch Entwürfe speichern und Vorlagen verwenden.",
"calendar_view_title": "Ihr Kalender",
"calendar_view_desc": "Hier ist Ihr Kalender mit Beispielterminen. Wechseln Sie zwischen Tag-, Wochen-, Monats- und Agendaansicht.",
"create_event_title": "Ereignis erstellen",
"create_event_desc": "Klicken Sie auf diese Schaltfläche, um ein neues Kalenderereignis zu erstellen. Sie können Titel, Datum, Uhrzeit und Teilnehmer festlegen.",
"event_modal_title": "Ereignisdetails",
"event_modal_desc": "Hier ist das Ereignisformular. Geben Sie den Titel ein, wählen Sie Datum und Uhrzeit, fügen Sie einen Ort oder Teilnehmer hinzu. Klicken Sie auf Speichern, wenn Sie fertig sind — oder schließen Sie es und fahren Sie fort.",
"contacts_list_title": "Ihre Kontakte",
"contacts_list_desc": "Hier sind Ihre Kontakte. Klicken Sie auf einen Kontakt, um Details zu sehen. Sie können neue Kontakte erstellen oder vCards importieren.",
"files_title": "Dateispeicher",
+62 -6
View File
@@ -146,7 +146,8 @@
"show_all": "All",
"no_icons_found": "No icons found",
"inline_badge": "Inline",
"tab_badge": "Tab"
"tab_badge": "Tab",
"show_on_mobile": "Show on Mobile"
},
"email_list": {
"no_emails": "No messages found",
@@ -1182,6 +1183,12 @@
"opaque_warning": "This script was edited outside the visual builder. Only raw Sieve editing is available.",
"open_sieve_editor": "Open raw Sieve editor",
"fetch_error": "Failed to load filters",
"expanded_view": "Expanded view",
"expanded_view_description": "Show filter rules with detailed condition and action blocks",
"if": "If",
"then": "Then",
"match_all_conditions": "all match",
"match_any_condition": "any matches",
"and": "and",
"or": "or",
"cancel": "Cancel",
@@ -1746,7 +1753,9 @@
"month_hint": "Month (m)",
"week_hint": "Week (w)",
"day_hint": "Day (d)",
"agenda_hint": "Agenda (a)"
"agenda_hint": "Agenda (a)",
"tasks": "Tasks",
"tasks_hint": "Tasks (k)"
},
"events": {
"create": "Create event",
@@ -1855,7 +1864,15 @@
"notification_sound": "Notification sound",
"notification_sound_desc": "Play a sound for calendar alerts",
"invitation_parsing": "Parse email invitations",
"invitation_parsing_desc": "Detect calendar invitations in email attachments and show calendar actions"
"invitation_parsing_desc": "Detect calendar invitations in email attachments and show calendar actions",
"show_time_in_month_view": "Show time in month view",
"show_time_in_month_view_desc": "Display event times in the month calendar view",
"show_week_numbers": "Show week numbers",
"show_week_numbers_desc": "Display week numbers in the mini-calendar",
"enable_tasks": "Enable tasks",
"enable_tasks_desc": "Show a tasks view in the calendar for managing to-dos",
"show_tasks_on_calendar": "Show tasks on calendar",
"show_tasks_on_calendar_desc": "Display task chips on the day and week calendar views"
},
"days": {
"monday": "Monday",
@@ -1888,7 +1905,8 @@
"rsvp_updated": "Response updated",
"rsvp_error": "Failed to update response",
"event_duplicated": "Event duplicated",
"event_error": "Failed to save event"
"event_error": "Failed to save event",
"task_due": "Task due"
},
"status": {
"loading_calendars": "Loading calendars...",
@@ -1986,10 +2004,48 @@
"last_refreshed": "Last updated: {time}"
},
"tasks": {
"label": "Tasks",
"no_tasks": "No tasks",
"no_title": "(No title)",
"mark_complete": "Mark as complete",
"mark_incomplete": "Mark as incomplete"
"mark_incomplete": "Mark as incomplete",
"filter_all": "All",
"filter_pending": "Pending",
"filter_completed": "Completed",
"filter_overdue": "Overdue",
"show_completed": "Show completed",
"create": "New Task",
"edit": "Edit Task",
"title_placeholder": "Task title",
"description_placeholder": "Add a description...",
"due_date": "Due date",
"include_time": "Include time",
"priority": "Priority",
"priority_none": "None",
"priority_high": "High",
"priority_medium": "Medium",
"priority_low": "Low",
"progress": "Status",
"progress_needs_action": "Needs action",
"progress_in_process": "In process",
"progress_completed": "Completed",
"progress_cancelled": "Cancelled",
"calendar": "Calendar",
"alert": "Reminder",
"alert_none": "None",
"alert_at_time": "At time of due date",
"alert_5min": "5 minutes before",
"alert_15min": "15 minutes before",
"alert_30min": "30 minutes before",
"alert_1hr": "1 hour before",
"alert_1day": "1 day before",
"delete": "Delete",
"cancel": "Cancel",
"save": "Save",
"quick_add_placeholder": "Add a task...",
"due_today": "Today",
"due_tomorrow": "Tomorrow",
"overdue": "Overdue"
}
},
"advanced_search": {
@@ -2066,7 +2122,7 @@
"file": "File",
"parent_directory": "Parent directory",
"breadcrumb_root": "Home",
"drop_files_here": "Drop files here to upload",
"drop_files_here": "Drop files or folders here to upload",
"uploading": "Uploading...",
"upload_success": "{count, plural, one {1 file uploaded} other {# files uploaded}}",
"upload_error": "Failed to upload file",
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "Todos",
"no_icons_found": "No se encontraron iconos",
"inline_badge": "Integrado",
"tab_badge": "Pestaña"
"tab_badge": "Pestaña",
"show_on_mobile": "Mostrar en móvil"
},
"email_list": {
"no_emails": "No se encontraron mensajes",
@@ -691,7 +692,9 @@
"delete": "Eliminar palabra clave",
"save": "Guardar",
"add": "Añadir",
"cancel": "Cancelar"
"cancel": "Cancelar",
"migrating": "Actualizando etiqueta en correos existentes…",
"migration_error": "Error al actualizar la etiqueta en correos existentes"
},
"language_region": {
"title": "Idioma y Región",
@@ -806,6 +809,17 @@
"close": "Cerrar",
"invalid_email": "Por favor ingrese una dirección de correo válida",
"already_added": "Este remitente ya es de confianza"
},
"hover_actions": {
"label": "Acciones rápidas al pasar el ratón",
"description": "Elige qué acciones rápidas aparecen al pasar el ratón sobre un correo en la lista",
"delete": "Eliminar",
"star": "Marcar / Desmarcar estrella",
"mark_read": "Marcar como leído / no leído",
"archive": "Archivar",
"tag": "Etiqueta",
"spam": "Marcar como spam",
"none_selected": "No hay acciones seleccionadas"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "Este script fue editado fuera del constructor visual. Solo está disponible la edición Sieve sin formato.",
"open_sieve_editor": "Abrir editor Sieve",
"fetch_error": "Error al cargar los filtros",
"expanded_view": "Vista expandida",
"expanded_view_description": "Mostrar reglas de filtro con bloques detallados de condiciones y acciones",
"if": "Si",
"then": "Entonces",
"match_all_conditions": "todas coinciden",
"match_any_condition": "alguna coincide",
"and": "y",
"or": "o",
"cancel": "Cancelar",
@@ -1842,7 +1862,11 @@
"notification_sound": "Sonido de notificación",
"notification_sound_desc": "Reproducir un sonido para las alertas del calendario",
"invitation_parsing": "Analizar invitaciones por correo",
"invitation_parsing_desc": "Detectar invitaciones de calendario en archivos adjuntos del correo y mostrar acciones del calendario"
"invitation_parsing_desc": "Detectar invitaciones de calendario en archivos adjuntos del correo y mostrar acciones del calendario",
"show_time_in_month_view": "Mostrar hora en vista mensual",
"show_time_in_month_view_desc": "Mostrar las horas de los eventos en la vista mensual del calendario",
"show_week_numbers": "Mostrar números de semana",
"show_week_numbers_desc": "Mostrar los números de semana en el minicalendario"
},
"days": {
"monday": "Lunes",
@@ -2053,7 +2077,7 @@
"file": "Archivo",
"parent_directory": "Directorio superior",
"breadcrumb_root": "Inicio",
"drop_files_here": "Suelte los archivos aquí para subirlos",
"drop_files_here": "Suelte archivos o carpetas aquí para subirlos",
"uploading": "Subiendo...",
"upload_success": "{count, plural, one {1 archivo subido} other {# archivos subidos}}",
"upload_error": "Error al subir el archivo",
@@ -2238,8 +2262,14 @@
"settings_desc": "Personaliza todo: tema, densidad, firmas, filtros, atajos de teclado, valores predeterminados del calendario y más.",
"shortcuts_title": "Atajos de teclado",
"shortcuts_desc": "Para usuarios avanzados. Pulsa ? en cualquier momento para ver todos los atajos disponibles.",
"compose_open_title": "El compositor",
"compose_open_desc": "Este es el compositor de correo. Añade destinatarios, escribe tu mensaje, adjunta archivos y usa formato de texto enriquecido. También puedes guardar borradores y usar plantillas.",
"calendar_view_title": "Tu calendario",
"calendar_view_desc": "Aquí está tu calendario con eventos de ejemplo. Cambia entre vistas de día, semana, mes y agenda.",
"create_event_title": "Crear un evento",
"create_event_desc": "Haz clic en este botón para crear un nuevo evento de calendario. Puedes establecer un título, fecha, hora y añadir participantes.",
"event_modal_title": "Detalles del evento",
"event_modal_desc": "Aquí está el formulario del evento. Rellena el título, elige una fecha y hora, añade una ubicación o participantes. Pulsa guardar cuando hayas terminado — o ciérralo y continúa.",
"contacts_list_title": "Tus contactos",
"contacts_list_desc": "Aquí están tus contactos. Haz clic en cualquier contacto para ver sus detalles. Puedes crear contactos nuevos o importar vCards.",
"files_title": "Almacenamiento de archivos",
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "Toutes",
"no_icons_found": "Aucune icône trouvée",
"inline_badge": "Intégré",
"tab_badge": "Onglet"
"tab_badge": "Onglet",
"show_on_mobile": "Afficher sur mobile"
},
"email_list": {
"no_emails": "Aucun message trouvé",
@@ -691,7 +692,9 @@
"delete": "Supprimer le mot-clé",
"save": "Enregistrer",
"add": "Ajouter",
"cancel": "Annuler"
"cancel": "Annuler",
"migrating": "Mise à jour du mot-clé sur les e-mails existants…",
"migration_error": "Échec de la mise à jour du mot-clé sur les e-mails existants"
},
"language_region": {
"title": "Langue et région",
@@ -806,6 +809,17 @@
"close": "Fermer",
"invalid_email": "Veuillez entrer une adresse email valide",
"already_added": "Cet expéditeur est déjà de confiance"
},
"hover_actions": {
"label": "Actions rapides au survol",
"description": "Choisissez les actions rapides qui apparaissent au survol d'un e-mail dans la liste",
"delete": "Supprimer",
"star": "Étoile / Retirer l'étoile",
"mark_read": "Marquer lu / non lu",
"archive": "Archiver",
"tag": "Étiquette",
"spam": "Marquer comme spam",
"none_selected": "Aucune action sélectionnée"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "Ce script a été modifié en dehors du constructeur visuel. Seule l'édition Sieve brute est disponible.",
"open_sieve_editor": "Ouvrir l'éditeur Sieve brut",
"fetch_error": "Échec du chargement des filtres",
"expanded_view": "Vue étendue",
"expanded_view_description": "Afficher les règles de filtre avec des blocs de conditions et d'actions détaillés",
"if": "Si",
"then": "Alors",
"match_all_conditions": "toutes correspondent",
"match_any_condition": "une correspond",
"and": "et",
"or": "ou",
"cancel": "Annuler",
@@ -1842,7 +1862,11 @@
"notification_sound": "Son de notification",
"notification_sound_desc": "Jouer un son pour les alertes de calendrier",
"invitation_parsing": "Analyser les invitations par e-mail",
"invitation_parsing_desc": "Détecter les invitations de calendrier dans les pièces jointes des e-mails et afficher les actions du calendrier"
"invitation_parsing_desc": "Détecter les invitations de calendrier dans les pièces jointes des e-mails et afficher les actions du calendrier",
"show_time_in_month_view": "Afficher l'heure dans la vue mensuelle",
"show_time_in_month_view_desc": "Afficher les heures des événements dans la vue mensuelle du calendrier",
"show_week_numbers": "Afficher les numéros de semaine",
"show_week_numbers_desc": "Afficher les numéros de semaine dans le mini-calendrier"
},
"days": {
"monday": "Lundi",
@@ -2053,7 +2077,7 @@
"file": "Fichier",
"parent_directory": "Répertoire parent",
"breadcrumb_root": "Accueil",
"drop_files_here": "Déposez les fichiers ici pour les téléverser",
"drop_files_here": "Déposez des fichiers ou dossiers ici pour les téléverser",
"uploading": "Téléversement en cours...",
"upload_success": "{count, plural, one {1 fichier téléversé} other {# fichiers téléversés}}",
"upload_error": "Échec du téléversement du fichier",
@@ -2238,8 +2262,14 @@
"settings_desc": "Personnalisez tout : thème, densité, signatures, filtres, raccourcis clavier, paramètres du calendrier et plus encore.",
"shortcuts_title": "Raccourcis clavier",
"shortcuts_desc": "Les utilisateurs avancés adorent ça. Appuyez sur ? à tout moment pour voir tous les raccourcis disponibles. Naviguez, rédigez et gérez vos emails sans toucher à la souris.",
"compose_open_title": "Le compositeur",
"compose_open_desc": "Voici le compositeur d'e-mail. Ajoutez des destinataires, rédigez votre message, joignez des fichiers et utilisez la mise en forme enrichie. Vous pouvez aussi sauvegarder des brouillons et utiliser des modèles.",
"calendar_view_title": "Votre calendrier",
"calendar_view_desc": "Voici votre calendrier avec des événements exemples. Basculez entre les vues jour, semaine, mois et agenda avec la barre d'outils.",
"create_event_title": "Créer un événement",
"create_event_desc": "Cliquez sur ce bouton pour créer un nouvel événement. Vous pouvez définir un titre, une date, une heure et ajouter des participants.",
"event_modal_title": "Détails de l'événement",
"event_modal_desc": "Voici le formulaire de l'événement. Remplissez le titre, choisissez une date et une heure, ajoutez un lieu ou des participants. Cliquez sur enregistrer quand vous avez terminé — ou fermez-le et passez à autre chose.",
"contacts_list_title": "Vos contacts",
"contacts_list_desc": "Voici vos contacts. Cliquez sur un contact pour voir ses détails à droite. Vous pouvez aussi créer de nouveaux contacts, importer des vCards ou organiser les contacts en groupes.",
"files_title": "Stockage de fichiers",
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "Tutte",
"no_icons_found": "Nessuna icona trovata",
"inline_badge": "Integrato",
"tab_badge": "Scheda"
"tab_badge": "Scheda",
"show_on_mobile": "Mostra su mobile"
},
"email_list": {
"no_emails": "Nessun messaggio trovato",
@@ -691,7 +692,9 @@
"delete": "Elimina parola chiave",
"save": "Salva",
"add": "Aggiungi",
"cancel": "Annulla"
"cancel": "Annulla",
"migrating": "Aggiornamento parola chiave sulle email esistenti…",
"migration_error": "Impossibile aggiornare la parola chiave sulle email esistenti"
},
"language_region": {
"title": "Lingua e regione",
@@ -806,6 +809,17 @@
"close": "Chiudi",
"invalid_email": "Inserisci un indirizzo email valido",
"already_added": "Questo mittente è già attendibile"
},
"hover_actions": {
"label": "Azioni rapide al passaggio del mouse",
"description": "Scegli quali azioni rapide appaiono al passaggio del mouse su un'email nella lista",
"delete": "Elimina",
"star": "Segna / Rimuovi stella",
"mark_read": "Segna come letto / non letto",
"archive": "Archivia",
"tag": "Etichetta",
"spam": "Segna come spam",
"none_selected": "Nessuna azione selezionata"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "Questo script è stato modificato al di fuori del costruttore visuale. È disponibile solo la modifica Sieve grezza.",
"open_sieve_editor": "Apri editor Sieve",
"fetch_error": "Impossibile caricare i filtri",
"expanded_view": "Vista espansa",
"expanded_view_description": "Mostra le regole dei filtri con blocchi dettagliati di condizioni e azioni",
"if": "Se",
"then": "Allora",
"match_all_conditions": "tutte corrispondono",
"match_any_condition": "una corrisponde",
"and": "e",
"or": "o",
"cancel": "Annulla",
@@ -1842,7 +1862,11 @@
"notification_sound": "Suono di notifica",
"notification_sound_desc": "Riproduci un suono per gli avvisi del calendario",
"invitation_parsing": "Analizza gli inviti email",
"invitation_parsing_desc": "Rileva gli inviti del calendario negli allegati email e mostra le azioni del calendario"
"invitation_parsing_desc": "Rileva gli inviti del calendario negli allegati email e mostra le azioni del calendario",
"show_time_in_month_view": "Mostra orario nella vista mensile",
"show_time_in_month_view_desc": "Visualizza gli orari degli eventi nella vista mensile del calendario",
"show_week_numbers": "Mostra numeri di settimana",
"show_week_numbers_desc": "Mostra i numeri di settimana nel mini-calendario"
},
"days": {
"monday": "Lunedì",
@@ -2053,7 +2077,7 @@
"file": "File",
"parent_directory": "Directory superiore",
"breadcrumb_root": "Home",
"drop_files_here": "Trascina i file qui per caricarli",
"drop_files_here": "Trascina file o cartelle qui per caricarli",
"uploading": "Caricamento in corso...",
"upload_success": "{count, plural, one {1 file caricato} other {# file caricati}}",
"upload_error": "Caricamento del file non riuscito",
@@ -2238,8 +2262,14 @@
"settings_desc": "Personalizza tutto: tema, densità, firme, filtri, scorciatoie da tastiera, impostazioni del calendario e altro ancora.",
"shortcuts_title": "Scorciatoie da tastiera",
"shortcuts_desc": "Gli utenti esperti adorano questo. Premi ? in qualsiasi momento per vedere tutte le scorciatoie disponibili. Puoi navigare, comporre e gestire le email senza toccare il mouse.",
"compose_open_title": "Il compositore",
"compose_open_desc": "Questo è il compositore di email. Aggiungi destinatari, scrivi il tuo messaggio, allega file e usa la formattazione del testo. Puoi anche salvare bozze e usare modelli.",
"calendar_view_title": "Il tuo calendario",
"calendar_view_desc": "Ecco il tuo calendario con eventi di esempio. Puoi passare tra le viste giorno, settimana, mese e agenda usando la barra degli strumenti.",
"create_event_title": "Crea un evento",
"create_event_desc": "Fai clic su questo pulsante per creare un nuovo evento del calendario. Puoi impostare un titolo, data, ora e aggiungere partecipanti.",
"event_modal_title": "Dettagli evento",
"event_modal_desc": "Ecco il modulo dell'evento. Inserisci il titolo, scegli data e ora, aggiungi un luogo o partecipanti. Premi salva quando hai finito — o chiudilo e vai avanti.",
"contacts_list_title": "I tuoi contatti",
"contacts_list_desc": "Ecco i tuoi contatti. Clicca su un contatto per vedere i suoi dettagli a destra. Puoi anche creare nuovi contatti, importare vCard o organizzare i contatti in gruppi.",
"files_title": "Archiviazione file",
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "すべて",
"no_icons_found": "アイコンが見つかりません",
"inline_badge": "埋め込み",
"tab_badge": "タブ"
"tab_badge": "タブ",
"show_on_mobile": "モバイルで表示"
},
"email_list": {
"no_emails": "メッセージが見つかりません",
@@ -691,7 +692,9 @@
"delete": "キーワードを削除",
"save": "保存",
"add": "追加",
"cancel": "キャンセル"
"cancel": "キャンセル",
"migrating": "既存のメールでキーワードを更新中…",
"migration_error": "既存のメールでのキーワード更新に失敗しました"
},
"language_region": {
"title": "言語と地域",
@@ -806,6 +809,17 @@
"close": "閉じる",
"invalid_email": "有効なメールアドレスを入力してください",
"already_added": "この送信者はすでに信頼されています"
},
"hover_actions": {
"label": "ホバークイックアクション",
"description": "リスト内のメールにカーソルを合わせたときに表示するクイックアクションを選択",
"delete": "削除",
"star": "スター付け / 解除",
"mark_read": "既読 / 未読にする",
"archive": "アーカイブ",
"tag": "タグ",
"spam": "スパムとしてマーク",
"none_selected": "アクションが選択されていません"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "このスクリプトはビジュアルビルダーの外部で編集されました。Sieveスクリプトの直接編集のみ可能です。",
"open_sieve_editor": "Sieveスクリプトエディタを開く",
"fetch_error": "フィルターの読み込みに失敗しました",
"expanded_view": "詳細表示",
"expanded_view_description": "フィルタールールを条件とアクションのブロックで表示",
"if": "条件",
"then": "実行",
"match_all_conditions": "すべて一致",
"match_any_condition": "いずれか一致",
"and": "かつ",
"or": "または",
"cancel": "キャンセル",
@@ -1842,7 +1862,11 @@
"notification_sound": "通知音",
"notification_sound_desc": "カレンダーアラートの音を鳴らす",
"invitation_parsing": "メール招待を解析する",
"invitation_parsing_desc": "メール添付のカレンダー招待を検出してカレンダー操作を表示する"
"invitation_parsing_desc": "メール添付のカレンダー招待を検出してカレンダー操作を表示する",
"show_time_in_month_view": "月表示で時刻を表示",
"show_time_in_month_view_desc": "月カレンダー表示でイベントの時刻を表示する",
"show_week_numbers": "週番号を表示",
"show_week_numbers_desc": "ミニカレンダーに週番号を表示する"
},
"days": {
"monday": "月曜日",
@@ -2053,7 +2077,7 @@
"file": "ファイル",
"parent_directory": "親ディレクトリ",
"breadcrumb_root": "ホーム",
"drop_files_here": "ここにファイルをドロップしてアップロード",
"drop_files_here": "ここにファイルまたはフォルダをドロップしてアップロード",
"uploading": "アップロード中...",
"upload_success": "{count, plural, other {#件のファイルをアップロードしました}}",
"upload_error": "ファイルのアップロードに失敗しました",
@@ -2238,8 +2262,14 @@
"settings_desc": "すべてをカスタマイズできます:テーマ、表示密度、署名、フィルター、キーボードショートカット、カレンダー設定など。",
"shortcuts_title": "キーボードショートカット",
"shortcuts_desc": "パワーユーザー向けの機能です。いつでも ? を押すと利用可能なすべてのショートカットが表示されます。マウスを使わずにナビゲーション、作成、メール管理ができます。",
"compose_open_title": "メール作成画面",
"compose_open_desc": "これはメール作成画面です。宛先を追加し、メッセージを書き、ファイルを添付し、リッチテキスト書式を使用できます。下書きの保存やテンプレートの使用も可能です。",
"calendar_view_title": "カレンダー表示",
"calendar_view_desc": "サンプルイベント付きのカレンダーです。ツールバーで日、週、月、アジェンダビューを切り替えられます。",
"create_event_title": "イベントを作成",
"create_event_desc": "このボタンをクリックして新しいカレンダーイベントを作成します。タイトル、日付、時間を設定し、参加者を追加できます。",
"event_modal_title": "イベント詳細",
"event_modal_desc": "イベントフォームです。タイトルを入力し、日時を選択し、場所や参加者を追加してください。完了したら保存をクリック — または閉じて次に進みましょう。",
"contacts_list_title": "連絡先一覧",
"contacts_list_desc": "連絡先の一覧です。連絡先をクリックすると右側に詳細が表示されます。新しい連絡先の作成、vCardのインポート、グループへの整理もできます。",
"files_title": "ファイルストレージ",
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "Alle",
"no_icons_found": "Geen pictogrammen gevonden",
"inline_badge": "Ingesloten",
"tab_badge": "Tabblad"
"tab_badge": "Tabblad",
"show_on_mobile": "Weergeven op mobiel"
},
"email_list": {
"no_emails": "Geen berichten gevonden",
@@ -691,7 +692,9 @@
"delete": "Trefwoord verwijderen",
"save": "Opslaan",
"add": "Toevoegen",
"cancel": "Annuleren"
"cancel": "Annuleren",
"migrating": "Trefwoord bijwerken op bestaande e-mails…",
"migration_error": "Kan trefwoord niet bijwerken op bestaande e-mails"
},
"language_region": {
"title": "Taal & Regio",
@@ -806,6 +809,17 @@
"close": "Sluiten",
"invalid_email": "Voer een geldig e-mailadres in",
"already_added": "Deze afzender wordt al vertrouwd"
},
"hover_actions": {
"label": "Snelle hover-acties",
"description": "Kies welke snelle acties verschijnen wanneer u over een e-mail in de lijst beweegt",
"delete": "Verwijderen",
"star": "Ster aan / uit",
"mark_read": "Markeer gelezen / ongelezen",
"archive": "Archiveren",
"tag": "Label",
"spam": "Markeer als spam",
"none_selected": "Geen acties geselecteerd"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "Dit script is buiten de visuele builder bewerkt. Alleen Sieve-scriptbewerking is beschikbaar.",
"open_sieve_editor": "Sieve-scripteditor openen",
"fetch_error": "Filters konden niet worden geladen",
"expanded_view": "Uitgebreide weergave",
"expanded_view_description": "Filterregels weergeven met gedetailleerde voorwaarde- en actieblokken",
"if": "Als",
"then": "Dan",
"match_all_conditions": "alle overeenkomen",
"match_any_condition": "een overeenkomt",
"and": "en",
"or": "of",
"cancel": "Annuleren",
@@ -1842,7 +1862,11 @@
"notification_sound": "Meldingsgeluid",
"notification_sound_desc": "Geluid afspelen voor agendameldingen",
"invitation_parsing": "E-mailuitnodigingen verwerken",
"invitation_parsing_desc": "Kalenderuitnodigingen in e-mailbijlagen detecteren en kalenderacties tonen"
"invitation_parsing_desc": "Kalenderuitnodigingen in e-mailbijlagen detecteren en kalenderacties tonen",
"show_time_in_month_view": "Tijd weergeven in maandweergave",
"show_time_in_month_view_desc": "Evenementtijden weergeven in de maandkalenderweergave",
"show_week_numbers": "Weeknummers weergeven",
"show_week_numbers_desc": "Weeknummers weergeven in de minikalender"
},
"days": {
"monday": "Maandag",
@@ -2053,7 +2077,7 @@
"file": "Bestand",
"parent_directory": "Bovenliggende map",
"breadcrumb_root": "Start",
"drop_files_here": "Sleep bestanden hierheen om te uploaden",
"drop_files_here": "Sleep bestanden of mappen hierheen om te uploaden",
"uploading": "Uploaden...",
"upload_success": "{count, plural, one {1 bestand geüpload} other {# bestanden geüpload}}",
"upload_error": "Bestand uploaden mislukt",
@@ -2238,8 +2262,14 @@
"settings_desc": "Pas alles aan: thema, dichtheid, handtekeningen, filters, sneltoetsen, agendainstellingen en meer.",
"shortcuts_title": "Sneltoetsen",
"shortcuts_desc": "Ervaren gebruikers zijn hier dol op. Druk op ? om alle beschikbare sneltoetsen te bekijken. Navigeer, schrijf en beheer e-mails zonder de muis aan te raken.",
"compose_open_title": "De e-maileditor",
"compose_open_desc": "Dit is de e-maileditor. Voeg ontvangers toe, schrijf uw bericht, voeg bestanden bij en gebruik rijke tekstopmaak. U kunt ook concepten opslaan en sjablonen gebruiken.",
"calendar_view_title": "Uw agenda",
"calendar_view_desc": "Hier is uw agenda met voorbeeldevenementen. Schakel tussen dag-, week-, maand- en agendaweergave via de werkbalk.",
"create_event_title": "Evenement aanmaken",
"create_event_desc": "Klik op deze knop om een nieuw agenda-evenement aan te maken. U kunt een titel, datum, tijd en deelnemers instellen.",
"event_modal_title": "Evenementdetails",
"event_modal_desc": "Hier is het evenementformulier. Vul de titel in, kies een datum en tijd, voeg een locatie of deelnemers toe. Klik op opslaan als u klaar bent — of sluit het en ga verder.",
"contacts_list_title": "Uw contacten",
"contacts_list_desc": "Hier zijn uw contacten. Klik op een contact om de details rechts te bekijken. U kunt ook nieuwe contacten aanmaken, vCards importeren of contacten in groepen organiseren.",
"files_title": "Bestandsopslag",
+34 -4
View File
@@ -146,7 +146,8 @@
"show_all": "Todos",
"no_icons_found": "Nenhum ícone encontrado",
"inline_badge": "Integrado",
"tab_badge": "Aba"
"tab_badge": "Aba",
"show_on_mobile": "Mostrar no celular"
},
"email_list": {
"no_emails": "Nenhuma mensagem encontrada",
@@ -691,7 +692,9 @@
"delete": "Excluir palavra-chave",
"save": "Salvar",
"add": "Adicionar",
"cancel": "Cancelar"
"cancel": "Cancelar",
"migrating": "Atualizando etiqueta nos e-mails existentes…",
"migration_error": "Falha ao atualizar etiqueta nos e-mails existentes"
},
"language_region": {
"title": "Idioma e Região",
@@ -806,6 +809,17 @@
"close": "Fechar",
"invalid_email": "Por favor, digite um endereço de e-mail válido",
"already_added": "Este remetente já é confiável"
},
"hover_actions": {
"label": "Ações rápidas ao passar o mouse",
"description": "Escolha quais ações rápidas aparecem ao passar o mouse sobre um e-mail na lista",
"delete": "Excluir",
"star": "Favoritar / Desfavoritar",
"mark_read": "Marcar como lido / não lido",
"archive": "Arquivar",
"tag": "Etiqueta",
"spam": "Marcar como spam",
"none_selected": "Nenhuma ação selecionada"
}
},
"composer": {
@@ -1169,6 +1183,12 @@
"opaque_warning": "Este script foi editado fora do construtor visual. Apenas a edição Sieve bruta está disponível.",
"open_sieve_editor": "Abrir editor Sieve",
"fetch_error": "Falha ao carregar filtros",
"expanded_view": "Vista expandida",
"expanded_view_description": "Mostrar regras de filtro com blocos detalhados de condições e ações",
"if": "Se",
"then": "Então",
"match_all_conditions": "todas correspondem",
"match_any_condition": "uma corresponde",
"and": "e",
"or": "ou",
"cancel": "Cancelar",
@@ -1842,7 +1862,11 @@
"notification_sound": "Som de notificação",
"notification_sound_desc": "Reproduzir um som para alertas do calendário",
"invitation_parsing": "Analisar convites por e-mail",
"invitation_parsing_desc": "Detectar convites de calendário em anexos de e-mail e mostrar ações do calendário"
"invitation_parsing_desc": "Detectar convites de calendário em anexos de e-mail e mostrar ações do calendário",
"show_time_in_month_view": "Mostrar horário na visualização mensal",
"show_time_in_month_view_desc": "Exibir horários dos eventos na visualização mensal do calendário",
"show_week_numbers": "Mostrar números da semana",
"show_week_numbers_desc": "Exibir números da semana no minicalendário"
},
"days": {
"monday": "Segunda-feira",
@@ -2053,7 +2077,7 @@
"file": "Ficheiro",
"parent_directory": "Diretório superior",
"breadcrumb_root": "Início",
"drop_files_here": "Largue os ficheiros aqui para carregar",
"drop_files_here": "Largue ficheiros ou pastas aqui para carregar",
"uploading": "A carregar...",
"upload_success": "{count, plural, one {1 ficheiro carregado} other {# ficheiros carregados}}",
"upload_error": "Falha ao carregar o ficheiro",
@@ -2238,8 +2262,14 @@
"settings_desc": "Personalize tudo: tema, densidade, assinaturas, filtros, atalhos de teclado, padrões do calendário e mais.",
"shortcuts_title": "Atalhos de teclado",
"shortcuts_desc": "Usuários avançados adoram isso. Pressione ? a qualquer momento para ver todos os atalhos disponíveis. Navegue, escreva e gerencie e-mails sem tocar no mouse.",
"compose_open_title": "O compositor",
"compose_open_desc": "Este é o compositor de e-mail. Adicione destinatários, escreva sua mensagem, anexe arquivos e use formatação de texto rico. Você também pode salvar rascunhos e usar modelos.",
"calendar_view_title": "Seu calendário",
"calendar_view_desc": "Aqui está seu calendário com eventos de exemplo. Você pode alternar entre as visualizações de dia, semana, mês e agenda usando a barra de ferramentas.",
"create_event_title": "Criar um evento",
"create_event_desc": "Clique neste botão para criar um novo evento no calendário. Você pode definir um título, data, hora e adicionar participantes.",
"event_modal_title": "Detalhes do evento",
"event_modal_desc": "Aqui está o formulário do evento. Preencha o título, escolha uma data e hora, adicione um local ou participantes. Clique em salvar quando terminar — ou feche e siga em frente.",
"contacts_list_title": "Seus contatos",
"contacts_list_desc": "Aqui estão seus contatos. Clique em qualquer contato para ver seus detalhes à direita. Você também pode criar novos contatos, importar vCards ou organizar contatos em grupos.",
"files_title": "Armazenamento de ficheiros",
+875 -7
View File
File diff suppressed because it is too large Load Diff
+11 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bulwark-webmail",
"version": "1.4.6",
"version": "1.4.7",
"description": "Bulwark Webmail — a modern webmail client built for Stalwart Mail Server",
"author": "Bulwark Webmail <bulwark@rbm.systems>",
"license": "AGPL-3.0-only",
@@ -33,6 +33,16 @@
},
"dependencies": {
"@tanstack/react-virtual": "^3.13.18",
"@tiptap/extension-color": "^3.20.4",
"@tiptap/extension-image": "^3.20.4",
"@tiptap/extension-link": "^3.20.4",
"@tiptap/extension-placeholder": "^3.20.4",
"@tiptap/extension-text-align": "^3.20.4",
"@tiptap/extension-text-style": "^3.20.4",
"@tiptap/extension-underline": "^3.20.4",
"@tiptap/pm": "^3.20.4",
"@tiptap/react": "^3.20.4",
"@tiptap/starter-kit": "^3.20.4",
"asn1js": "^3.0.7",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
+10 -2
View File
@@ -14,6 +14,8 @@ export function proxy(request: NextRequest) {
const connectSrc = isDev ? `'self' https: ws: wss:` : `'self' https:`;
const frameAncestors = process.env.ALLOWED_FRAME_ANCESTORS?.trim() || "'none'";
const csp = [
`default-src 'self'`,
`script-src ${scriptSrc}`,
@@ -25,7 +27,7 @@ export function proxy(request: NextRequest) {
`object-src 'none'`,
`base-uri 'self'`,
`form-action 'self'`,
`frame-ancestors 'none'`,
`frame-ancestors ${frameAncestors}`,
].join("; ");
let intlResponse: ReturnType<typeof intlMiddleware> | null = null;
@@ -44,7 +46,13 @@ export function proxy(request: NextRequest) {
response.headers.set("x-middleware-request-x-nonce", nonce);
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("X-Frame-Options", "DENY");
// X-Frame-Options only supports DENY/SAMEORIGIN. When frame-ancestors
// specifies explicit origins, we rely solely on the CSP header.
if (frameAncestors === "'none'") {
response.headers.set("X-Frame-Options", "DENY");
}
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
response.headers.set("X-XSS-Protection", "0");
response.headers.set(
+201 -200
View File
@@ -13,6 +13,7 @@ import { fetchConfig } from '@/hooks/use-config';
import { debug } from '@/lib/debug';
import { generateAccountId } from '@/lib/account-utils';
import { replaceWindowLocation } 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';
@@ -35,9 +36,10 @@ interface AuthState {
login: (serverUrl: string, username: string, password: string, totp?: string, rememberMe?: boolean) => Promise<boolean>;
loginWithOAuth: (serverUrl: string, code: string, codeVerifier: string, redirectUri: string) => Promise<boolean>;
loginWithServerSso: (code: string, state: string) => Promise<boolean>;
loginDemo: () => Promise<boolean>;
refreshAccessToken: () => Promise<string | null>;
logout: () => Promise<void>;
logout: () => void;
logoutAll: () => void;
switchAccount: (accountId: string) => Promise<void>;
checkAuth: () => Promise<void>;
@@ -125,7 +127,7 @@ function saveRedirectAfterLogin(): void {
}
}
function redirectToLogin(): void {
export function redirectToLogin(): void {
if (typeof window === 'undefined') return;
const loginPath = getLocaleLoginPath();
@@ -228,6 +230,39 @@ function clearAllRefreshTimers(): void {
refreshPromises.clear();
}
/**
* Synchronously clears all auth and feature store state.
* Called during full logout (no remaining accounts).
*/
function performFullLogout(set: (state: Partial<AuthState>) => void): void {
useSettingsStore.getState().disableSync();
set({
isAuthenticated: false,
isLoading: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
isDemoMode: false,
});
clearAllStores();
// Remove persisted state AFTER the final set() so the persist middleware
// doesn't re-write stale values.
try { localStorage.removeItem('auth-storage'); } catch { /* noop */ }
try { localStorage.removeItem('account-storage'); } catch { /* noop */ }
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
@@ -501,6 +536,8 @@ export const useAuthStore = create<AuthState>()(
scheduleRefresh(expires_in, get().refreshAccessToken, accountId);
notifyParent('sso:auth-success', { username });
// Sync settings from server (only if enabled)
fetchConfig().then(config => {
if (!config.settingsSyncEnabled) return;
@@ -517,9 +554,118 @@ export const useAuthStore = create<AuthState>()(
return true;
} catch (error) {
debug.error('OAuth login error:', error);
const errorMsg = error instanceof Error ? error.message : 'generic';
notifyParent('sso:auth-failure', { error: errorMsg });
set({
isLoading: false,
error: error instanceof Error ? error.message : 'generic',
error: errorMsg,
isAuthenticated: false,
client: null,
});
return false;
}
},
loginWithServerSso: async (code, state) => {
set({ isLoading: true, error: null });
try {
// Server-side SSO: the server holds the PKCE verifier in an encrypted cookie
const ssoRes = await fetch('/api/auth/sso/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ code, state }),
});
if (!ssoRes.ok) {
const errorData = await ssoRes.json().catch(() => ({ error: 'token_exchange_failed' }));
throw new Error(errorData.error || 'token_exchange_failed');
}
const { access_token, expires_in } = await ssoRes.json();
// We need the server URL from config
const config = await fetchConfig();
const ssoServerUrl = config.jmapServerUrl;
if (!ssoServerUrl) {
throw new Error('Server URL not configured');
}
const accountStore = useAccountStore.getState();
const refreshFn = get().refreshAccessToken;
const client = JMAPClient.withBearer(ssoServerUrl, access_token, '', () => refreshFn());
client.onConnectionChange((connected) => {
set({ connectionLost: !connected });
});
await client.connect();
const username = client.getUsername();
const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), username);
initializeFeatureStores(client);
const accountId = generateAccountId(username, ssoServerUrl);
const prevAccountId = get().activeAccountId;
if (prevAccountId && prevAccountId !== accountId) {
snapshotAccount(prevAccountId);
clearAllStores();
}
clients.set(accountId, client);
accountStore.addAccount({
label: primaryIdentity?.name || username,
serverUrl: ssoServerUrl,
username,
authMode: 'oauth',
rememberMe: true,
displayName: primaryIdentity?.name || username,
email: primaryIdentity?.email || username,
lastLoginAt: Date.now(),
isConnected: true,
hasError: false,
isDefault: accountStore.accounts.length === 0,
});
accountStore.setActiveAccount(accountId);
set({
isAuthenticated: true,
isLoading: false,
serverUrl: ssoServerUrl,
username,
client,
identities,
primaryIdentity,
authMode: 'oauth',
accessToken: access_token,
tokenExpiresAt: Date.now() + expires_in * 1000,
connectionLost: false,
error: null,
activeAccountId: accountId,
});
scheduleRefresh(expires_in, get().refreshAccessToken, accountId);
notifyParent('sso:auth-success', { username });
fetchConfig().then(cfg => {
if (!cfg.settingsSyncEnabled) return;
useSettingsStore.getState().loadFromServer(username, ssoServerUrl).finally(() => {
useSettingsStore.getState().enableSync(username, ssoServerUrl);
});
}).catch(() => {});
return true;
} catch (error) {
debug.error('Server SSO login error:', error);
const errorMsg = error instanceof Error ? error.message : 'generic';
notifyParent('sso:auth-failure', { error: errorMsg });
set({
isLoading: false,
error: errorMsg,
isAuthenticated: false,
client: null,
});
@@ -543,6 +689,7 @@ export const useAuthStore = create<AuthState>()(
const res = await fetch(`/api/auth/token?slot=${slot}`, { method: 'PUT' });
if (!res.ok) {
notifyParent('sso:session-expired');
markSessionExpired();
get().logout();
return null;
@@ -561,6 +708,7 @@ export const useAuthStore = create<AuthState>()(
return access_token;
} catch (error) {
debug.error('Token refresh failed:', error);
notifyParent('sso:session-expired');
markSessionExpired();
get().logout();
return null;
@@ -576,7 +724,7 @@ export const useAuthStore = create<AuthState>()(
return promise;
},
logout: async () => {
logout: () => {
const state = get();
const wasDemoMode = state.isDemoMode;
const wasOAuth = state.authMode === 'oauth';
@@ -585,39 +733,14 @@ export const useAuthStore = create<AuthState>()(
const account = accountId ? accountStore.getAccountById(accountId) : null;
const slot = account?.cookieSlot ?? 0;
// Demo mode: simple cleanup, no network calls
if (wasDemoMode) {
set({ client: null });
state.client?.disconnect();
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
isDemoMode: false,
});
localStorage.removeItem('auth-storage');
clearAllStores();
redirectToLogin();
return;
}
// Stop refresh timers immediately
clearRefreshTimer(accountId ?? undefined);
// Null out the client BEFORE disconnecting so the page doesn't fire
// data-loading effects with the stale disconnected client while
// stores are being cleared.
// Disconnect and null out the client BEFORE clearing stores so the
// page doesn't fire data-loading effects with the stale client.
const oldClient = state.client;
set({ client: null });
state.client?.disconnect();
oldClient?.disconnect();
// Remove client from multi-account map
if (accountId) {
@@ -630,61 +753,17 @@ export const useAuthStore = create<AuthState>()(
// Check if there are remaining accounts to switch to
const remainingAccounts = accountStore.accounts;
const shouldRedirectToLogin = remainingAccounts.length === 0;
if (remainingAccounts.length > 0) {
// Switch to the next account
if (remainingAccounts.length > 0 && !wasDemoMode) {
// Switch to the next account — this is the one path that stays in-app
const nextAccount = remainingAccounts[0];
// Clean current stores, then switch
clearAllStores();
// Restore next account
let nextClient = clients.get(nextAccount.id);
// If the client isn't in memory, try to restore it from the session
if (!nextClient) {
try {
if (nextAccount.authMode === 'oauth') {
const res = await fetch(`/api/auth/token?slot=${nextAccount.cookieSlot}`, { method: 'PUT' });
if (res.ok) {
const { access_token, expires_in } = await res.json();
const refreshFn = get().refreshAccessToken;
nextClient = JMAPClient.withBearer(nextAccount.serverUrl, access_token, nextAccount.username, () => refreshFn());
nextClient.onConnectionChange((connected) => {
if (get().activeAccountId === nextAccount.id) {
set({ connectionLost: !connected });
}
accountStore.updateAccount(nextAccount.id, { isConnected: connected });
});
await nextClient.connect();
clients.set(nextAccount.id, nextClient);
scheduleRefresh(expires_in, get().refreshAccessToken, nextAccount.id);
}
} else if (nextAccount.authMode === 'basic' && nextAccount.rememberMe) {
const res = await fetch(`/api/auth/session?slot=${nextAccount.cookieSlot}`);
if (res.ok) {
const { serverUrl: sUrl, username: uName, password: pwd } = await res.json();
nextClient = new JMAPClient(sUrl, uName, pwd);
nextClient.onConnectionChange((connected) => {
if (get().activeAccountId === nextAccount.id) {
set({ connectionLost: !connected });
}
accountStore.updateAccount(nextAccount.id, { isConnected: connected });
});
await nextClient.connect();
clients.set(nextAccount.id, nextClient);
}
}
} catch (err) {
debug.error(`Failed to restore next account ${nextAccount.id} during logout:`, err);
nextClient = undefined;
}
}
const nextClient = clients.get(nextAccount.id);
if (nextClient) {
const restored = restoreAccount(nextAccount.id);
accountStore.setActiveAccount(nextAccount.id);
// Build identity state up front so the name updates atomically
const restoredIdentities = restored ? useIdentityStore.getState().identities : [];
const restoredPrimary = restoredIdentities[0] ?? null;
@@ -711,132 +790,49 @@ export const useAuthStore = create<AuthState>()(
}).catch((err) => debug.error('Failed to load identities after switch:', err));
}
} else {
// Could not restore the next account — remove it and do a full logout
// Client not in memory — clear everything and redirect.
// Trying to async-restore during logout caused the original bug.
debug.error(`Cannot restore next account ${nextAccount.id}, performing full logout`);
evictAccount(nextAccount.id);
accountStore.removeAccount(nextAccount.id);
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
});
localStorage.removeItem('auth-storage');
clearAllStores();
redirectToLogin();
performFullLogout(set);
}
} else {
// No accounts remaining — full logout
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
});
localStorage.removeItem('auth-storage');
clearAllStores();
// Background cookie cleanup for the removed account
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
}
return;
}
// Clean up cookies for the removed account
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: shouldRedirectToLogin }).catch((err) => {
debug.error('Failed to clear session cookie:', err);
});
// No accounts remaining (or demo mode) — full logout + redirect
performFullLogout(set);
if (wasOAuth && shouldRedirectToLogin) {
let redirectCommitted = false;
const commitLoginRedirect = () => {
if (redirectCommitted) return;
redirectCommitted = true;
redirectToLogin();
};
notifyParent('sso:logout');
window.setTimeout(commitLoginRedirect, 0);
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true })
.then((res) => {
if (!res.ok) throw new Error(`Revocation failed: ${res.status}`);
return res.json();
})
.then((data) => {
if (redirectCommitted) return;
if (data.end_session_url) {
redirectCommitted = true;
const locale = window.location.pathname.split('/')[1] || 'en';
const redirectUri = `${window.location.origin}/${locale}/login`;
const url = new URL(data.end_session_url);
url.searchParams.set('post_logout_redirect_uri', redirectUri);
replaceWindowLocation(url.toString());
return;
}
commitLoginRedirect();
})
.catch((err) => {
debug.error('OAuth logout cleanup failed:', err);
commitLoginRedirect();
});
} else if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: false })
.catch((err) => {
debug.error('OAuth logout cleanup failed:', err);
});
} else if (shouldRedirectToLogin) {
redirectToLogin();
// Background cookie/token cleanup — keepalive ensures completion during navigation
if (!wasDemoMode) {
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
}
}
// Redirect to login — this is synchronous and happens AFTER all state is cleared
redirectToLogin();
},
logoutAll: () => {
// Disconnect all clients
for (const client of clients.values()) {
client.disconnect();
for (const c of clients.values()) {
c.disconnect();
}
clients.clear();
clearAllRefreshTimers();
evictAll();
useSettingsStore.getState().disableSync();
useAccountStore.getState().accounts.forEach(() => {});
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
});
localStorage.removeItem('auth-storage');
clearAllStores();
performFullLogout(set);
// Clear all accounts from registry
const accountStore = useAccountStore.getState();
@@ -845,9 +841,10 @@ export const useAuthStore = create<AuthState>()(
accountStore.removeAccount(account.id);
}
// Delete all cookies
// 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(() => {});
redirectToLogin();
},
@@ -1302,16 +1299,20 @@ export const useAuthStore = create<AuthState>()(
}),
{
name: 'auth-storage',
partialize: (state) => ({
serverUrl: state.serverUrl,
username: state.username,
authMode: state.authMode,
isAuthenticated: (state.authMode === 'oauth' || state.rememberMe)
? state.isAuthenticated
: undefined,
rememberMe: state.rememberMe,
activeAccountId: state.activeAccountId,
}),
partialize: (state) => {
// Don't persist unauthenticated state — prevents resurrecting stale sessions
if (!state.isAuthenticated) return {};
return {
serverUrl: state.serverUrl,
username: state.username,
authMode: state.authMode,
isAuthenticated: (state.authMode === 'oauth' || state.rememberMe)
? state.isAuthenticated
: undefined,
rememberMe: state.rememberMe,
activeAccountId: state.activeAccountId,
};
},
}
)
);
+129 -10
View File
@@ -5,9 +5,9 @@ import type { Calendar, CalendarEvent, CalendarParticipant } from '@/lib/jmap/ty
import { debug } from '@/lib/debug';
import { normalizeAllDayDuration } from '@/lib/calendar-utils';
export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda';
export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda' | 'tasks';
const CALENDAR_VIEW_MODES: CalendarViewMode[] = ['month', 'week', 'day', 'agenda'];
const CALENDAR_VIEW_MODES: CalendarViewMode[] = ['month', 'week', 'day', 'agenda', 'tasks'];
export function isCalendarViewMode(value: unknown): value is CalendarViewMode {
return typeof value === 'string' && CALENDAR_VIEW_MODES.includes(value as CalendarViewMode);
@@ -169,7 +169,46 @@ export const useCalendarStore = create<CalendarStore>()(
}
cleanUpdates.calendarIds = remapped;
}
await client.updateCalendarEvent(realId, cleanUpdates, sendSchedulingMessages, targetAccountId);
try {
await client.updateCalendarEvent(realId, cleanUpdates, sendSchedulingMessages, targetAccountId);
} catch (updateError) {
// Stalwart rejects updates to "synthetic" JMAP IDs (CalDAV-created events
// or expanded recurring-event instances returned by expandRecurrences).
// Resolve the real event via a UID query and retry.
const message = updateError instanceof Error ? updateError.message : '';
if (message.toLowerCase().includes('synthetic') && storeEvent) {
debug.log('Event has synthetic ID, resolving real ID via UID query');
const queryResults = await client.queryCalendarEvents(
{ uid: storeEvent.uid }, undefined, undefined, targetAccountId
);
const realEvent = queryResults.find(e => !e.recurrenceId) || queryResults[0];
if (realEvent) {
const resolvedId = realEvent.originalId || realEvent.id;
if (storeEvent.recurrenceId) {
// Recurring instance: patch the master event's recurrenceOverrides
const patchUpdates: Record<string, unknown> = {};
for (const [key, value] of Object.entries(cleanUpdates as Record<string, unknown>)) {
if (['id', 'uid', '@type', 'calendarIds', 'recurrenceRules', 'recurrenceOverrides', 'excludedRecurrenceRules'].includes(key)) continue;
patchUpdates[`recurrenceOverrides/${storeEvent.recurrenceId}/${key}`] = value;
}
await client.updateCalendarEvent(
resolvedId,
patchUpdates as unknown as Partial<CalendarEvent>,
sendSchedulingMessages,
targetAccountId
);
} else {
// Non-recurring event with synthetic ID: retry with the real ID
await client.updateCalendarEvent(resolvedId, cleanUpdates, sendSchedulingMessages, targetAccountId);
}
set((state) => ({
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
}));
return;
}
}
throw updateError;
}
set((state) => ({
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
}));
@@ -202,12 +241,60 @@ export const useCalendarStore = create<CalendarStore>()(
if (replyTo) {
patch.replyTo = replyTo;
}
await client.updateCalendarEvent(
realId,
patch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
try {
await client.updateCalendarEvent(
realId,
patch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
} catch (updateError) {
// Stalwart rejects updates to synthetic IDs. Resolve real ID via UID query.
const message = updateError instanceof Error ? updateError.message : '';
if (message.toLowerCase().includes('synthetic') && storeEvent) {
debug.log('RSVP: Event has synthetic ID, resolving real ID via UID query');
const queryResults = await client.queryCalendarEvents(
{ uid: storeEvent.uid }, undefined, undefined, targetAccountId
);
const realEvent = queryResults.find(e => !e.recurrenceId) || queryResults[0];
if (realEvent) {
const resolvedId = realEvent.originalId || realEvent.id;
if (storeEvent.recurrenceId) {
// Recurring instance: patch RSVP as recurrence override on master
const overridePatch: Record<string, unknown> = {
[`recurrenceOverrides/${storeEvent.recurrenceId}/${patchKey}`]: status,
};
if (replyTo) {
overridePatch[`recurrenceOverrides/${storeEvent.recurrenceId}/replyTo`] = replyTo;
}
await client.updateCalendarEvent(
resolvedId,
overridePatch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
} else {
// Non-recurring event: retry RSVP with real ID
await client.updateCalendarEvent(
resolvedId,
patch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
}
set((state) => ({
events: state.events.map(e => e.id === eventId ? { ...e, participants: {
...e.participants,
...(e.participants?.[participantId] ? {
[participantId]: { ...e.participants[participantId], participationStatus: status as CalendarParticipant['participationStatus'] },
} : {}),
}} : e),
}));
return;
}
}
throw updateError;
}
set((state) => ({
events: state.events.map(e => {
if (e.id !== eventId || !e.participants?.[participantId]) return e;
@@ -351,7 +438,39 @@ export const useCalendarStore = create<CalendarStore>()(
debug.error('Failed to send cancellation emails:', e);
}
}
await client.deleteCalendarEvent(realId, sendSchedulingMessages, targetAccountId);
try {
await client.deleteCalendarEvent(realId, sendSchedulingMessages, targetAccountId);
} catch (deleteError) {
// Stalwart rejects deletes on synthetic IDs (CalDAV-created events or
// expanded recurring instances). Resolve the real ID via UID query.
const message = deleteError instanceof Error ? deleteError.message : '';
if (message.toLowerCase().includes('synthetic') && storeEvent) {
debug.log('Event has synthetic ID, resolving real ID via UID query for delete');
const queryResults = await client.queryCalendarEvents(
{ uid: storeEvent.uid }, undefined, undefined, targetAccountId
);
const realEvent = queryResults.find(e => !e.recurrenceId) || queryResults[0];
if (realEvent) {
const resolvedId = realEvent.originalId || realEvent.id;
if (storeEvent.recurrenceId) {
// Recurring instance: exclude via recurrenceOverrides on master
await client.updateCalendarEvent(
resolvedId,
{ [`recurrenceOverrides/${storeEvent.recurrenceId}`]: { excluded: true } } as unknown as Partial<CalendarEvent>,
false,
targetAccountId
);
} else {
// Non-recurring event: delete using the real ID
await client.deleteCalendarEvent(resolvedId, sendSchedulingMessages, targetAccountId);
}
} else {
throw deleteError;
}
} else {
throw deleteError;
}
}
set((state) => ({
events: state.events.filter(e => e.id !== id),
selectedEventId: state.selectedEventId === id ? null : state.selectedEventId,
+3 -2
View File
@@ -371,10 +371,11 @@ export const useFileStore = create<FileState>((set, get) => ({
}
// Create directories as flat entries with prefixed names (no parentId nesting)
// Convert "/" separators from webkitRelativePath to PATH_SEP () for server names
const sortedDirs = [...dirs].sort((a, b) => a.split('/').length - b.split('/').length);
for (const dir of sortedDirs) {
if (abortController.signal.aborted) break;
const fullDirName = prefix + dir;
const fullDirName = prefix + dir.replace(/\//g, PATH_SEP);
try {
await client.createFileDirectory(fullDirName, null);
} catch {
@@ -387,7 +388,7 @@ export const useFileStore = create<FileState>((set, get) => ({
if (abortController.signal.aborted) break;
const file = files[i];
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
const fullName = prefix + relativePath;
const fullName = prefix + relativePath.replace(/\//g, PATH_SEP);
set({ uploadProgress: { name: relativePath, loaded: 0, total: file.size, current: i + 1, totalFiles } });
+20
View File
@@ -119,8 +119,16 @@ interface SettingsState {
sessionTimeout: number; // minutes (0 = never)
trustedSenders: string[]; // Email addresses that can load external content
// Filters
expandedFilterView: boolean;
// Calendar
showTimeInMonthView: boolean;
showWeekNumbers: boolean;
// Calendar Tasks
enableCalendarTasks: boolean;
showTasksOnCalendar: boolean;
// Calendar Notifications
calendarNotificationsEnabled: boolean;
@@ -219,8 +227,16 @@ const DEFAULT_SETTINGS = {
sessionTimeout: 0, // Never
trustedSenders: [] as string[],
// Filters
expandedFilterView: false,
// Calendar
showTimeInMonthView: false,
showWeekNumbers: false,
// Calendar Tasks
enableCalendarTasks: false,
showTasksOnCalendar: true,
// Calendar Notifications
calendarNotificationsEnabled: true,
@@ -306,7 +322,11 @@ export const useSettingsStore = create<SettingsState>()(
calendarNotificationsEnabled: state.calendarNotificationsEnabled,
calendarNotificationSound: state.calendarNotificationSound,
calendarInvitationParsingEnabled: state.calendarInvitationParsingEnabled,
enableCalendarTasks: state.enableCalendarTasks,
showTasksOnCalendar: state.showTasksOnCalendar,
expandedFilterView: state.expandedFilterView,
showTimeInMonthView: state.showTimeInMonthView,
showWeekNumbers: state.showWeekNumbers,
toolbarPosition: state.toolbarPosition,
senderFavicons: state.senderFavicons,
folderIcons: state.folderIcons,
+58 -1
View File
@@ -1,5 +1,6 @@
import { create } from 'zustand';
import type { CalendarTask } from '@/lib/jmap/types';
import type { IJMAPClient } from '@/lib/jmap/client-interface';
export type TaskViewFilter = 'all' | 'pending' | 'completed' | 'overdue';
@@ -8,19 +9,75 @@ interface TaskStore {
selectedTaskId: string | null;
filter: TaskViewFilter;
showCompleted: boolean;
isLoading: boolean;
error: string | null;
setTasks: (tasks: CalendarTask[]) => void;
setSelectedTaskId: (id: string | null) => void;
setFilter: (filter: TaskViewFilter) => void;
setShowCompleted: (show: boolean) => void;
fetchTasks: (client: IJMAPClient, calendarIds?: string[]) => Promise<void>;
createTask: (client: IJMAPClient, task: Partial<CalendarTask>) => Promise<CalendarTask>;
updateTask: (client: IJMAPClient, id: string, updates: Partial<CalendarTask>) => Promise<void>;
deleteTask: (client: IJMAPClient, id: string) => Promise<void>;
toggleTaskComplete: (client: IJMAPClient, task: CalendarTask) => Promise<void>;
clearTasks: () => void;
}
export const useTaskStore = create<TaskStore>((set) => ({
export const useTaskStore = create<TaskStore>((set, get) => ({
tasks: [],
selectedTaskId: null,
filter: 'all',
showCompleted: false,
isLoading: false,
error: null,
setTasks: (tasks) => set({ tasks }),
setSelectedTaskId: (id) => set({ selectedTaskId: id }),
setFilter: (filter) => set({ filter }),
setShowCompleted: (show) => set({ showCompleted: show }),
fetchTasks: async (client, calendarIds) => {
set({ isLoading: true, error: null });
try {
const tasks = await client.getCalendarTasks(calendarIds);
set({ tasks, isLoading: false });
} catch (error) {
console.error('Failed to fetch tasks:', error);
set({ isLoading: false, error: 'Failed to fetch tasks' });
}
},
createTask: async (client, task) => {
const created = await client.createCalendarTask(task);
set({ tasks: [...get().tasks, created] });
return created;
},
updateTask: async (client, id, updates) => {
await client.updateCalendarTask(id, updates);
set({
tasks: get().tasks.map(t => t.id === id ? { ...t, ...updates, updated: new Date().toISOString() } : t),
});
},
deleteTask: async (client, id) => {
await client.deleteCalendarTask(id);
set({
tasks: get().tasks.filter(t => t.id !== id),
selectedTaskId: get().selectedTaskId === id ? null : get().selectedTaskId,
});
},
toggleTaskComplete: async (client, task) => {
const newProgress = task.progress === 'completed' ? 'needs-action' : 'completed';
const updates: Partial<CalendarTask> = {
progress: newProgress,
progressUpdated: new Date().toISOString(),
};
await client.updateCalendarTask(task.id, updates);
set({
tasks: get().tasks.map(t => t.id === task.id ? { ...t, ...updates, updated: new Date().toISOString() } : t),
});
},
clearTasks: () => set({ tasks: [], selectedTaskId: null, error: null }),
}));