Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b141240fa3 | ||
|
|
44896dee3e | ||
|
|
a5c5fa6669 | ||
|
|
95af61c4be | ||
|
|
34e495dde3 | ||
|
|
0b721661e9 | ||
|
|
9fa851a674 | ||
|
|
41f91244d9 | ||
|
|
77514bd054 |
@@ -1,5 +1,23 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 1.4.4 (2026-03-19)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Calendar**: Implement CalDAV discovery API with automatic calendar home resolution for multi-account setups
|
||||||
|
- **Calendar**: Enhance calendar management settings with mailbox role reassignment controls
|
||||||
|
- **Email**: Add signature rendering utilities with HTML-to-text conversion and sanitization
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Auth**: Fix account session handling to update existing accounts instead of duplicating entries
|
||||||
|
- **Auth**: Fix logout redirects and unauthenticated home page rendering
|
||||||
|
- **Calendar**: Fix duplicate calendar edits and prevent double-save submissions in event modal
|
||||||
|
- **Calendar**: Remove stale calendar ID references in favor of CalDAV-discovered IDs
|
||||||
|
- **Contacts**: Improve RFC 9553 compliance for contact birthdays and address formatting
|
||||||
|
- **Email**: Fix email signature rendering for identity signatures
|
||||||
|
- **Folders**: Improve mailbox role management by clearing roles from all mailboxes before reassigning
|
||||||
|
|
||||||
## 1.4.3 (2026-03-19)
|
## 1.4.3 (2026-03-19)
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="public/branding/Bulwark_Logo_with_Lettering_White_and_Color.svg" />
|
<source media="(prefers-color-scheme: dark)" srcset="public/branding/Bulwark_Logo_with_Lettering_White_and_Color.svg" />
|
||||||
<source media="(prefers-color-scheme: light)" srcset="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" />
|
<source media="(prefers-color-scheme: light)" srcset="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" />
|
||||||
<img src="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" alt="Bulwark Webmail" width="480" />
|
<img src="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" alt="Bulwark Webmail" width="280" />
|
||||||
</picture>
|
</picture>
|
||||||
|
|
||||||
# Bulwark Webmail
|
# Bulwark Webmail
|
||||||
@@ -25,16 +25,16 @@ Built with Next.js and the JMAP protocol.
|
|||||||
<tr>
|
<tr>
|
||||||
<td width="50%">
|
<td width="50%">
|
||||||
|
|
||||||
<img src="screenshots/inbox.png" width="100%" alt="Inbox - three-pane layout with sidebar, email list, and viewer (dark mode)">
|
<img src="screenshots/inbox.png" width="100%" alt="Inbox — three-pane layout with sidebar, email list, and viewer (dark mode)">
|
||||||
|
|
||||||
**Mail** - Three-pane layout with sidebar, email list, and viewer
|
**Mail** — Three-pane layout with sidebar, email list, and viewer
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
<td width="50%">
|
<td width="50%">
|
||||||
|
|
||||||
<img src="screenshots/calendar.png" width="100%" alt="Calendar">
|
<img src="screenshots/calendar.png" width="100%" alt="Calendar">
|
||||||
|
|
||||||
**Calendar** - Month, week, day, and agenda views with event management
|
**Calendar** — Month, week, day, and agenda views with event management
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -43,14 +43,14 @@ Built with Next.js and the JMAP protocol.
|
|||||||
|
|
||||||
<img src="screenshots/contacts.png" width="100%" alt="Contacts">
|
<img src="screenshots/contacts.png" width="100%" alt="Contacts">
|
||||||
|
|
||||||
**Contacts** - Contact management with groups and vCard support
|
**Contacts** — Contact management with groups and vCard support
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
<td width="50%">
|
<td width="50%">
|
||||||
|
|
||||||
<img src="screenshots/files.png" width="100%" alt="File browser">
|
<img src="screenshots/files.png" width="100%" alt="File browser">
|
||||||
|
|
||||||
**Files** - Cloud file browser with upload, preview, and folder navigation
|
**Files** — Cloud file browser with upload, preview, and folder navigation
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -62,16 +62,16 @@ Built with Next.js and the JMAP protocol.
|
|||||||
<tr>
|
<tr>
|
||||||
<td width="50%">
|
<td width="50%">
|
||||||
|
|
||||||
<img src="screenshots/inbox%20whitemode.png" width="100%" alt="Inbox - light mode">
|
<img src="screenshots/inbox%20whitemode.png" width="100%" alt="Inbox — light mode">
|
||||||
|
|
||||||
**Light mode** - Full theme support with intelligent color transformation
|
**Light mode** — Full theme support with intelligent color transformation
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
<td width="50%">
|
<td width="50%">
|
||||||
|
|
||||||
<img src="screenshots/settings.png" width="100%" alt="Settings">
|
<img src="screenshots/settings.png" width="100%" alt="Settings">
|
||||||
|
|
||||||
**Settings** - Appearance, identities, filters, templates, and more
|
**Settings** — Appearance, identities, filters, templates, and more
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -80,7 +80,7 @@ Built with Next.js and the JMAP protocol.
|
|||||||
|
|
||||||
<img src="screenshots/login.png" width="100%" alt="Login page">
|
<img src="screenshots/login.png" width="100%" alt="Login page">
|
||||||
|
|
||||||
**Login** - Configurable branding with OAuth2/OIDC and 2FA support
|
**Login** — Configurable branding with OAuth2/OIDC and 2FA support
|
||||||
|
|
||||||
</td>
|
</td>
|
||||||
<td width="50%">
|
<td width="50%">
|
||||||
@@ -94,21 +94,21 @@ Built with Next.js and the JMAP protocol.
|
|||||||
### Mail
|
### Mail
|
||||||
|
|
||||||
- **Read, compose, reply, reply-all, forward** with rich HTML rendering
|
- **Read, compose, reply, reply-all, forward** with rich HTML rendering
|
||||||
- **Threading** - Gmail-style inline expansion with thread navigation
|
- **Threading** — Gmail-style inline expansion with thread navigation
|
||||||
- **Draft auto-save** with discard confirmation
|
- **Draft auto-save** with discard confirmation
|
||||||
- **Attachments** - upload, download, and inline preview
|
- **Attachments** — upload, download, and inline preview
|
||||||
- **Search** - full-text with JMAP filter panel, search chips, cross-mailbox queries, wildcard support, and OR conditions
|
- **Search** — full-text with JMAP filter panel, search chips, cross-mailbox queries, wildcard support, and OR conditions
|
||||||
- **Batch operations** - multi-select with checkboxes, archive, delete, move, tag
|
- **Batch operations** — multi-select with checkboxes, archive, delete, move, tag
|
||||||
- **Archive modes** - archive directly or organize archived mail by year or month
|
- **Archive modes** — archive directly or organize archived mail by year or month
|
||||||
- **Print** emails directly from the viewer
|
- **Print** emails directly from the viewer
|
||||||
- **Color tags/labels** and star/unstar
|
- **Color tags/labels** and star/unstar
|
||||||
- **Virtual scrolling** for large mailboxes
|
- **Virtual scrolling** for large mailboxes
|
||||||
- **Quick reply** from the viewer
|
- **Quick reply** from the viewer
|
||||||
- **Sender avatars** - favicon-based with negative caching for performance
|
- **Sender avatars** — favicon-based with negative caching for performance
|
||||||
- **Recipient popover** for quick contact interaction
|
- **Recipient popover** for quick contact interaction
|
||||||
- **Folder management** - create, rename, delete folders with icon picker and subfolder support
|
- **TNEF support** — extract Outlook `winmail.dat` message bodies and attachments automatically
|
||||||
- **Tag counts** - unread and total counts displayed in sidebar
|
- **Folder management** — create, rename, delete folders with icon picker and subfolder support
|
||||||
- **TNEF support** - extract Outlook `winmail.dat` message bodies and attachments automatically
|
- **Tag counts** — unread and total counts displayed in sidebar
|
||||||
|
|
||||||
### Calendar
|
### Calendar
|
||||||
|
|
||||||
@@ -116,8 +116,8 @@ Built with Next.js and the JMAP protocol.
|
|||||||
- **Event hover preview** popover with details
|
- **Event hover preview** popover with details
|
||||||
- **Drag-and-drop rescheduling**, click-drag creation, edge-resize (15-min snap)
|
- **Drag-and-drop rescheduling**, click-drag creation, edge-resize (15-min snap)
|
||||||
- **Recurring events** with edit/delete scope (this / this and following / all)
|
- **Recurring events** with edit/delete scope (this / this and following / all)
|
||||||
- **Participant scheduling** - iTIP invitations, organizer/attendee UI, RSVP
|
- **Participant scheduling** — iTIP invitations, organizer/attendee UI, RSVP
|
||||||
- **Inline calendar invitations** in email viewer - auto-detect `.ics`, RSVP, import
|
- **Inline calendar invitations** in email viewer — auto-detect `.ics`, RSVP, import
|
||||||
- **iCalendar import** with preview and bulk create
|
- **iCalendar import** with preview and bulk create
|
||||||
- **Notifications** with configurable sound and alert persistence
|
- **Notifications** with configurable sound and alert persistence
|
||||||
- **Real-time sync** via JMAP push
|
- **Real-time sync** via JMAP push
|
||||||
@@ -128,15 +128,15 @@ Built with Next.js and the JMAP protocol.
|
|||||||
- **Contact groups** with group expansion and member management
|
- **Contact groups** with group expansion and member management
|
||||||
- **vCard import/export** (RFC 6350) with duplicate detection
|
- **vCard import/export** (RFC 6350) with duplicate detection
|
||||||
- **Autocomplete** in composer (To/Cc/Bcc)
|
- **Autocomplete** in composer (To/Cc/Bcc)
|
||||||
- **Bulk operations** - multi-select, delete, group add, export
|
- **Bulk operations** — multi-select, delete, group add, export
|
||||||
|
|
||||||
### Filters & Automation
|
### Filters & Automation
|
||||||
|
|
||||||
- **Server-side email filters** via JMAP Sieve Scripts (RFC 9661)
|
- **Server-side email filters** via JMAP Sieve Scripts (RFC 9661)
|
||||||
- **Visual rule builder** - conditions (From, To, Subject, Size, Body…) and actions (Move, Forward, Star, Discard…)
|
- **Visual rule builder** — conditions (From, To, Subject, Size, Body…) and actions (Move, Forward, Star, Discard…)
|
||||||
- **Raw Sieve editor** with syntax validation
|
- **Raw Sieve editor** with syntax validation
|
||||||
- **Vacation responder** with date range scheduling and sidebar indicator
|
- **Vacation responder** with date range scheduling and sidebar indicator
|
||||||
- **Email templates** - reusable, categorized, with placeholder auto-fill (`{{recipientName}}`, `{{date}}`, etc.)
|
- **Email templates** — reusable, categorized, with placeholder auto-fill (`{{recipientName}}`, `{{date}}`, etc.)
|
||||||
|
|
||||||
### Files
|
### Files
|
||||||
|
|
||||||
@@ -144,39 +144,39 @@ Built with Next.js and the JMAP protocol.
|
|||||||
- **Upload and download** files with progress tracking and folder upload support
|
- **Upload and download** files with progress tracking and folder upload support
|
||||||
- **Folder navigation** with breadcrumb path and tree sidebar
|
- **Folder navigation** with breadcrumb path and tree sidebar
|
||||||
- **Grid and list views** with sorting by name, size, or date
|
- **Grid and list views** with sorting by name, size, or date
|
||||||
- **Clipboard operations** - cut, copy, paste, duplicate files
|
- **Clipboard operations** — cut, copy, paste, duplicate files
|
||||||
- **File preview** for images, text, audio, video, and more
|
- **File preview** for images, text, audio, video, and more
|
||||||
- **Favorites and recent files** for quick access
|
- **Favorites and recent files** for quick access
|
||||||
- **Bulk operations** - multi-select, delete, move, download
|
- **Bulk operations** — multi-select, delete, move, download
|
||||||
|
|
||||||
### Security & Privacy
|
### Security & Privacy
|
||||||
|
|
||||||
- **External content blocked** by default - trusted senders list for auto-load
|
- **External content blocked** by default — trusted senders list for auto-load
|
||||||
- **HTML sanitization** via DOMPurify with XSS prevention
|
- **HTML sanitization** via DOMPurify with XSS prevention
|
||||||
- **S/MIME** - manage certificates, sign outgoing mail, encrypt to recipients, decrypt messages, and verify signatures
|
- **S/MIME** — manage certificates, sign outgoing mail, encrypt to recipients, decrypt messages, and verify signatures
|
||||||
- **SPF/DKIM/DMARC** status indicators
|
- **SPF/DKIM/DMARC** status indicators
|
||||||
- **OAuth2/OIDC with PKCE** for SSO (Keycloak, Authentik, or built-in), with OAuth-only mode
|
- **OAuth2/OIDC with PKCE** for SSO (Keycloak, Authentik, or built-in), with OAuth-only mode
|
||||||
- **TOTP two-factor authentication**
|
- **TOTP two-factor authentication**
|
||||||
- **Account security panel** - manage passwords and 2FA via Stalwart admin API
|
- **Account security panel** — manage passwords and 2FA via Stalwart admin API
|
||||||
- **"Remember me"** - AES-256-GCM encrypted httpOnly cookie (opt-in)
|
- **"Remember me"** — AES-256-GCM encrypted httpOnly cookie (opt-in)
|
||||||
- **Security headers** - CSP with per-request nonce, X-Frame-Options, Referrer-Policy
|
- **Security headers** — CSP with per-request nonce, X-Frame-Options, Referrer-Policy
|
||||||
- **Newsletter unsubscribe** (RFC 2369)
|
- **Newsletter unsubscribe** (RFC 2369)
|
||||||
|
|
||||||
### Interface
|
### Interface
|
||||||
|
|
||||||
- **Three-pane layout** - sidebar, email list, viewer with resizable columns
|
- **Three-pane layout** — sidebar, email list, viewer with resizable columns
|
||||||
- **Dark and light themes** with intelligent email color transformation
|
- **Dark and light themes** with intelligent email color transformation
|
||||||
- **Responsive** - desktop sidebar + mobile bottom tab bar with tablet support
|
- **Always-light email rendering** option for problematic HTML messages in dark theme
|
||||||
- **Keyboard shortcuts** - full navigation without a mouse
|
- **Responsive** — desktop sidebar + mobile bottom tab bar with tablet support
|
||||||
|
- **Keyboard shortcuts** — full navigation without a mouse
|
||||||
- **Drag-and-drop** email organization between mailboxes and tag assignment
|
- **Drag-and-drop** email organization between mailboxes and tag assignment
|
||||||
- **Right-click context menus**, toast notifications with undo, form validation with shake feedback
|
- **Right-click context menus**, toast notifications with undo, form validation with shake feedback
|
||||||
- **Always-light email rendering** option for problematic HTML messages in dark theme
|
|
||||||
- **Customizable toolbar** position, custom favicon, sidebar/login logos, and login page branding
|
- **Customizable toolbar** position, custom favicon, sidebar/login logos, and login page branding
|
||||||
- **Sidebar apps** - pin custom tools to the navigation rail and open them inline or in a new tab
|
- **Sidebar apps** — pin custom tools to the navigation rail and open them inline or in a new tab
|
||||||
- **Settings sync** - preferences synchronized with the server (encrypted)
|
- **Settings sync** — preferences synchronized with the server (encrypted)
|
||||||
- **Storage quota** display
|
- **Storage quota** display
|
||||||
- **Shared folders** - multi-account access
|
- **Shared folders** — multi-account access
|
||||||
- **Accessibility** - WCAG AA contrast, reduced-motion support, focus trap, screen reader live regions
|
- **Accessibility** — WCAG AA contrast, reduced-motion support, focus trap, screen reader live regions
|
||||||
|
|
||||||
### Internationalization
|
### Internationalization
|
||||||
|
|
||||||
@@ -187,13 +187,13 @@ Automatic browser detection with persistent preference.
|
|||||||
### Identity Management
|
### Identity Management
|
||||||
|
|
||||||
- **Multiple sender identities** with per-identity signatures
|
- **Multiple sender identities** with per-identity signatures
|
||||||
- **Sub-addressing** - `user+tag@domain.com` with contextual tag suggestions
|
- **Identity refresh** — keep the identity manager aligned with server-side changes after edits
|
||||||
- **Identity refresh** - keep the identity manager aligned with server-side changes after edits
|
- **Sub-addressing** — `user+tag@domain.com` with contextual tag suggestions
|
||||||
- **Identity badges** in viewer and email list
|
- **Identity badges** in viewer and email list
|
||||||
|
|
||||||
### Operations
|
### Operations
|
||||||
|
|
||||||
- **Automatic update check** - server logs when a newer release is available
|
- **Automatic update check** — server logs when a newer release is available
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -211,7 +211,7 @@ Or with Docker Compose:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env.local
|
cp .env.example .env.local
|
||||||
# Edit .env.local - set JMAP_SERVER_URL
|
# Edit .env.local — set JMAP_SERVER_URL
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -222,7 +222,7 @@ git clone https://github.com/bulwarkmail/webmail.git
|
|||||||
cd webmail
|
cd webmail
|
||||||
npm install
|
npm install
|
||||||
cp .env.example .env.local
|
cp .env.example .env.local
|
||||||
# Edit .env.local - set JMAP_SERVER_URL
|
# Edit .env.local — set JMAP_SERVER_URL
|
||||||
npm run build && npm start
|
npm run build && npm start
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -246,7 +246,7 @@ JMAP_SERVER_URL=https://mail.example.com
|
|||||||
APP_NAME=My Webmail
|
APP_NAME=My Webmail
|
||||||
```
|
```
|
||||||
|
|
||||||
All variables are **runtime** - Docker deployments can be configured without rebuilding.
|
All variables are **runtime** — Docker deployments can be configured without rebuilding.
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Server Listen Address</summary>
|
<summary>Server Listen Address</summary>
|
||||||
@@ -313,7 +313,7 @@ Credentials encrypted with AES-256-GCM, stored in an httpOnly cookie (30-day exp
|
|||||||
|
|
||||||
## Why Stalwart?
|
## Why Stalwart?
|
||||||
|
|
||||||
[Stalwart](https://github.com/stalwartlabs/mail-server) is a mail server written in Rust with **native JMAP support** - not IMAP/SMTP with JMAP bolted on. It handles JMAP, IMAP, SMTP, and ManageSieve in a single binary. Self-hosted, no third-party dependencies.
|
[Stalwart](https://github.com/stalwartlabs/mail-server) is a mail server written in Rust with **native JMAP support** — not IMAP/SMTP with JMAP bolted on. It handles JMAP, IMAP, SMTP, and ManageSieve in a single binary. Self-hosted, no third-party dependencies.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import { useSidebarApps } from "@/hooks/use-sidebar-apps";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { FilePreviewModal } from "@/components/files/file-preview-modal";
|
import { FilePreviewModal } from "@/components/files/file-preview-modal";
|
||||||
import { isFilePreviewable } from "@/lib/file-preview";
|
import { isFilePreviewable } from "@/lib/file-preview";
|
||||||
|
import { appendPlainTextSignature } from "@/lib/signature-utils";
|
||||||
import { Search, Filter, ChevronDown, X, Paperclip, Star, Mail, MailOpen, RotateCcw, PenSquare, PenLine, CheckSquare, Square } from "lucide-react";
|
import { Search, Filter, ChevronDown, X, Paperclip, Star, Mail, MailOpen, RotateCcw, PenSquare, PenLine, CheckSquare, Square } from "lucide-react";
|
||||||
import { ResizeHandle } from "@/components/layout/resize-handle";
|
import { ResizeHandle } from "@/components/layout/resize-handle";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -862,10 +863,7 @@ export default function Home() {
|
|||||||
const primaryIdentity = identities[0];
|
const primaryIdentity = identities[0];
|
||||||
|
|
||||||
// Append signature from the primary identity
|
// Append signature from the primary identity
|
||||||
let finalBody = body;
|
const finalBody = appendPlainTextSignature(body, primaryIdentity);
|
||||||
if (primaryIdentity?.textSignature) {
|
|
||||||
finalBody = body + '\n\n-- \n' + primaryIdentity.textSignature;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send reply with just the body text
|
// Send reply with just the body text
|
||||||
await sendEmail(
|
await sendEmail(
|
||||||
@@ -1022,6 +1020,10 @@ export default function Home() {
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DragDropProvider>
|
<DragDropProvider>
|
||||||
<div className="flex flex-col h-dvh bg-background overflow-hidden">
|
<div className="flex flex-col h-dvh bg-background overflow-hidden">
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { logger } from '@/lib/logger';
|
||||||
|
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
|
||||||
|
|
||||||
|
interface DiscoveryAccountRequest {
|
||||||
|
key: string;
|
||||||
|
candidates: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DiscoveryResult {
|
||||||
|
url: string | null;
|
||||||
|
resolvedAccount: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPublicUrl(serverUrl: string, path: string): string {
|
||||||
|
return new URL(path, serverUrl).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probeCalendarHome(serverUrl: string, authHeader: string, accountName: string): Promise<string | null> {
|
||||||
|
const targetUrl = buildPublicUrl(serverUrl, `/dav/cal/${encodeURIComponent(accountName)}`);
|
||||||
|
const response = await fetch(targetUrl, {
|
||||||
|
method: 'PROPFIND',
|
||||||
|
headers: {
|
||||||
|
Authorization: authHeader,
|
||||||
|
Depth: '0',
|
||||||
|
'Content-Type': 'application/xml; charset=utf-8',
|
||||||
|
},
|
||||||
|
body: `<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<D:propfind xmlns:D="DAV:">
|
||||||
|
<D:prop>
|
||||||
|
<D:resourcetype/>
|
||||||
|
<D:displayname/>
|
||||||
|
</D:prop>
|
||||||
|
</D:propfind>`,
|
||||||
|
redirect: 'manual',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 207) {
|
||||||
|
return targetUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status >= 300 && response.status < 400) {
|
||||||
|
const location = response.headers.get('Location');
|
||||||
|
if (location) {
|
||||||
|
return new URL(location, targetUrl).toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const creds = await getStalwartCredentials(request);
|
||||||
|
if (!creds) {
|
||||||
|
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json().catch(() => ({}));
|
||||||
|
const accounts = Array.isArray(body.accounts) ? body.accounts as DiscoveryAccountRequest[] : [];
|
||||||
|
const wellKnownUrl = buildPublicUrl(creds.serverUrl, '/.well-known/caldav');
|
||||||
|
const discovered: Record<string, DiscoveryResult> = {};
|
||||||
|
|
||||||
|
for (const account of accounts) {
|
||||||
|
if (!account?.key) continue;
|
||||||
|
|
||||||
|
const candidates = Array.from(new Set(
|
||||||
|
(account.candidates || [])
|
||||||
|
.map((candidate) => candidate?.trim())
|
||||||
|
.filter((candidate): candidate is string => Boolean(candidate))
|
||||||
|
));
|
||||||
|
|
||||||
|
let url: string | null = null;
|
||||||
|
let resolvedAccount: string | null = null;
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
try {
|
||||||
|
url = await probeCalendarHome(creds.serverUrl, creds.authHeader, candidate);
|
||||||
|
if (url) {
|
||||||
|
resolvedAccount = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('CalDAV discovery probe failed', {
|
||||||
|
accountKey: account.key,
|
||||||
|
candidate,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
discovered[account.key] = { url, resolvedAccount };
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
wellKnownUrl,
|
||||||
|
accounts: discovered,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('CalDAV discovery failed', { error: error instanceof Error ? error.message : 'Unknown' });
|
||||||
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import { format, parseISO, isToday, isTomorrow } from "date-fns";
|
|||||||
import { Calendar as CalendarIcon, MapPin, Users } from "lucide-react";
|
import { Calendar as CalendarIcon, MapPin, Users } from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { parseDuration, getEventColor } from "./event-card";
|
import { parseDuration, getEventColor } from "./event-card";
|
||||||
import { getEventDayBounds } from "@/lib/calendar-utils";
|
import { getEventDayBounds, getPrimaryCalendarId } from "@/lib/calendar-utils";
|
||||||
import { getParticipantCount } from "@/lib/calendar-participants";
|
import { getParticipantCount } from "@/lib/calendar-participants";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
|
|
||||||
@@ -113,8 +113,8 @@ export function CalendarAgendaView({
|
|||||||
|
|
||||||
<div className="divide-y divide-border">
|
<div className="divide-y divide-border">
|
||||||
{group.events.map((ev) => {
|
{group.events.map((ev) => {
|
||||||
const calId = Object.keys(ev.calendarIds)[0];
|
const calId = getPrimaryCalendarId(ev);
|
||||||
const calendar = calendarMap.get(calId);
|
const calendar = calId ? calendarMap.get(calId) : undefined;
|
||||||
const color = getEventColor(ev, calendar);
|
const color = getEventColor(ev, calendar);
|
||||||
const start = parseISO(ev.start);
|
const start = parseISO(ev.start);
|
||||||
const durMin = parseDuration(ev.duration);
|
const durMin = parseDuration(ev.duration);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { format, isToday, parseISO } from "date-fns";
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { EventCard, parseDuration } from "./event-card";
|
import { EventCard, parseDuration } from "./event-card";
|
||||||
import { QuickEventInput } from "./quick-event-input";
|
import { QuickEventInput } from "./quick-event-input";
|
||||||
import { getEventDayBounds, layoutOverlappingEvents, formatSnapTime } from "@/lib/calendar-utils";
|
import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
||||||
|
|
||||||
@@ -127,12 +127,12 @@ export function CalendarDayView({
|
|||||||
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
|
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{allDayEvents.map((ev) => {
|
{allDayEvents.map((ev) => {
|
||||||
const calId = Object.keys(ev.calendarIds)[0];
|
const calId = getPrimaryCalendarId(ev);
|
||||||
return (
|
return (
|
||||||
<EventCard
|
<EventCard
|
||||||
key={ev.id}
|
key={ev.id}
|
||||||
event={ev}
|
event={ev}
|
||||||
calendar={calendarMap.get(calId)}
|
calendar={calId ? calendarMap.get(calId) : undefined}
|
||||||
variant="chip"
|
variant="chip"
|
||||||
onClick={(rect) => onSelectEvent(ev, rect)}
|
onClick={(rect) => onSelectEvent(ev, rect)}
|
||||||
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
||||||
@@ -192,7 +192,7 @@ export function CalendarDayView({
|
|||||||
const top = (startMin / 60) * HOUR_HEIGHT;
|
const top = (startMin / 60) * HOUR_HEIGHT;
|
||||||
const baseHeight = Math.max(24, (durMin / 60) * HOUR_HEIGHT);
|
const baseHeight = Math.max(24, (durMin / 60) * HOUR_HEIGHT);
|
||||||
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight;
|
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight;
|
||||||
const calId = Object.keys(ev.calendarIds)[0];
|
const calId = getPrimaryCalendarId(ev);
|
||||||
const leftPct = (column / totalColumns) * 100;
|
const leftPct = (column / totalColumns) * 100;
|
||||||
const widthPct = (1 / totalColumns) * 100;
|
const widthPct = (1 / totalColumns) * 100;
|
||||||
|
|
||||||
@@ -205,7 +205,7 @@ export function CalendarDayView({
|
|||||||
>
|
>
|
||||||
<EventCard
|
<EventCard
|
||||||
event={ev}
|
event={ev}
|
||||||
calendar={calendarMap.get(calId)}
|
calendar={calId ? calendarMap.get(calId) : undefined}
|
||||||
variant="block"
|
variant="block"
|
||||||
onClick={(rect) => onSelectEvent(ev, rect)}
|
onClick={(rect) => onSelectEvent(ev, rect)}
|
||||||
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
} from "date-fns";
|
} from "date-fns";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { EventCard } from "./event-card";
|
import { EventCard } from "./event-card";
|
||||||
import { buildWeekSegments, getEventDayBounds } from "@/lib/calendar-utils";
|
import { buildWeekSegments, getEventDayBounds, getPrimaryCalendarId } from "@/lib/calendar-utils";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
@@ -197,8 +197,8 @@ export function CalendarMonthView({
|
|||||||
dayEvents.length > 0 && (
|
dayEvents.length > 0 && (
|
||||||
<div className="flex items-center justify-center gap-0.5 flex-wrap">
|
<div className="flex items-center justify-center gap-0.5 flex-wrap">
|
||||||
{dayEvents.slice(0, 3).map((ev) => {
|
{dayEvents.slice(0, 3).map((ev) => {
|
||||||
const calId = Object.keys(ev.calendarIds)[0];
|
const calId = getPrimaryCalendarId(ev);
|
||||||
const cal = calendarMap.get(calId);
|
const cal = calId ? calendarMap.get(calId) : undefined;
|
||||||
const evColor = ev.color || cal?.color || "#3b82f6";
|
const evColor = ev.color || cal?.color || "#3b82f6";
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
@@ -222,7 +222,7 @@ export function CalendarMonthView({
|
|||||||
{!isMobile && segments.length > 0 && (
|
{!isMobile && segments.length > 0 && (
|
||||||
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
|
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
|
||||||
{segments.map((segment) => {
|
{segments.map((segment) => {
|
||||||
const calId = Object.keys(segment.event.calendarIds)[0];
|
const calId = getPrimaryCalendarId(segment.event);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
|
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
|
||||||
@@ -236,7 +236,7 @@ export function CalendarMonthView({
|
|||||||
>
|
>
|
||||||
<EventCard
|
<EventCard
|
||||||
event={segment.event}
|
event={segment.event}
|
||||||
calendar={calendarMap.get(calId)}
|
calendar={calId ? calendarMap.get(calId) : undefined}
|
||||||
variant="span"
|
variant="span"
|
||||||
continuesBefore={segment.continuesBefore}
|
continuesBefore={segment.continuesBefore}
|
||||||
continuesAfter={segment.continuesAfter}
|
continuesAfter={segment.continuesAfter}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export function CalendarSidebarPanel({
|
|||||||
const shared = calendars.filter(c => c.isShared);
|
const shared = calendars.filter(c => c.isShared);
|
||||||
const groups = new Map<string, { accountName: string; calendars: Calendar[] }>();
|
const groups = new Map<string, { accountName: string; calendars: Calendar[] }>();
|
||||||
for (const cal of shared) {
|
for (const cal of shared) {
|
||||||
const key = cal.accountId!;
|
const key = cal.accountId || cal.accountName || cal.id;
|
||||||
if (!groups.has(key)) {
|
if (!groups.has(key)) {
|
||||||
groups.set(key, { accountName: cal.accountName || key, calendars: [] });
|
groups.set(key, { accountName: cal.accountName || key, calendars: [] });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ export function CalendarToolbar({
|
|||||||
const shared = calendars.filter(c => c.isShared);
|
const shared = calendars.filter(c => c.isShared);
|
||||||
const groups = new Map<string, { accountName: string; cals: typeof shared }>();
|
const groups = new Map<string, { accountName: string; cals: typeof shared }>();
|
||||||
for (const c of shared) {
|
for (const c of shared) {
|
||||||
const key = c.accountId!;
|
const key = c.accountId || c.accountName || c.id;
|
||||||
if (!groups.has(key)) groups.set(key, { accountName: c.accountName || key, cals: [] });
|
if (!groups.has(key)) groups.set(key, { accountName: c.accountName || key, cals: [] });
|
||||||
groups.get(key)!.cals.push(c);
|
groups.get(key)!.cals.push(c);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { EventCard, parseDuration } from "./event-card";
|
import { EventCard, parseDuration } from "./event-card";
|
||||||
import { QuickEventInput } from "./quick-event-input";
|
import { QuickEventInput } from "./quick-event-input";
|
||||||
import { buildWeekSegments, getEventDayBounds, layoutOverlappingEvents, formatSnapTime } from "@/lib/calendar-utils";
|
import { buildWeekSegments, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
||||||
|
|
||||||
@@ -162,7 +162,7 @@ export function CalendarWeekView({
|
|||||||
|
|
||||||
<div className="absolute inset-0 pointer-events-none">
|
<div className="absolute inset-0 pointer-events-none">
|
||||||
{allDaySegments.map((segment) => {
|
{allDaySegments.map((segment) => {
|
||||||
const calId = Object.keys(segment.event.calendarIds)[0];
|
const calId = getPrimaryCalendarId(segment.event);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
|
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
|
||||||
@@ -176,7 +176,7 @@ export function CalendarWeekView({
|
|||||||
>
|
>
|
||||||
<EventCard
|
<EventCard
|
||||||
event={segment.event}
|
event={segment.event}
|
||||||
calendar={calendarMap.get(calId)}
|
calendar={calId ? calendarMap.get(calId) : undefined}
|
||||||
variant="span"
|
variant="span"
|
||||||
continuesBefore={segment.continuesBefore}
|
continuesBefore={segment.continuesBefore}
|
||||||
continuesAfter={segment.continuesAfter}
|
continuesAfter={segment.continuesAfter}
|
||||||
@@ -284,7 +284,7 @@ export function CalendarWeekView({
|
|||||||
const top = (startMin / 60) * HOUR_HEIGHT;
|
const top = (startMin / 60) * HOUR_HEIGHT;
|
||||||
const baseHeight = Math.max(20, (durMin / 60) * HOUR_HEIGHT);
|
const baseHeight = Math.max(20, (durMin / 60) * HOUR_HEIGHT);
|
||||||
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight;
|
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight;
|
||||||
const calId = Object.keys(ev.calendarIds)[0];
|
const calId = getPrimaryCalendarId(ev);
|
||||||
const leftPct = (column / totalColumns) * 100;
|
const leftPct = (column / totalColumns) * 100;
|
||||||
const widthPct = (1 / totalColumns) * 100;
|
const widthPct = (1 / totalColumns) * 100;
|
||||||
|
|
||||||
@@ -297,7 +297,7 @@ export function CalendarWeekView({
|
|||||||
>
|
>
|
||||||
<EventCard
|
<EventCard
|
||||||
event={ev}
|
event={ev}
|
||||||
calendar={calendarMap.get(calId)}
|
calendar={calId ? calendarMap.get(calId) : undefined}
|
||||||
variant="block"
|
variant="block"
|
||||||
onClick={(rect) => onSelectEvent(ev, rect)}
|
onClick={(rect) => onSelectEvent(ev, rect)}
|
||||||
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { X, Trash2, Check, Users, CalendarDays, Copy, Pencil, Clock, MapPin, Vid
|
|||||||
import { format, parseISO, addHours, addDays } from "date-fns";
|
import { format, parseISO, addHours, addDays } from "date-fns";
|
||||||
import type { CalendarEvent, Calendar, CalendarParticipant } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar, CalendarParticipant } from "@/lib/jmap/types";
|
||||||
import { parseDuration, getEventColor } from "./event-card";
|
import { parseDuration, getEventColor } from "./event-card";
|
||||||
import { buildAllDayDuration, getEventDisplayEndDate } from "@/lib/calendar-utils";
|
import { buildAllDayDuration, getEventDisplayEndDate, getPrimaryCalendarId } from "@/lib/calendar-utils";
|
||||||
import { ParticipantInput } from "./participant-input";
|
import { ParticipantInput } from "./participant-input";
|
||||||
import {
|
import {
|
||||||
isOrganizer,
|
isOrganizer,
|
||||||
@@ -25,7 +25,7 @@ interface EventModalProps {
|
|||||||
calendars: Calendar[];
|
calendars: Calendar[];
|
||||||
defaultDate?: Date;
|
defaultDate?: Date;
|
||||||
defaultEndDate?: Date;
|
defaultEndDate?: Date;
|
||||||
onSave: (data: Partial<CalendarEvent>, sendSchedulingMessages?: boolean) => void;
|
onSave: (data: Partial<CalendarEvent>, sendSchedulingMessages?: boolean) => void | Promise<void>;
|
||||||
onDelete?: (id: string, sendSchedulingMessages?: boolean) => void;
|
onDelete?: (id: string, sendSchedulingMessages?: boolean) => void;
|
||||||
onDuplicate?: (data: Partial<CalendarEvent>) => void;
|
onDuplicate?: (data: Partial<CalendarEvent>) => void;
|
||||||
onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void;
|
onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void;
|
||||||
@@ -184,7 +184,7 @@ export function EventModal({
|
|||||||
const [endTime, setEndTime] = useState(formatTimeInput(getInitialEnd()));
|
const [endTime, setEndTime] = useState(formatTimeInput(getInitialEnd()));
|
||||||
const [allDay, setAllDay] = useState(event?.showWithoutTime || false);
|
const [allDay, setAllDay] = useState(event?.showWithoutTime || false);
|
||||||
const [calendarId, setCalendarId] = useState<string>(() => {
|
const [calendarId, setCalendarId] = useState<string>(() => {
|
||||||
if (event?.calendarIds) return Object.keys(event.calendarIds)[0] || calendars[0]?.id || "";
|
if (event?.calendarIds) return getPrimaryCalendarId(event) || calendars[0]?.id || "";
|
||||||
const defaultCal = calendars.find(c => c.isDefault);
|
const defaultCal = calendars.find(c => c.isDefault);
|
||||||
return defaultCal?.id || calendars[0]?.id || "";
|
return defaultCal?.id || calendars[0]?.id || "";
|
||||||
});
|
});
|
||||||
@@ -209,6 +209,7 @@ export function EventModal({
|
|||||||
return "none";
|
return "none";
|
||||||
});
|
});
|
||||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||||
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
|
||||||
const [attendees, setAttendees] = useState<{ name: string; email: string }[]>(() => {
|
const [attendees, setAttendees] = useState<{ name: string; email: string }[]>(() => {
|
||||||
if (!event?.participants) return [];
|
if (!event?.participants) return [];
|
||||||
@@ -231,9 +232,9 @@ export function EventModal({
|
|||||||
setAttendees(prev => prev.filter(a => a.email.toLowerCase() !== email.toLowerCase()));
|
setAttendees(prev => prev.filter(a => a.email.toLowerCase() !== email.toLowerCase()));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSave = useCallback(() => {
|
const handleSave = useCallback(async () => {
|
||||||
const trimmedTitle = title.trim();
|
const trimmedTitle = title.trim();
|
||||||
if (!trimmedTitle) return;
|
if (!trimmedTitle || isSaving) return;
|
||||||
if (trimmedTitle.length > 500 || description.trim().length > 10000 || location.trim().length > 500) return;
|
if (trimmedTitle.length > 500 || description.trim().length > 10000 || location.trim().length > 500) return;
|
||||||
|
|
||||||
const startStr = allDay
|
const startStr = allDay
|
||||||
@@ -343,8 +344,13 @@ export function EventModal({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const shouldSendScheduling = attendees.length > 0 && sendInvitations;
|
const shouldSendScheduling = attendees.length > 0 && sendInvitations;
|
||||||
onSave(data, shouldSendScheduling);
|
setIsSaving(true);
|
||||||
}, [title, description, location, startDate, startTime, endDate, endTime, allDay, calendarId, recurrence, alert, attendees, sendInvitations, currentUserEmails, existingParticipants, event, onSave]);
|
try {
|
||||||
|
await onSave(data, shouldSendScheduling);
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
|
}, [title, description, location, startDate, startTime, endDate, endTime, allDay, calendarId, recurrence, alert, attendees, sendInvitations, currentUserEmails, existingParticipants, event, onSave, isSaving]);
|
||||||
|
|
||||||
const handleRsvp = useCallback((status: CalendarParticipant['participationStatus']) => {
|
const handleRsvp = useCallback((status: CalendarParticipant['participationStatus']) => {
|
||||||
if (!event || !userParticipantId || !onRsvp) return;
|
if (!event || !userParticipantId || !onRsvp) return;
|
||||||
@@ -945,7 +951,7 @@ export function EventModal({
|
|||||||
<Button variant="outline" onClick={isEdit ? () => setMode("view") : onClose}>
|
<Button variant="outline" onClick={isEdit ? () => setMode("view") : onClose}>
|
||||||
{t("form.cancel")}
|
{t("form.cancel")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={handleSave} disabled={!title.trim()}>
|
<Button onClick={handleSave} disabled={!title.trim() || isSaving}>
|
||||||
{t("form.save")}
|
{t("form.save")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { Mail, Phone, Building, MapPin, StickyNote, Pencil, Trash2, BookUser, Co
|
|||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { ContactCard } from "@/lib/jmap/types";
|
import type { ContactCard, AnniversaryDate, PartialDate } from "@/lib/jmap/types";
|
||||||
import { getContactDisplayName, getContactPrimaryEmail } from "@/stores/contact-store";
|
import { getContactDisplayName, getContactPrimaryEmail } from "@/stores/contact-store";
|
||||||
import { useSmimeStore } from "@/stores/smime-store";
|
import { useSmimeStore } from "@/stores/smime-store";
|
||||||
import { parseCertificatePemOrDer, extractCertificateInfo } from "@/lib/smime/certificate-utils";
|
import { parseCertificatePemOrDer, extractCertificateInfo } from "@/lib/smime/certificate-utils";
|
||||||
@@ -26,12 +26,23 @@ function formatPhoneFeatures(features?: Record<string, boolean>): string {
|
|||||||
return Object.keys(features).filter(k => features[k]).join(", ");
|
return Object.keys(features).filter(k => features[k]).join(", ");
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(dateInput: string | Record<string, unknown>): string {
|
function formatDate(dateInput: AnniversaryDate): string {
|
||||||
// Handle RFC 9553 PartialDate objects: { year?, month?, day?, calendarScale? }
|
// Handle RFC 9553 PartialDate objects: { year?, month?, day?, calendarScale? }
|
||||||
|
// Handle RFC 9553 Timestamp objects: { "@type": "Timestamp", utc: "..." }
|
||||||
if (typeof dateInput === 'object' && dateInput !== null) {
|
if (typeof dateInput === 'object' && dateInput !== null) {
|
||||||
const year = dateInput.year as number | undefined;
|
if (dateInput['@type'] === 'Timestamp' && typeof dateInput.utc === 'string') {
|
||||||
const month = dateInput.month as number | undefined;
|
try {
|
||||||
const day = dateInput.day as number | undefined;
|
const d = new Date(dateInput.utc as string);
|
||||||
|
if (!isNaN(d.getTime())) {
|
||||||
|
return d.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
|
||||||
|
}
|
||||||
|
} catch { /* fallback */ }
|
||||||
|
return String(dateInput.utc);
|
||||||
|
}
|
||||||
|
const pd = dateInput as PartialDate;
|
||||||
|
const year = pd.year;
|
||||||
|
const month = pd.month;
|
||||||
|
const day = pd.day;
|
||||||
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
if (month && monthNames[month - 1]) parts.push(monthNames[month - 1]);
|
if (month && monthNames[month - 1]) parts.push(monthNames[month - 1]);
|
||||||
@@ -282,9 +293,11 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
|
|||||||
{addresses.map((a, i) => (
|
{addresses.map((a, i) => (
|
||||||
<div key={i} className="text-sm space-y-0.5 rounded-md border border-border/60 bg-muted/30 p-3">
|
<div key={i} className="text-sm space-y-0.5 rounded-md border border-border/60 bg-muted/30 p-3">
|
||||||
<div>
|
<div>
|
||||||
{a.fullAddress
|
{a.full || a.fullAddress
|
||||||
? a.fullAddress
|
? (a.full || a.fullAddress)
|
||||||
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
|
: a.components && a.components.length > 0
|
||||||
|
? a.components.filter(c => c.kind !== 'separator').map(c => c.value).filter(Boolean).join(", ")
|
||||||
|
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
|
||||||
{a.contexts && <ContextBadge contexts={a.contexts} />}
|
{a.contexts && <ContextBadge contexts={a.contexts} />}
|
||||||
</div>
|
</div>
|
||||||
{a.timeZone && (
|
{a.timeZone && (
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { ContactCard, ContactOnlineService, ContactAnniversary, ContactPersonalInfo, AddressBook } from "@/lib/jmap/types";
|
import type { ContactCard, ContactOnlineService, ContactAnniversary, ContactPersonalInfo, AddressBook, AnniversaryDate, PartialDate, ContactAddress } from "@/lib/jmap/types";
|
||||||
|
|
||||||
interface EmailEntry {
|
interface EmailEntry {
|
||||||
address: string;
|
address: string;
|
||||||
@@ -129,6 +129,67 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
|
|
||||||
const findComponent = (kind: string) => contact?.name?.components?.find(c => c.kind === kind)?.value || "";
|
const findComponent = (kind: string) => contact?.name?.components?.find(c => c.kind === kind)?.value || "";
|
||||||
|
|
||||||
|
// Convert RFC 9553 AnniversaryDate to ISO date string for HTML date input
|
||||||
|
function anniversaryDateToString(date: AnniversaryDate): string {
|
||||||
|
if (typeof date === 'string') return date;
|
||||||
|
if (date && typeof date === 'object') {
|
||||||
|
if ('@type' in date && date['@type'] === 'Timestamp' && 'utc' in date) {
|
||||||
|
return (date as { utc: string }).utc.split('T')[0];
|
||||||
|
}
|
||||||
|
const pd = date as PartialDate;
|
||||||
|
if (pd.year && pd.month && pd.day) {
|
||||||
|
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
if (pd.month && pd.day) {
|
||||||
|
return `--${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
if (pd.year && pd.month) {
|
||||||
|
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
if (pd.year) return String(pd.year);
|
||||||
|
}
|
||||||
|
return String(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert ISO date string back to RFC 9553 PartialDate for the server
|
||||||
|
function stringToPartialDate(str: string): PartialDate {
|
||||||
|
if (str.startsWith('--')) {
|
||||||
|
const parts = str.substring(2).split('-');
|
||||||
|
const pd: PartialDate = { month: parseInt(parts[0], 10) };
|
||||||
|
if (parts[1]) pd.day = parseInt(parts[1], 10);
|
||||||
|
return pd;
|
||||||
|
}
|
||||||
|
const parts = str.split('-');
|
||||||
|
const pd: PartialDate = {};
|
||||||
|
if (parts[0]) pd.year = parseInt(parts[0], 10);
|
||||||
|
if (parts[1]) pd.month = parseInt(parts[1], 10);
|
||||||
|
if (parts[2]) pd.day = parseInt(parts[2], 10);
|
||||||
|
return pd;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract flat address fields from RFC 9553 components format
|
||||||
|
function addressToFlat(a: ContactAddress): AddressEntry {
|
||||||
|
if (a.components && a.components.length > 0) {
|
||||||
|
const findComp = (kind: string) => a.components!.filter(c => c.kind === kind).map(c => c.value).join(' ');
|
||||||
|
return {
|
||||||
|
street: findComp('name') || findComp('number') ? [findComp('number'), findComp('name')].filter(Boolean).join(' ') : '',
|
||||||
|
locality: findComp('locality'),
|
||||||
|
region: findComp('region'),
|
||||||
|
postcode: findComp('postcode'),
|
||||||
|
country: findComp('country'),
|
||||||
|
context: a.contexts?.work ? 'work' : a.contexts?.private ? 'private' : '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
street: a.street || '',
|
||||||
|
locality: a.locality || '',
|
||||||
|
region: a.region || '',
|
||||||
|
postcode: a.postcode || '',
|
||||||
|
country: a.country || '',
|
||||||
|
context: a.contexts?.work ? 'work' : a.contexts?.private ? 'private' : '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const [prefix, setPrefix] = useState(findComponent("prefix"));
|
const [prefix, setPrefix] = useState(findComponent("prefix"));
|
||||||
const [givenName, setGivenName] = useState(findComponent("given"));
|
const [givenName, setGivenName] = useState(findComponent("given"));
|
||||||
const [additionalName, setAdditionalName] = useState(findComponent("additional"));
|
const [additionalName, setAdditionalName] = useState(findComponent("additional"));
|
||||||
@@ -184,14 +245,7 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
|
|
||||||
const [addresses, setAddresses] = useState<AddressEntry[]>(() => {
|
const [addresses, setAddresses] = useState<AddressEntry[]>(() => {
|
||||||
if (contact?.addresses) {
|
if (contact?.addresses) {
|
||||||
return Object.values(contact.addresses).map(a => ({
|
return Object.values(contact.addresses).map(a => addressToFlat(a));
|
||||||
street: a.street || "",
|
|
||||||
locality: a.locality || "",
|
|
||||||
region: a.region || "",
|
|
||||||
postcode: a.postcode || "",
|
|
||||||
country: a.country || "",
|
|
||||||
context: a.contexts?.work ? "work" : a.contexts?.private ? "private" : "",
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
return [];
|
return [];
|
||||||
});
|
});
|
||||||
@@ -210,7 +264,7 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
const [anniversaries, setAnniversaries] = useState<AnniversaryEntry[]>(() => {
|
const [anniversaries, setAnniversaries] = useState<AnniversaryEntry[]>(() => {
|
||||||
if (contact?.anniversaries) {
|
if (contact?.anniversaries) {
|
||||||
return Object.values(contact.anniversaries).map(a => ({
|
return Object.values(contact.anniversaries).map(a => ({
|
||||||
date: a.date,
|
date: anniversaryDateToString(a.date),
|
||||||
kind: a.kind,
|
kind: a.kind,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -336,12 +390,13 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
|
|
||||||
const addressesMap: Record<string, ContactCard["addresses"] extends Record<string, infer V> ? V : never> = {};
|
const addressesMap: Record<string, ContactCard["addresses"] extends Record<string, infer V> ? V : never> = {};
|
||||||
addresses.filter(a => a.street.trim() || a.locality.trim() || a.country.trim()).forEach((a, i) => {
|
addresses.filter(a => a.street.trim() || a.locality.trim() || a.country.trim()).forEach((a, i) => {
|
||||||
const obj: Record<string, unknown> = {};
|
const components: Array<{ kind: string; value: string }> = [];
|
||||||
if (a.street.trim()) obj.street = a.street.trim();
|
if (a.street.trim()) components.push({ kind: "name", value: a.street.trim() });
|
||||||
if (a.locality.trim()) obj.locality = a.locality.trim();
|
if (a.locality.trim()) components.push({ kind: "locality", value: a.locality.trim() });
|
||||||
if (a.region.trim()) obj.region = a.region.trim();
|
if (a.region.trim()) components.push({ kind: "region", value: a.region.trim() });
|
||||||
if (a.postcode.trim()) obj.postcode = a.postcode.trim();
|
if (a.postcode.trim()) components.push({ kind: "postcode", value: a.postcode.trim() });
|
||||||
if (a.country.trim()) obj.country = a.country.trim();
|
if (a.country.trim()) components.push({ kind: "country", value: a.country.trim() });
|
||||||
|
const obj: Record<string, unknown> = { components, isOrdered: true, defaultSeparator: ", " };
|
||||||
if (a.context) obj.contexts = { [a.context]: true };
|
if (a.context) obj.contexts = { [a.context]: true };
|
||||||
// @ts-expect-error - dynamic build
|
// @ts-expect-error - dynamic build
|
||||||
addressesMap[`a${i}`] = obj;
|
addressesMap[`a${i}`] = obj;
|
||||||
@@ -357,7 +412,7 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
|
|
||||||
const anniversariesMap: Record<string, ContactAnniversary> = {};
|
const anniversariesMap: Record<string, ContactAnniversary> = {};
|
||||||
anniversaries.filter(a => a.date.trim()).forEach((a, i) => {
|
anniversaries.filter(a => a.date.trim()).forEach((a, i) => {
|
||||||
anniversariesMap[`an${i}`] = { date: a.date.trim(), kind: a.kind };
|
anniversariesMap[`an${i}`] = { date: stringToPartialDate(a.date.trim()), kind: a.kind };
|
||||||
});
|
});
|
||||||
|
|
||||||
const personalInfoMap: Record<string, ContactPersonalInfo> = {};
|
const personalInfoMap: Record<string, ContactPersonalInfo> = {};
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { substitutePlaceholders } from "@/lib/template-utils";
|
|||||||
import { TemplatePicker } from "@/components/templates/template-picker";
|
import { TemplatePicker } from "@/components/templates/template-picker";
|
||||||
import { TemplateForm } from "@/components/templates/template-form";
|
import { TemplateForm } from "@/components/templates/template-form";
|
||||||
import type { EmailTemplate } from "@/lib/template-types";
|
import type { EmailTemplate } from "@/lib/template-types";
|
||||||
|
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
|
||||||
|
|
||||||
export interface ComposerDraftData {
|
export interface ComposerDraftData {
|
||||||
to: string;
|
to: string;
|
||||||
@@ -199,6 +200,14 @@ export function EmailComposer({
|
|||||||
const { client } = useAuthStore();
|
const { client } = useAuthStore();
|
||||||
const identities = useIdentityStore((s) => s.identities);
|
const identities = useIdentityStore((s) => s.identities);
|
||||||
const primaryIdentity = identities[0] ?? null;
|
const primaryIdentity = identities[0] ?? null;
|
||||||
|
const currentIdentity = selectedIdentityId
|
||||||
|
? identities.find((identity) => identity.id === selectedIdentityId) || primaryIdentity
|
||||||
|
: primaryIdentity;
|
||||||
|
const composerSignatureHtml = currentIdentity?.htmlSignature
|
||||||
|
? `<div>${sanitizeEmailHtml(currentIdentity.htmlSignature)}</div>`
|
||||||
|
: currentIdentity?.textSignature
|
||||||
|
? `<div>${getPlainTextSignature(currentIdentity).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')}</div>`
|
||||||
|
: '';
|
||||||
const getAutocomplete = useContactStore((s) => s.getAutocomplete);
|
const getAutocomplete = useContactStore((s) => s.getAutocomplete);
|
||||||
const addTemplate = useTemplateStore((s) => s.addTemplate);
|
const addTemplate = useTemplateStore((s) => s.addTemplate);
|
||||||
const sendRawEmail = useEmailStore((s) => s.sendRawEmail);
|
const sendRawEmail = useEmailStore((s) => s.sendRawEmail);
|
||||||
@@ -527,10 +536,6 @@ export function EmailComposer({
|
|||||||
setSaveStatus('saving');
|
setSaveStatus('saving');
|
||||||
|
|
||||||
// Get the selected identity or primary identity
|
// Get the selected identity or primary identity
|
||||||
const currentIdentity = selectedIdentityId
|
|
||||||
? identities.find(id => id.id === selectedIdentityId)
|
|
||||||
: primaryIdentity;
|
|
||||||
|
|
||||||
// Generate sub-addressed email if tag is set
|
// Generate sub-addressed email if tag is set
|
||||||
const fromEmail = currentIdentity?.email
|
const fromEmail = currentIdentity?.email
|
||||||
? subAddressTag
|
? subAddressTag
|
||||||
@@ -649,10 +654,6 @@ export function EmailComposer({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentIdentity = selectedIdentityId
|
|
||||||
? identities.find(id => id.id === selectedIdentityId)
|
|
||||||
: primaryIdentity;
|
|
||||||
|
|
||||||
const fromEmail = currentIdentity?.email
|
const fromEmail = currentIdentity?.email
|
||||||
? subAddressTag
|
? subAddressTag
|
||||||
? generateSubAddress(currentIdentity.email, subAddressTag)
|
? generateSubAddress(currentIdentity.email, subAddressTag)
|
||||||
@@ -660,10 +661,7 @@ export function EmailComposer({
|
|||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
// Append signature from the selected identity
|
// Append signature from the selected identity
|
||||||
let finalBody = body;
|
let finalBody = appendPlainTextSignature(body, currentIdentity);
|
||||||
if (currentIdentity?.textSignature) {
|
|
||||||
finalBody = body + '\n\n-- \n' + currentIdentity.textSignature;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Append quoted original text for the plain text part in reply/forward
|
// Append quoted original text for the plain text part in reply/forward
|
||||||
if (replyTo && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
if (replyTo && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
||||||
@@ -1126,6 +1124,13 @@ export function EmailComposer({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{composerSignatureHtml && (
|
||||||
|
<div
|
||||||
|
className="px-4 pb-3 text-sm leading-6 text-foreground break-words [&_a]:text-primary [&_a]:underline-offset-2 [&_a:hover]:underline"
|
||||||
|
dangerouslySetInnerHTML={{ __html: `<div>-- </div>${composerSignatureHtml}` }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Quoted original HTML */}
|
{/* Quoted original HTML */}
|
||||||
{replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward') && (
|
{replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward') && (
|
||||||
<div className="border-t border-border">
|
<div className="border-t border-border">
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import ReactDOM from "react-dom";
|
|||||||
import DOMPurify from "dompurify";
|
import DOMPurify from "dompurify";
|
||||||
import { Email, ContactCard, Mailbox } from "@/lib/jmap/types";
|
import { Email, ContactCard, Mailbox } from "@/lib/jmap/types";
|
||||||
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
|
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
|
||||||
|
import { hasMeaningfulHtmlBody } from "@/lib/signature-utils";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { formatFileSize, cn, buildMailboxTree, MailboxNode, formatDateTime } from "@/lib/utils";
|
import { formatFileSize, cn, buildMailboxTree, MailboxNode, formatDateTime } from "@/lib/utils";
|
||||||
@@ -706,7 +707,11 @@ function ContactSidebarPanel({
|
|||||||
<SidebarSection icon={MapPin} title="Addresses">
|
<SidebarSection icon={MapPin} title="Addresses">
|
||||||
{addresses.map((a, i) => (
|
{addresses.map((a, i) => (
|
||||||
<div key={i} className="text-sm text-muted-foreground">
|
<div key={i} className="text-sm text-muted-foreground">
|
||||||
{[a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
|
{a.full || a.fullAddress
|
||||||
|
? (a.full || a.fullAddress)
|
||||||
|
: a.components && a.components.length > 0
|
||||||
|
? a.components.filter(c => c.kind !== 'separator').map(c => c.value).filter(Boolean).join(", ")
|
||||||
|
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</SidebarSection>
|
</SidebarSection>
|
||||||
@@ -2144,9 +2149,7 @@ export function EmailViewer({
|
|||||||
// Server-generated HTML from text/plain emails often lacks <br> tags, collapsing newlines.
|
// Server-generated HTML from text/plain emails often lacks <br> tags, collapsing newlines.
|
||||||
const hasTextBody = email.textBody?.[0]?.partId && email.bodyValues[email.textBody[0].partId];
|
const hasTextBody = email.textBody?.[0]?.partId && email.bodyValues[email.textBody[0].partId];
|
||||||
if (hasTextBody && htmlContent) {
|
if (hasTextBody && htmlContent) {
|
||||||
const stripped = htmlContent.replace(/<\/?(html|head|body|meta|!doctype|!DOCTYPE|br\s*\/?)[^>]*>/gi, '').trim();
|
useHtmlVersion = hasMeaningfulHtmlBody(htmlContent);
|
||||||
const hasRichContent = /<(table|tr|td|th|img|style|link|div\s+[^>]*class|span\s+[^>]*class|font|center|blockquote|ul|ol|li|h[1-6])\b/i.test(stripped);
|
|
||||||
useHtmlVersion = hasRichContent;
|
|
||||||
} else {
|
} else {
|
||||||
useHtmlVersion = !!htmlContent;
|
useHtmlVersion = !!htmlContent;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useState, useEffect, useMemo } from "react";
|
|||||||
import DOMPurify from "dompurify";
|
import DOMPurify from "dompurify";
|
||||||
import { Email, ThreadGroup } from "@/lib/jmap/types";
|
import { Email, ThreadGroup } from "@/lib/jmap/types";
|
||||||
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
|
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
|
||||||
|
import { hasMeaningfulHtmlBody } from "@/lib/signature-utils";
|
||||||
import { transformInlineStyles, transformColorForDarkMode, transformBgColorForDarkMode } from "@/lib/color-transform";
|
import { transformInlineStyles, transformColorForDarkMode, transformBgColorForDarkMode } from "@/lib/color-transform";
|
||||||
import { useThemeStore } from "@/stores/theme-store";
|
import { useThemeStore } from "@/stores/theme-store";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
@@ -320,9 +321,7 @@ function EmailCard({
|
|||||||
// Server-generated HTML from text/plain emails often lacks <br> tags, collapsing newlines.
|
// Server-generated HTML from text/plain emails often lacks <br> tags, collapsing newlines.
|
||||||
const hasTextBody = email.textBody?.[0]?.partId && email.bodyValues[email.textBody[0].partId];
|
const hasTextBody = email.textBody?.[0]?.partId && email.bodyValues[email.textBody[0].partId];
|
||||||
if (hasTextBody && htmlContent) {
|
if (hasTextBody && htmlContent) {
|
||||||
const stripped = htmlContent.replace(/<\/?(html|head|body|meta|!doctype|!DOCTYPE|br\s*\/?)[^>]*>/gi, '').trim();
|
useHtmlVersion = hasMeaningfulHtmlBody(htmlContent);
|
||||||
const hasRichContent = /<(table|tr|td|th|img|style|link|div\s+[^>]*class|span\s+[^>]*class|font|center|blockquote|ul|ol|li|h[1-6])\b/i.test(stripped);
|
|
||||||
useHtmlVersion = hasRichContent;
|
|
||||||
} else {
|
} else {
|
||||||
useHtmlVersion = !!htmlContent;
|
useHtmlVersion = !!htmlContent;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,9 @@ export function CalendarManagementSettings() {
|
|||||||
const { client, serverUrl, username } = useAuthStore();
|
const { client, serverUrl, username } = useAuthStore();
|
||||||
const { calendars, updateCalendar, createCalendar, removeCalendar, clearCalendarEvents, fetchCalendars, icalSubscriptions, removeICalSubscription, refreshICalSubscription, isSubscriptionCalendar } = useCalendarStore();
|
const { calendars, updateCalendar, createCalendar, removeCalendar, clearCalendarEvents, fetchCalendars, icalSubscriptions, removeICalSubscription, refreshICalSubscription, isSubscriptionCalendar } = useCalendarStore();
|
||||||
|
|
||||||
|
const [discoveredCalDavUrls, setDiscoveredCalDavUrls] = useState<Record<string, string | null>>({});
|
||||||
|
const [wellKnownCalDavUrl, setWellKnownCalDavUrl] = useState<string | null>(null);
|
||||||
|
|
||||||
const [isCreating, setIsCreating] = useState(false);
|
const [isCreating, setIsCreating] = useState(false);
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
@@ -175,6 +178,60 @@ export function CalendarManagementSettings() {
|
|||||||
}
|
}
|
||||||
}, [client, calendars.length, fetchCalendars]);
|
}, [client, calendars.length, fetchCalendars]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!client || !serverUrl || !username) {
|
||||||
|
setDiscoveredCalDavUrls({});
|
||||||
|
setWellKnownCalDavUrl(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const primaryKey = username;
|
||||||
|
const accounts = new Map<string, string[]>();
|
||||||
|
accounts.set(primaryKey, [username]);
|
||||||
|
|
||||||
|
for (const calendar of calendars) {
|
||||||
|
if (!calendar.isShared) continue;
|
||||||
|
const key = calendar.accountId || calendar.accountName || calendar.id;
|
||||||
|
const candidates = accounts.get(key) || [];
|
||||||
|
if (calendar.accountId) candidates.push(calendar.accountId);
|
||||||
|
if (calendar.accountName) candidates.push(calendar.accountName);
|
||||||
|
accounts.set(key, candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
|
||||||
|
fetch('/api/caldav/discover', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
accounts: Array.from(accounts.entries()).map(([key, candidates]) => ({ key, candidates })),
|
||||||
|
}),
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
.then(async (response) => {
|
||||||
|
if (!response.ok) throw new Error(`CalDAV discovery failed: ${response.status}`);
|
||||||
|
return response.json() as Promise<{
|
||||||
|
wellKnownUrl?: string;
|
||||||
|
accounts?: Record<string, { url: string | null }>;
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
.then((payload) => {
|
||||||
|
setWellKnownCalDavUrl(payload.wellKnownUrl || null);
|
||||||
|
const next: Record<string, string | null> = {};
|
||||||
|
for (const [key, value] of Object.entries(payload.accounts || {})) {
|
||||||
|
next[key] = value?.url || null;
|
||||||
|
}
|
||||||
|
setDiscoveredCalDavUrls(next);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
const fallbackWellKnown = new URL('/.well-known/caldav', serverUrl).toString();
|
||||||
|
setDiscoveredCalDavUrls({});
|
||||||
|
setWellKnownCalDavUrl(fallbackWellKnown);
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => controller.abort();
|
||||||
|
}, [client, calendars, serverUrl, username]);
|
||||||
|
|
||||||
const handleRefreshSubscription = async (subId: string) => {
|
const handleRefreshSubscription = async (subId: string) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
setRefreshingSubId(subId);
|
setRefreshingSubId(subId);
|
||||||
@@ -295,8 +352,10 @@ export function CalendarManagementSettings() {
|
|||||||
|
|
||||||
const buildCalDavUrl = (calendarId: string) => {
|
const buildCalDavUrl = (calendarId: string) => {
|
||||||
if (!serverUrl || !username) return null;
|
if (!serverUrl || !username) return null;
|
||||||
const base = serverUrl.replace(/\/$/, '');
|
const calendar = calendars.find((entry) => entry.id === calendarId);
|
||||||
return `${base}/dav/cal/${encodeURIComponent(username)}/${encodeURIComponent(calendarId)}/`;
|
if (!calendar) return null;
|
||||||
|
const accountKey = calendar.isShared ? (calendar.accountId || calendar.accountName || calendar.id) : username;
|
||||||
|
return discoveredCalDavUrls[accountKey] || wellKnownCalDavUrl;
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCopyUrl = async (url: string) => {
|
const handleCopyUrl = async (url: string) => {
|
||||||
|
|||||||
@@ -490,21 +490,34 @@ export function FolderSettings() {
|
|||||||
|
|
||||||
{/* Standard Folder Roles — advanced section */}
|
{/* Standard Folder Roles — advanced section */}
|
||||||
<SettingsSection title={t('standard_roles')} description={t('standard_roles_description')}>
|
<SettingsSection title={t('standard_roles')} description={t('standard_roles_description')}>
|
||||||
{STANDARD_ROLES.map((role) => (
|
{STANDARD_ROLES.map((role) => {
|
||||||
<SettingItem key={role} label={t(`role_${role}`)}>
|
// Disambiguate duplicate folder names by appending parent path
|
||||||
<Select
|
const nameCounts = new Map<string, number>();
|
||||||
value={getRoleMailboxId(role)}
|
ownMailboxes.forEach(mb => nameCounts.set(mb.name, (nameCounts.get(mb.name) || 0) + 1));
|
||||||
onChange={(value) => handleRoleChange(role, value)}
|
const getParentPath = (mb: { parentId?: string; name: string }) => {
|
||||||
options={[
|
if (!mb.parentId) return '';
|
||||||
{ value: '', label: t('role_none') },
|
const parent = ownMailboxes.find(p => p.id === mb.parentId);
|
||||||
...ownMailboxes.map(mb => ({
|
return parent ? `${parent.name}/` : '';
|
||||||
value: mb.id,
|
};
|
||||||
label: mb.name,
|
|
||||||
})),
|
return (
|
||||||
]}
|
<SettingItem key={role} label={t(`role_${role}`)}>
|
||||||
/>
|
<Select
|
||||||
</SettingItem>
|
value={getRoleMailboxId(role)}
|
||||||
))}
|
onChange={(value) => handleRoleChange(role, value)}
|
||||||
|
options={[
|
||||||
|
{ value: '', label: t('role_none') },
|
||||||
|
...ownMailboxes.map(mb => ({
|
||||||
|
value: mb.id,
|
||||||
|
label: (nameCounts.get(mb.name) || 0) > 1
|
||||||
|
? `${getParentPath(mb)}${mb.name} (${mb.id.slice(-6)})`
|
||||||
|
: mb.name,
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export default [
|
|||||||
"*.config.js",
|
"*.config.js",
|
||||||
"*.config.mjs",
|
"*.config.mjs",
|
||||||
"e2e/**",
|
"e2e/**",
|
||||||
|
"local-data/**/*.mjs",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
appendPlainTextSignature,
|
||||||
|
getPlainTextSignature,
|
||||||
|
hasMeaningfulHtmlBody,
|
||||||
|
} from '../signature-utils';
|
||||||
|
|
||||||
|
describe('signature-utils', () => {
|
||||||
|
describe('getPlainTextSignature', () => {
|
||||||
|
it('prefers text signatures when present', () => {
|
||||||
|
expect(getPlainTextSignature({ textSignature: 'Regards,\nAlice', htmlSignature: '<p>Ignored</p>' })).toBe('Regards,\nAlice');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('converts html-only signatures into plain text', () => {
|
||||||
|
expect(getPlainTextSignature({ htmlSignature: '<p>Alice Example<br><a href="mailto:alice@example.com">alice@example.com</a></p>' })).toBe('Alice Example\nalice@example.com');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('appendPlainTextSignature', () => {
|
||||||
|
it('appends a converted html signature to the text body', () => {
|
||||||
|
expect(appendPlainTextSignature('Hello there', { htmlSignature: '<p>Alice<br>Engineering</p>' })).toBe('Hello there\n\n-- \nAlice\nEngineering');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the body untouched when no signature exists', () => {
|
||||||
|
expect(appendPlainTextSignature('Hello there', {})).toBe('Hello there');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('hasMeaningfulHtmlBody', () => {
|
||||||
|
it('prefers html bodies that preserve signature formatting', () => {
|
||||||
|
expect(hasMeaningfulHtmlBody('<div>Hello</div><br><p>Alice</p>')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores minimal wrapper html with a single block', () => {
|
||||||
|
expect(hasMeaningfulHtmlBody('<div>Hello world</div>')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export function replaceWindowLocation(url: string): void {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.location.replace(url);
|
||||||
|
}
|
||||||
@@ -142,3 +142,7 @@ export function formatSnapTime(minutes: number, timeFormat: "12h" | "24h"): stri
|
|||||||
}
|
}
|
||||||
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
|
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getPrimaryCalendarId(event: Pick<CalendarEvent, 'calendarIds'>): string | undefined {
|
||||||
|
return Object.keys(event.calendarIds || {})[0];
|
||||||
|
}
|
||||||
|
|||||||
+32
-1
@@ -252,7 +252,20 @@ export interface ContactTitle {
|
|||||||
organizationId?: string;
|
organizationId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RFC 9553 AddressComponent
|
||||||
|
export interface AddressComponent {
|
||||||
|
kind: 'room' | 'apartment' | 'floor' | 'building' | 'number' | 'name' | 'block' | 'subDistrict' | 'district' | 'locality' | 'region' | 'postcode' | 'country' | 'direction' | 'landmark' | 'postOfficeBox' | 'separator' | string;
|
||||||
|
value: string;
|
||||||
|
phonetic?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ContactAddress {
|
export interface ContactAddress {
|
||||||
|
// RFC 9553 format
|
||||||
|
components?: AddressComponent[];
|
||||||
|
full?: string;
|
||||||
|
isOrdered?: boolean;
|
||||||
|
defaultSeparator?: string;
|
||||||
|
// Legacy flat fields (from vCard import)
|
||||||
street?: string;
|
street?: string;
|
||||||
locality?: string;
|
locality?: string;
|
||||||
region?: string;
|
region?: string;
|
||||||
@@ -284,9 +297,27 @@ export interface ContactMedia {
|
|||||||
mediaType?: string;
|
mediaType?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RFC 9553 PartialDate
|
||||||
|
export interface PartialDate {
|
||||||
|
'@type'?: 'PartialDate';
|
||||||
|
year?: number;
|
||||||
|
month?: number;
|
||||||
|
day?: number;
|
||||||
|
calendarScale?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 9553 Timestamp
|
||||||
|
export interface Timestamp {
|
||||||
|
'@type': 'Timestamp';
|
||||||
|
utc: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AnniversaryDate = string | PartialDate | Timestamp;
|
||||||
|
|
||||||
export interface ContactAnniversary {
|
export interface ContactAnniversary {
|
||||||
|
'@type'?: 'Anniversary';
|
||||||
kind: 'birth' | 'death' | 'wedding' | 'other';
|
kind: 'birth' | 'death' | 'wedding' | 'other';
|
||||||
date: string;
|
date: AnniversaryDate;
|
||||||
place?: ContactAddress;
|
place?: ContactAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { parseHtmlSafely, sanitizeSignatureHtml } from '@/lib/email-sanitization';
|
||||||
|
|
||||||
|
type SignatureSource = {
|
||||||
|
textSignature?: string;
|
||||||
|
htmlSignature?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const BLOCK_TAGS = new Set([
|
||||||
|
'address',
|
||||||
|
'article',
|
||||||
|
'aside',
|
||||||
|
'blockquote',
|
||||||
|
'div',
|
||||||
|
'footer',
|
||||||
|
'header',
|
||||||
|
'li',
|
||||||
|
'nav',
|
||||||
|
'p',
|
||||||
|
'section',
|
||||||
|
'tr',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function normalizeSignatureLineBreaks(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/\r\n?/g, '\n')
|
||||||
|
.replace(/\u00a0/g, ' ')
|
||||||
|
.replace(/[ \t]+\n/g, '\n')
|
||||||
|
.replace(/\n{3,}/g, '\n\n')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function htmlToPlainText(html: string): string {
|
||||||
|
const document = parseHtmlSafely(html);
|
||||||
|
const chunks: string[] = [];
|
||||||
|
|
||||||
|
const appendText = (value: string) => {
|
||||||
|
if (!value) return;
|
||||||
|
const normalized = value.replace(/\s+/g, ' ');
|
||||||
|
if (!normalized.trim()) return;
|
||||||
|
const previous = chunks[chunks.length - 1];
|
||||||
|
if (previous && !previous.endsWith('\n') && !previous.endsWith(' ')) {
|
||||||
|
chunks.push(' ');
|
||||||
|
}
|
||||||
|
chunks.push(normalized);
|
||||||
|
};
|
||||||
|
|
||||||
|
const appendNewline = () => {
|
||||||
|
const previous = chunks[chunks.length - 1];
|
||||||
|
if (previous === '\n') return;
|
||||||
|
if (previous?.endsWith('\n')) return;
|
||||||
|
chunks.push('\n');
|
||||||
|
};
|
||||||
|
|
||||||
|
const walk = (node: Node) => {
|
||||||
|
if (node.nodeType === Node.TEXT_NODE) {
|
||||||
|
appendText(node.textContent || '');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.nodeType !== Node.ELEMENT_NODE) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const element = node as HTMLElement;
|
||||||
|
const tagName = element.tagName.toLowerCase();
|
||||||
|
|
||||||
|
if (tagName === 'br') {
|
||||||
|
appendNewline();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tagName === 'a') {
|
||||||
|
const text = element.textContent?.replace(/\s+/g, ' ').trim() || '';
|
||||||
|
const href = element.getAttribute('href')?.trim() || '';
|
||||||
|
const normalizedHref = href.replace(/^mailto:/i, '');
|
||||||
|
if (text && normalizedHref && text === normalizedHref) {
|
||||||
|
appendText(text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (text && href && text !== href) {
|
||||||
|
appendText(`${text} <${href}>`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (BLOCK_TAGS.has(tagName) && chunks.length > 0) {
|
||||||
|
appendNewline();
|
||||||
|
}
|
||||||
|
|
||||||
|
Array.from(element.childNodes).forEach(walk);
|
||||||
|
|
||||||
|
if (BLOCK_TAGS.has(tagName)) {
|
||||||
|
appendNewline();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Array.from(document.body.childNodes).forEach(walk);
|
||||||
|
return normalizeSignatureLineBreaks(chunks.join(''));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPlainTextSignature(signature?: SignatureSource | null): string {
|
||||||
|
if (signature?.textSignature?.trim()) {
|
||||||
|
return normalizeSignatureLineBreaks(signature.textSignature);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (signature?.htmlSignature?.trim()) {
|
||||||
|
return htmlToPlainText(sanitizeSignatureHtml(signature.htmlSignature));
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appendPlainTextSignature(body: string, signature?: SignatureSource | null): string {
|
||||||
|
const plainTextSignature = getPlainTextSignature(signature);
|
||||||
|
if (!plainTextSignature) {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${body}\n\n-- \n${plainTextSignature}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasMeaningfulHtmlBody(html: string): boolean {
|
||||||
|
if (!html.trim()) return false;
|
||||||
|
|
||||||
|
const document = parseHtmlSafely(html);
|
||||||
|
const richSelector = [
|
||||||
|
'table',
|
||||||
|
'img',
|
||||||
|
'style',
|
||||||
|
'b',
|
||||||
|
'strong',
|
||||||
|
'i',
|
||||||
|
'em',
|
||||||
|
'u',
|
||||||
|
'font',
|
||||||
|
'a[href]',
|
||||||
|
'div[style]',
|
||||||
|
'span[style]',
|
||||||
|
'p[style]',
|
||||||
|
'h1',
|
||||||
|
'h2',
|
||||||
|
'h3',
|
||||||
|
'h4',
|
||||||
|
'h5',
|
||||||
|
'h6',
|
||||||
|
'ul',
|
||||||
|
'ol',
|
||||||
|
'blockquote',
|
||||||
|
'br',
|
||||||
|
].join(', ');
|
||||||
|
|
||||||
|
if (document.querySelector(richSelector)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const blockElements = document.body.querySelectorAll('p, div, blockquote, li');
|
||||||
|
return blockElements.length > 1;
|
||||||
|
}
|
||||||
+10
-6
@@ -97,17 +97,19 @@ const ROLE_PRIORITY: Record<string, number> = {
|
|||||||
|
|
||||||
// Deduplicate mailboxes (e.g., "Sent" vs "Sent Mail")
|
// Deduplicate mailboxes (e.g., "Sent" vs "Sent Mail")
|
||||||
function deduplicateMailboxes(mailboxes: Mailbox[]): Mailbox[] {
|
function deduplicateMailboxes(mailboxes: Mailbox[]): Mailbox[] {
|
||||||
const roleMap = new Map<string, Mailbox>();
|
|
||||||
const result: Mailbox[] = [];
|
const result: Mailbox[] = [];
|
||||||
|
|
||||||
// First pass: collect mailboxes with roles
|
// Group role mailboxes by account so deduplication is scoped per-account
|
||||||
|
const rolesByAccount = new Map<string, Mailbox[]>();
|
||||||
mailboxes.forEach(mb => {
|
mailboxes.forEach(mb => {
|
||||||
if (mb.role) {
|
if (mb.role) {
|
||||||
roleMap.set(mb.role, mb);
|
const key = mb.accountId || '';
|
||||||
|
if (!rolesByAccount.has(key)) rolesByAccount.set(key, []);
|
||||||
|
rolesByAccount.get(key)!.push(mb);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Second pass: filter out duplicates
|
// Filter out duplicates scoped to the same account
|
||||||
mailboxes.forEach(mb => {
|
mailboxes.forEach(mb => {
|
||||||
// If this mailbox has a role, always keep it
|
// If this mailbox has a role, always keep it
|
||||||
if (mb.role) {
|
if (mb.role) {
|
||||||
@@ -115,9 +117,11 @@ function deduplicateMailboxes(mailboxes: Mailbox[]): Mailbox[] {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if this is a duplicate of a role-based mailbox
|
// Check if this is a duplicate of a role-based mailbox in the SAME account
|
||||||
|
const accountKey = mb.accountId || '';
|
||||||
|
const accountRoles = rolesByAccount.get(accountKey) || [];
|
||||||
const lowerName = mb.name.toLowerCase();
|
const lowerName = mb.name.toLowerCase();
|
||||||
const isDuplicate = Array.from(roleMap.values()).some(roleMb => {
|
const isDuplicate = accountRoles.some(roleMb => {
|
||||||
const roleLowerName = roleMb.name.toLowerCase();
|
const roleLowerName = roleMb.name.toLowerCase();
|
||||||
// Check for common duplicates: "Sent Mail" vs "Sent", etc.
|
// Check for common duplicates: "Sent Mail" vs "Sent", etc.
|
||||||
return lowerName.includes(roleLowerName) || roleLowerName.includes(lowerName);
|
return lowerName.includes(roleLowerName) || roleLowerName.includes(lowerName);
|
||||||
|
|||||||
+48
-9
@@ -1,4 +1,26 @@
|
|||||||
import type { ContactCard, NameComponent, ContactMedia, ContactOnlineService } from "@/lib/jmap/types";
|
import type { ContactCard, NameComponent, ContactMedia, ContactOnlineService, AnniversaryDate, PartialDate } from "@/lib/jmap/types";
|
||||||
|
|
||||||
|
// Convert RFC 9553 AnniversaryDate (PartialDate|Timestamp|string) to vCard date string
|
||||||
|
function anniversaryDateToVcardString(date: AnniversaryDate): string {
|
||||||
|
if (typeof date === 'string') return date;
|
||||||
|
if (date && typeof date === 'object') {
|
||||||
|
if ('@type' in date && date['@type'] === 'Timestamp' && 'utc' in date) {
|
||||||
|
return (date as { utc: string }).utc.split('T')[0];
|
||||||
|
}
|
||||||
|
const pd = date as PartialDate;
|
||||||
|
if (pd.year && pd.month && pd.day) {
|
||||||
|
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
if (pd.month && pd.day) {
|
||||||
|
return `--${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
if (pd.year && pd.month) {
|
||||||
|
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
if (pd.year) return String(pd.year);
|
||||||
|
}
|
||||||
|
return String(date);
|
||||||
|
}
|
||||||
|
|
||||||
const VCARD_SEX_TO_GENDER: Record<string, string> = {
|
const VCARD_SEX_TO_GENDER: Record<string, string> = {
|
||||||
M: "masculine",
|
M: "masculine",
|
||||||
@@ -598,14 +620,30 @@ function generateSingleVCard(contact: ContactCard): string {
|
|||||||
for (const addr of Object.values(contact.addresses)) {
|
for (const addr of Object.values(contact.addresses)) {
|
||||||
const type = contextToType(addr.contexts);
|
const type = contextToType(addr.contexts);
|
||||||
const typeParam = type ? `;TYPE=${type}` : "";
|
const typeParam = type ? `;TYPE=${type}` : "";
|
||||||
|
let street = addr.street || "";
|
||||||
|
let locality = addr.locality || "";
|
||||||
|
let region = addr.region || "";
|
||||||
|
let postcode = addr.postcode || "";
|
||||||
|
let country = addr.country || "";
|
||||||
|
// RFC 9553 components-based address: extract flat fields for vCard ADR
|
||||||
|
if (addr.components && addr.components.length > 0) {
|
||||||
|
const findComp = (kind: string) => addr.components!.filter(c => c.kind === kind).map(c => c.value).join(' ');
|
||||||
|
const number = findComp('number');
|
||||||
|
const name = findComp('name');
|
||||||
|
street = street || [number, name].filter(Boolean).join(' ');
|
||||||
|
locality = locality || findComp('locality');
|
||||||
|
region = region || findComp('region');
|
||||||
|
postcode = postcode || findComp('postcode');
|
||||||
|
country = country || findComp('country');
|
||||||
|
}
|
||||||
const parts = [
|
const parts = [
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
addr.street || "",
|
street,
|
||||||
addr.locality || "",
|
locality,
|
||||||
addr.region || "",
|
region,
|
||||||
addr.postcode || "",
|
postcode,
|
||||||
addr.country || "",
|
country,
|
||||||
];
|
];
|
||||||
lines.push(`ADR${typeParam}:${parts.map(encodeValue).join(";")}`);
|
lines.push(`ADR${typeParam}:${parts.map(encodeValue).join(";")}`);
|
||||||
}
|
}
|
||||||
@@ -613,12 +651,13 @@ function generateSingleVCard(contact: ContactCard): string {
|
|||||||
|
|
||||||
if (contact.anniversaries) {
|
if (contact.anniversaries) {
|
||||||
for (const ann of Object.values(contact.anniversaries)) {
|
for (const ann of Object.values(contact.anniversaries)) {
|
||||||
|
const dateStr = anniversaryDateToVcardString(ann.date);
|
||||||
if (ann.kind === "birth") {
|
if (ann.kind === "birth") {
|
||||||
lines.push(`BDAY:${ann.date}`);
|
lines.push(`BDAY:${dateStr}`);
|
||||||
} else if (ann.kind === "wedding") {
|
} else if (ann.kind === "wedding") {
|
||||||
lines.push(`ANNIVERSARY:${ann.date}`);
|
lines.push(`ANNIVERSARY:${dateStr}`);
|
||||||
} else if (ann.kind === "death") {
|
} else if (ann.kind === "death") {
|
||||||
lines.push(`DEATHDATE:${ann.date}`);
|
lines.push(`DEATHDATE:${dateStr}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "bulwark-webmail",
|
"name": "bulwark-webmail",
|
||||||
"version": "1.4.3",
|
"version": "1.4.4",
|
||||||
"description": "Bulwark Webmail — a modern webmail client built for Stalwart Mail Server",
|
"description": "Bulwark Webmail — a modern webmail client built for Stalwart Mail Server",
|
||||||
"author": "Bulwark Webmail <bulwark@rbm.systems>",
|
"author": "Bulwark Webmail <bulwark@rbm.systems>",
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import * as browserNavigation from '@/lib/browser-navigation';
|
||||||
|
import { useAuthStore } from '../auth-store';
|
||||||
|
import { useAccountStore } from '../account-store';
|
||||||
|
|
||||||
|
type FetchInput = Parameters<typeof fetch>[0];
|
||||||
|
type FetchInit = Parameters<typeof fetch>[1];
|
||||||
|
|
||||||
|
describe('auth-store logout redirects', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
sessionStorage.clear();
|
||||||
|
localStorage.clear();
|
||||||
|
window.history.pushState({}, '', '/en');
|
||||||
|
|
||||||
|
useAccountStore.setState({
|
||||||
|
accounts: [],
|
||||||
|
activeAccountId: null,
|
||||||
|
defaultAccountId: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
useAuthStore.setState({
|
||||||
|
isAuthenticated: false,
|
||||||
|
isLoading: false,
|
||||||
|
error: null,
|
||||||
|
serverUrl: null,
|
||||||
|
username: null,
|
||||||
|
client: null,
|
||||||
|
identities: [],
|
||||||
|
primaryIdentity: null,
|
||||||
|
authMode: 'basic',
|
||||||
|
rememberMe: false,
|
||||||
|
accessToken: null,
|
||||||
|
tokenExpiresAt: null,
|
||||||
|
connectionLost: false,
|
||||||
|
activeAccountId: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirects full logout to the locale login page', () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
const replaceSpy = vi.spyOn(browserNavigation, 'replaceWindowLocation').mockImplementation(() => {});
|
||||||
|
|
||||||
|
window.history.pushState({}, '', '/fr/calendar');
|
||||||
|
useAuthStore.setState({ isAuthenticated: true, authMode: 'basic' });
|
||||||
|
|
||||||
|
useAuthStore.getState().logout();
|
||||||
|
|
||||||
|
expect(replaceSpy).toHaveBeenCalledWith('/fr/login');
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith('/api/auth/session?slot=0', { method: 'DELETE', keepalive: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks session expiry, preserves the current path, and redirects to login on refresh failure', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
const fetchMock = vi.fn(async (input: FetchInput, init?: FetchInit) => {
|
||||||
|
const url = String(input);
|
||||||
|
const method = init?.method ?? 'GET';
|
||||||
|
|
||||||
|
if (url === '/api/auth/token?slot=0' && method === 'PUT') {
|
||||||
|
return { ok: false, json: async () => ({}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url === '/api/auth/token?slot=0' && method === 'DELETE') {
|
||||||
|
return { ok: true, json: async () => ({}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url === '/api/auth/session?slot=0' && method === 'DELETE') {
|
||||||
|
return { ok: true, json: async () => ({}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected fetch call: ${method} ${url}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
const replaceSpy = vi.spyOn(browserNavigation, 'replaceWindowLocation').mockImplementation(() => {});
|
||||||
|
|
||||||
|
window.history.pushState({}, '', '/en/calendar?view=day');
|
||||||
|
useAuthStore.setState({
|
||||||
|
isAuthenticated: true,
|
||||||
|
authMode: 'oauth',
|
||||||
|
activeAccountId: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
await useAuthStore.getState().refreshAccessToken();
|
||||||
|
await vi.runAllTimersAsync();
|
||||||
|
|
||||||
|
expect(sessionStorage.getItem('session_expired')).toBe('true');
|
||||||
|
expect(sessionStorage.getItem('redirect_after_login')).toBe('/en/calendar?view=day');
|
||||||
|
expect(replaceSpy).toHaveBeenCalledWith('/en/login');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -226,6 +226,34 @@ describe('email-store folder management', () => {
|
|||||||
expect(client.updateMailbox).toHaveBeenCalledWith('trash-1', { role: 'trash' });
|
expect(client.updateMailbox).toHaveBeenCalledWith('trash-1', { role: 'trash' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should clear role from ALL mailboxes with that role when reassigning', async () => {
|
||||||
|
// Simulate server anomaly: two mailboxes with role "trash"
|
||||||
|
const extraTrash = makeMailbox({ id: 'trash-2', name: 'Deleted Items', role: 'trash' });
|
||||||
|
useEmailStore.setState({
|
||||||
|
mailboxes: [inbox, sent, trash, custom, extraTrash],
|
||||||
|
});
|
||||||
|
|
||||||
|
const newMailboxes = [inbox, sent, custom,
|
||||||
|
makeMailbox({ id: 'trash-1', name: 'Trash', role: undefined }),
|
||||||
|
makeMailbox({ id: 'trash-2', name: 'Deleted Items', role: undefined }),
|
||||||
|
];
|
||||||
|
// custom-1 gets the trash role
|
||||||
|
newMailboxes[2] = { ...newMailboxes[2], role: 'trash' };
|
||||||
|
|
||||||
|
const client = makeMockClient({
|
||||||
|
getAllMailboxes: vi.fn().mockResolvedValue(newMailboxes),
|
||||||
|
});
|
||||||
|
|
||||||
|
await useEmailStore.getState().setMailboxRole(client, 'custom-1', 'trash');
|
||||||
|
|
||||||
|
// Should clear trash role from BOTH trash-1 and trash-2
|
||||||
|
expect(client.updateMailbox).toHaveBeenCalledWith('trash-1', { role: null });
|
||||||
|
expect(client.updateMailbox).toHaveBeenCalledWith('trash-2', { role: null });
|
||||||
|
// Then set trash role on custom-1
|
||||||
|
expect(client.updateMailbox).toHaveBeenCalledWith('custom-1', { role: 'trash' });
|
||||||
|
expect(client.updateMailbox).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
it('should set error on failure', async () => {
|
it('should set error on failure', async () => {
|
||||||
const client = makeMockClient({
|
const client = makeMockClient({
|
||||||
updateMailbox: vi.fn().mockRejectedValue(new Error('Role update failed')),
|
updateMailbox: vi.fn().mockRejectedValue(new Error('Role update failed')),
|
||||||
|
|||||||
+21
-4
@@ -58,13 +58,30 @@ export const useAccountStore = create<AccountState>()(
|
|||||||
|
|
||||||
addAccount: (entry) => {
|
addAccount: (entry) => {
|
||||||
const state = get();
|
const state = get();
|
||||||
if (state.accounts.length >= MAX_ACCOUNTS) {
|
|
||||||
throw new Error(`Maximum of ${MAX_ACCOUNTS} accounts reached`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const id = generateAccountId(entry.username, entry.serverUrl);
|
const id = generateAccountId(entry.username, entry.serverUrl);
|
||||||
if (state.accounts.some((a) => a.id === id)) {
|
if (state.accounts.some((a) => a.id === id)) {
|
||||||
return id; // already exists, return existing id
|
// Already exists — update mutable fields and return existing id
|
||||||
|
set((s) => ({
|
||||||
|
accounts: s.accounts.map((a) =>
|
||||||
|
a.id === id
|
||||||
|
? {
|
||||||
|
...a,
|
||||||
|
rememberMe: entry.rememberMe,
|
||||||
|
isConnected: entry.isConnected,
|
||||||
|
hasError: entry.hasError,
|
||||||
|
errorMessage: undefined,
|
||||||
|
lastLoginAt: entry.lastLoginAt,
|
||||||
|
authMode: entry.authMode,
|
||||||
|
}
|
||||||
|
: a
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.accounts.length >= MAX_ACCOUNTS) {
|
||||||
|
throw new Error(`Maximum of ${MAX_ACCOUNTS} accounts reached`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cookieSlot = state.getNextCookieSlot();
|
const cookieSlot = state.getNextCookieSlot();
|
||||||
|
|||||||
+108
-25
@@ -11,6 +11,7 @@ import { useAccountStore } from './account-store';
|
|||||||
import { fetchConfig } from '@/hooks/use-config';
|
import { fetchConfig } from '@/hooks/use-config';
|
||||||
import { debug } from '@/lib/debug';
|
import { debug } from '@/lib/debug';
|
||||||
import { generateAccountId } from '@/lib/account-utils';
|
import { generateAccountId } from '@/lib/account-utils';
|
||||||
|
import { replaceWindowLocation } from '@/lib/browser-navigation';
|
||||||
import { snapshotAccount, restoreAccount, clearAllStores, evictAccount, evictAll } from '@/lib/account-state-manager';
|
import { snapshotAccount, restoreAccount, clearAllStores, evictAccount, evictAll } from '@/lib/account-state-manager';
|
||||||
import type { Identity } from '@/lib/jmap/types';
|
import type { Identity } from '@/lib/jmap/types';
|
||||||
|
|
||||||
@@ -98,8 +99,45 @@ function loadIdentities(rawIdentities: Identity[], username: string): { identiti
|
|||||||
return { identities, primaryIdentity };
|
return { identities, primaryIdentity };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getLocaleLoginPath(): string {
|
||||||
|
if (typeof window === 'undefined') return '/en/login';
|
||||||
|
|
||||||
|
const segments = window.location.pathname.split('/').filter(Boolean);
|
||||||
|
const locale = segments[0] || 'en';
|
||||||
|
return `/${locale}/login`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveRedirectAfterLogin(): void {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const loginPath = getLocaleLoginPath();
|
||||||
|
const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;
|
||||||
|
|
||||||
|
if (currentPath !== loginPath) {
|
||||||
|
sessionStorage.setItem('redirect_after_login', currentPath);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* noop */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirectToLogin(): void {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
const loginPath = getLocaleLoginPath();
|
||||||
|
if (window.location.pathname === loginPath) return;
|
||||||
|
replaceWindowLocation(loginPath);
|
||||||
|
}
|
||||||
|
|
||||||
function markSessionExpired(): void {
|
function markSessionExpired(): void {
|
||||||
try { sessionStorage.setItem('session_expired', 'true'); } catch { /* noop */ }
|
try {
|
||||||
|
sessionStorage.setItem('session_expired', 'true');
|
||||||
|
} catch {
|
||||||
|
/* noop */
|
||||||
|
}
|
||||||
|
|
||||||
|
saveRedirectAfterLogin();
|
||||||
}
|
}
|
||||||
|
|
||||||
function initializeFeatureStores(client: JMAPClient): void {
|
function initializeFeatureStores(client: JMAPClient): void {
|
||||||
@@ -250,6 +288,33 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
});
|
});
|
||||||
accountStore.setActiveAccount(accountId);
|
accountStore.setActiveAccount(accountId);
|
||||||
|
|
||||||
|
// Update account entry in case it already existed (addAccount is a no-op for existing accounts)
|
||||||
|
accountStore.updateAccount(accountId, {
|
||||||
|
rememberMe: !!rememberMe,
|
||||||
|
isConnected: true,
|
||||||
|
hasError: false,
|
||||||
|
errorMessage: undefined,
|
||||||
|
lastLoginAt: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store session cookie BEFORE setting isAuthenticated to avoid a race
|
||||||
|
// condition: setting isAuthenticated triggers navigation to the main page,
|
||||||
|
// whose checkAuth() would try to read the cookie before it was stored.
|
||||||
|
if (rememberMe) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/auth/session?slot=${cookieSlot}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
debug.error('Failed to store session: server returned', res.status);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
debug.error('Failed to store session:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
set({
|
set({
|
||||||
isAuthenticated: true,
|
isAuthenticated: true,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
@@ -259,6 +324,7 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
identities,
|
identities,
|
||||||
primaryIdentity,
|
primaryIdentity,
|
||||||
authMode: 'basic',
|
authMode: 'basic',
|
||||||
|
rememberMe: !!rememberMe,
|
||||||
accessToken: null,
|
accessToken: null,
|
||||||
tokenExpiresAt: null,
|
tokenExpiresAt: null,
|
||||||
connectionLost: false,
|
connectionLost: false,
|
||||||
@@ -274,23 +340,6 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
});
|
});
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
|
|
||||||
if (rememberMe) {
|
|
||||||
try {
|
|
||||||
const res = await fetch(`/api/auth/session?slot=${cookieSlot}`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ serverUrl, username, password: effectivePassword, slot: cookieSlot }),
|
|
||||||
});
|
|
||||||
if (res.ok) {
|
|
||||||
set({ rememberMe: true });
|
|
||||||
} else {
|
|
||||||
debug.error('Failed to store session: server returned', res.status);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
debug.error('Failed to store session:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
debug.error('Login error:', error);
|
debug.error('Login error:', error);
|
||||||
@@ -479,6 +528,7 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
|
|
||||||
// Check if there are remaining accounts to switch to
|
// Check if there are remaining accounts to switch to
|
||||||
const remainingAccounts = accountStore.accounts;
|
const remainingAccounts = accountStore.accounts;
|
||||||
|
const shouldRedirectToLogin = remainingAccounts.length === 0;
|
||||||
if (remainingAccounts.length > 0) {
|
if (remainingAccounts.length > 0) {
|
||||||
// Switch to the next account
|
// Switch to the next account
|
||||||
const nextAccount = remainingAccounts[0];
|
const nextAccount = remainingAccounts[0];
|
||||||
@@ -498,6 +548,7 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
username: nextAccount.username,
|
username: nextAccount.username,
|
||||||
client: nextClient,
|
client: nextClient,
|
||||||
authMode: nextAccount.authMode,
|
authMode: nextAccount.authMode,
|
||||||
|
rememberMe: nextAccount.rememberMe,
|
||||||
connectionLost: false,
|
connectionLost: false,
|
||||||
error: null,
|
error: null,
|
||||||
activeAccountId: nextAccount.id,
|
activeAccountId: nextAccount.id,
|
||||||
@@ -540,28 +591,51 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Clean up cookies for the removed account
|
// Clean up cookies for the removed account
|
||||||
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE' }).catch((err) => {
|
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: shouldRedirectToLogin }).catch((err) => {
|
||||||
debug.error('Failed to clear session cookie:', err);
|
debug.error('Failed to clear session cookie:', err);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (wasOAuth) {
|
if (wasOAuth && shouldRedirectToLogin) {
|
||||||
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE' })
|
let redirectCommitted = false;
|
||||||
|
const commitLoginRedirect = () => {
|
||||||
|
if (redirectCommitted) return;
|
||||||
|
redirectCommitted = true;
|
||||||
|
redirectToLogin();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.setTimeout(commitLoginRedirect, 0);
|
||||||
|
|
||||||
|
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true })
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (!res.ok) throw new Error(`Revocation failed: ${res.status}`);
|
if (!res.ok) throw new Error(`Revocation failed: ${res.status}`);
|
||||||
return res.json();
|
return res.json();
|
||||||
})
|
})
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
if (data.end_session_url && remainingAccounts.length === 0) {
|
if (redirectCommitted) return;
|
||||||
|
|
||||||
|
if (data.end_session_url) {
|
||||||
|
redirectCommitted = true;
|
||||||
const locale = window.location.pathname.split('/')[1] || 'en';
|
const locale = window.location.pathname.split('/')[1] || 'en';
|
||||||
const redirectUri = `${window.location.origin}/${locale}/login`;
|
const redirectUri = `${window.location.origin}/${locale}/login`;
|
||||||
const url = new URL(data.end_session_url);
|
const url = new URL(data.end_session_url);
|
||||||
url.searchParams.set('post_logout_redirect_uri', redirectUri);
|
url.searchParams.set('post_logout_redirect_uri', redirectUri);
|
||||||
window.location.href = url.toString();
|
replaceWindowLocation(url.toString());
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
commitLoginRedirect();
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
debug.error('OAuth logout cleanup failed:', 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();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -604,8 +678,9 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete all cookies
|
// Delete all cookies
|
||||||
fetch('/api/auth/session?all=true', { method: 'DELETE' }).catch(() => {});
|
fetch('/api/auth/session?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
|
||||||
fetch('/api/auth/token?all=true', { method: 'DELETE' }).catch(() => {});
|
fetch('/api/auth/token?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
|
||||||
|
redirectToLogin();
|
||||||
},
|
},
|
||||||
|
|
||||||
switchAccount: async (accountId: string) => {
|
switchAccount: async (accountId: string) => {
|
||||||
@@ -677,6 +752,11 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!targetClient) {
|
if (!targetClient) {
|
||||||
|
accountStore.updateAccount(accountId, {
|
||||||
|
isConnected: false,
|
||||||
|
hasError: true,
|
||||||
|
errorMessage: 'Unable to restore session',
|
||||||
|
});
|
||||||
set({ isLoading: false });
|
set({ isLoading: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -693,6 +773,7 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
username: targetAccount.username,
|
username: targetAccount.username,
|
||||||
client: targetClient,
|
client: targetClient,
|
||||||
authMode: targetAccount.authMode,
|
authMode: targetAccount.authMode,
|
||||||
|
rememberMe: targetAccount.rememberMe,
|
||||||
connectionLost: false,
|
connectionLost: false,
|
||||||
error: null,
|
error: null,
|
||||||
activeAccountId: accountId,
|
activeAccountId: accountId,
|
||||||
@@ -809,6 +890,7 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
identities,
|
identities,
|
||||||
primaryIdentity,
|
primaryIdentity,
|
||||||
authMode: targetAccount.authMode,
|
authMode: targetAccount.authMode,
|
||||||
|
rememberMe: targetAccount.rememberMe,
|
||||||
connectionLost: false,
|
connectionLost: false,
|
||||||
error: null,
|
error: null,
|
||||||
activeAccountId: targetId,
|
activeAccountId: targetId,
|
||||||
@@ -840,6 +922,7 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
identities,
|
identities,
|
||||||
primaryIdentity,
|
primaryIdentity,
|
||||||
authMode: acc.authMode,
|
authMode: acc.authMode,
|
||||||
|
rememberMe: acc.rememberMe,
|
||||||
connectionLost: false,
|
connectionLost: false,
|
||||||
error: null,
|
error: null,
|
||||||
activeAccountId: id,
|
activeAccountId: id,
|
||||||
|
|||||||
@@ -142,13 +142,6 @@ export const useCalendarStore = create<CalendarStore>()(
|
|||||||
}
|
}
|
||||||
const created = await client.createCalendarEvent(cleanEvent, sendSchedulingMessages, targetAccountId);
|
const created = await client.createCalendarEvent(cleanEvent, sendSchedulingMessages, targetAccountId);
|
||||||
set((state) => ({ events: [...state.events, created] }));
|
set((state) => ({ events: [...state.events, created] }));
|
||||||
if (sendSchedulingMessages && created.participants) {
|
|
||||||
try {
|
|
||||||
await client.sendImipInvitation(created);
|
|
||||||
} catch (e) {
|
|
||||||
debug.error('Failed to send invitation emails:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return created;
|
return created;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
debug.error('Failed to create event:', error);
|
debug.error('Failed to create event:', error);
|
||||||
@@ -178,16 +171,6 @@ export const useCalendarStore = create<CalendarStore>()(
|
|||||||
set((state) => ({
|
set((state) => ({
|
||||||
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
|
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
|
||||||
}));
|
}));
|
||||||
if (sendSchedulingMessages) {
|
|
||||||
try {
|
|
||||||
const updatedEvent = await client.getCalendarEvent(realId, targetAccountId);
|
|
||||||
if (updatedEvent?.participants) {
|
|
||||||
await client.sendImipInvitation(updatedEvent);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
debug.error('Failed to send update notification emails:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
debug.error('Failed to update event:', error);
|
debug.error('Failed to update event:', error);
|
||||||
set({ error: 'Failed to update event' });
|
set({ error: 'Failed to update event' });
|
||||||
|
|||||||
@@ -1298,11 +1298,11 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
|
|||||||
|
|
||||||
setMailboxRole: async (client, mailboxId, role) => {
|
setMailboxRole: async (client, mailboxId, role) => {
|
||||||
try {
|
try {
|
||||||
// If assigning a role, first clear that role from any other mailbox
|
// If assigning a role, first clear that role from ALL other mailboxes that have it
|
||||||
if (role) {
|
if (role) {
|
||||||
const existingMailbox = get().mailboxes.find(mb => mb.role === role && !mb.isShared);
|
const existingMailboxes = get().mailboxes.filter(mb => mb.role === role && !mb.isShared && mb.id !== mailboxId);
|
||||||
if (existingMailbox && existingMailbox.id !== mailboxId) {
|
for (const existing of existingMailboxes) {
|
||||||
await client.updateMailbox(existingMailbox.id, { role: null });
|
await client.updateMailbox(existing.id, { role: null });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await client.updateMailbox(mailboxId, { role });
|
await client.updateMailbox(mailboxId, { role });
|
||||||
|
|||||||
Reference in New Issue
Block a user