Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b141240fa3 | ||
|
|
44896dee3e | ||
|
|
a5c5fa6669 | ||
|
|
95af61c4be | ||
|
|
34e495dde3 | ||
|
|
0b721661e9 | ||
|
|
9fa851a674 | ||
|
|
41f91244d9 | ||
|
|
77514bd054 | ||
|
|
4501b3894b | ||
|
|
2edf2fab89 | ||
|
|
d493bb17dc | ||
|
|
234129397d | ||
|
|
9b3a47f9be | ||
|
|
0fcc932e66 | ||
|
|
0fe8e81dc7 | ||
|
|
267f7257cf | ||
|
|
fb8c9db716 | ||
|
|
2793d4b4af | ||
|
|
96c2ee9e13 | ||
|
|
af115e3245 | ||
|
|
fc79bf4f9b | ||
|
|
b844b88733 | ||
|
|
bcdde9f454 | ||
|
|
bb72ac92ae | ||
|
|
6457b27125 | ||
|
|
ef562bcaad | ||
|
|
9fdbb62205 | ||
|
|
2edbf379e2 | ||
|
|
cdc521b693 | ||
|
|
e7249f8bd3 | ||
|
|
a57492d7c0 | ||
|
|
2b4ff2f3de | ||
|
|
5a3f9faafe | ||
|
|
a74cd32364 | ||
|
|
38c04099e2 | ||
|
|
ae14e09f66 | ||
|
|
ada356e440 | ||
|
|
a886edda6f | ||
|
|
ff97d8bc4c | ||
|
|
b1db100c3a | ||
|
|
19584cfef6 | ||
|
|
8a2ef5a6c5 | ||
|
|
477fc8c885 | ||
|
|
84abfe79dd | ||
|
|
8a92d53125 | ||
|
|
6fe4a98b02 | ||
|
|
3186198fad | ||
|
|
5c933a595f | ||
|
|
828ad4df72 | ||
|
|
f720cb3ef8 | ||
|
|
818a02428b | ||
|
|
6ed30059e5 | ||
|
|
a2cb2b2c86 | ||
|
|
1f7cd61fc7 | ||
|
|
070eeeecee | ||
|
|
de35d1d8e8 | ||
|
|
7c5785e9e8 | ||
|
|
54f4d37595 | ||
|
|
71cd826c6f | ||
|
|
e96b9a72e7 | ||
|
|
ce4ebb3dc2 | ||
|
|
6680b65863 | ||
|
|
df64959e60 | ||
|
|
8641275bb4 | ||
|
|
6e78f2a09e | ||
|
|
d429652f72 |
+30
-2
@@ -67,6 +67,17 @@ JMAP_SERVER_URL=https://your-jmap-server.com
|
|||||||
# For Docker, mount a persistent volume at this path.
|
# For Docker, mount a persistent volume at this path.
|
||||||
# SETTINGS_DATA_DIR=./data/settings
|
# SETTINGS_DATA_DIR=./data/settings
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Server Listen Address
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# Hostname the server binds to (default: 0.0.0.0)
|
||||||
|
# Set to "::" for dual-stack
|
||||||
|
# HOSTNAME=0.0.0.0
|
||||||
|
|
||||||
|
# Port the server listens on (default: 3000)
|
||||||
|
# PORT=3000
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Logging
|
# Logging
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -78,10 +89,27 @@ JMAP_SERVER_URL=https://your-jmap-server.com
|
|||||||
# LOG_LEVEL=info
|
# LOG_LEVEL=info
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Login Page Customization (all optional)
|
# Branding (all optional)
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
# Custom logo images for the login page (PNG, SVG, etc.)
|
# Custom favicon for the browser tab.
|
||||||
|
# Supported formats: SVG (recommended), PNG, ICO.
|
||||||
|
# Recommended size: 32×32px minimum, 512×512px maximum (or SVG for best scaling).
|
||||||
|
# Can be an absolute URL or a path relative to the public/ directory.
|
||||||
|
# Defaults to the Bulwark favicon if not set.
|
||||||
|
# FAVICON_URL=/branding/my-favicon.svg
|
||||||
|
|
||||||
|
# Custom logos for the sidebar (shown in the main app after login).
|
||||||
|
# Supported formats: SVG (recommended), PNG, WebP.
|
||||||
|
# Recommended size: min 24×24px, max 128×128px
|
||||||
|
# Can be absolute URLs or paths relative to the public/ directory.
|
||||||
|
# If not set, no logo is shown in the sidebar.
|
||||||
|
# APP_LOGO_LIGHT_URL=/branding/my-logo-color.svg
|
||||||
|
# APP_LOGO_DARK_URL=/branding/my-logo-white.svg
|
||||||
|
|
||||||
|
# Custom logo images for the login page.
|
||||||
|
# Supported formats: SVG (recommended), PNG, WebP.
|
||||||
|
# Recommended size: min 32×32px, max 512×512px
|
||||||
# Can be absolute URLs or paths relative to the public/ directory.
|
# Can be absolute URLs or paths relative to the public/ directory.
|
||||||
# Light mode logo (shown on light backgrounds), defaults to Bulwark logo.
|
# Light mode logo (shown on light backgrounds), defaults to Bulwark logo.
|
||||||
LOGIN_LOGO_LIGHT_URL=/branding/Bulwark_Logo_Color.svg
|
LOGIN_LOGO_LIGHT_URL=/branding/Bulwark_Logo_Color.svg
|
||||||
|
|||||||
@@ -1,5 +1,84 @@
|
|||||||
# 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)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Auth**: Implement multi-account support with up to 5 simultaneous accounts and instant switching
|
||||||
|
- **Auth**: Add account switcher component with connection status, default account selection, and per-account logout
|
||||||
|
- **Auth**: Support multi-account OAuth and basic auth with per-account session persistence
|
||||||
|
- **Contacts**: Enhance contacts sidebar with collapsible sections, bulk operations, and address book grouping
|
||||||
|
- **Contacts**: Add contact import functionality and keyword filtering
|
||||||
|
- **Settings**: Add per-account encrypted settings storage with server-side sync support
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **UI**: Adjust popover alignment in sub-address helper component
|
||||||
|
- **Settings**: Improve error logging in settings sync functionality
|
||||||
|
|
||||||
|
## 1.4.2 (2026-03-19)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Calendar**: Add task list view for calendar tasks with task details and management
|
||||||
|
- **Calendar**: Add shared calendar grouping with visual separation in sidebar
|
||||||
|
- **Calendar**: Support double-click to create events and improve modal date handling
|
||||||
|
- **Contacts**: Add address book directories with drag-and-drop and editor picker
|
||||||
|
- **Email**: Add email attachment support in sendEmail functionality
|
||||||
|
- **Email**: Implement draft editing functionality across email components
|
||||||
|
- **Email**: Implement unwrapping of embedded message/rfc822 attachments with enhanced HTML body validation
|
||||||
|
- **Email**: Add email export/import localization keys for multiple languages
|
||||||
|
- **Contacts**: Update gender handling to use speakToAs structure
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Email**: Resolve default sender to canonical identity on local-part login
|
||||||
|
- **Email**: Refactor overflow handling in EmailViewer to use hidden priorities and layout effects
|
||||||
|
- **Email**: Remove debugMode usage from EmailViewer component
|
||||||
|
- **Calendar**: Enhance IMIP invitation and cancellation handling for calendar events
|
||||||
|
- **Calendar**: Add time-based sorting for events in buildWeekSegments function
|
||||||
|
- **Dependencies**: Update dompurify to 3.3.3 and elliptic to 6.6.1, add undici override
|
||||||
|
|
||||||
|
## 1.4.1 (2026-03-18)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Security**: Add S/MIME certificate management with identity bindings, signer auto-import, unlock controls, and compose/viewer sign, encrypt, decrypt, and verification flows
|
||||||
|
- **Email**: Add TNEF (`winmail.dat`) parsing to extract message bodies and attachments from Outlook rich-text emails
|
||||||
|
- **Email**: Add archive organization modes for archiving directly or into year/month subfolders
|
||||||
|
- **Email**: Add an "Always Show Emails in Light Mode" preference to avoid dark-mode conversion issues
|
||||||
|
- **Email**: Apply the 12-hour or 24-hour time format preference consistently across calendar and email surfaces
|
||||||
|
- **Identity**: Add identity refresh behavior in the identity manager so server-side changes stay in sync after edits
|
||||||
|
- **UI**: Add configurable sidebar apps with custom icons plus inline or new-tab launch modes
|
||||||
|
- **Branding**: Add runtime branding options for custom favicon, sidebar logos, and login logos
|
||||||
|
- **Deployment**: Add configurable server listen address support via `HOSTNAME`, including IPv6 and dual-stack guidance
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Calendar**: Improve all-day event handling
|
||||||
|
- **Calendar**: Validate and default persisted calendar view mode values
|
||||||
|
- **UI**: Use configured app names more consistently in metadata and login branding surfaces
|
||||||
|
- **Docker**: Correct `HOSTNAME` formatting in the Docker Compose example
|
||||||
|
- **Metadata**: Correct package author and container vendor metadata
|
||||||
|
|
||||||
## 1.3.0 (2026-03-16)
|
## 1.3.0 (2026-03-16)
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@ LABEL org.opencontainers.image.description="Modern webmail client built with Nex
|
|||||||
LABEL org.opencontainers.image.source="https://github.com/bulwarkmail/webmail"
|
LABEL org.opencontainers.image.source="https://github.com/bulwarkmail/webmail"
|
||||||
LABEL org.opencontainers.image.url="https://github.com/bulwarkmail/webmail"
|
LABEL org.opencontainers.image.url="https://github.com/bulwarkmail/webmail"
|
||||||
LABEL org.opencontainers.image.licenses="AGPL-3.0-only"
|
LABEL org.opencontainers.image.licenses="AGPL-3.0-only"
|
||||||
LABEL org.opencontainers.image.vendor="root.cloud"
|
LABEL org.opencontainers.image.vendor="rbm.systems"
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.ar
|
|||||||
Built with Next.js and the JMAP protocol.
|
Built with Next.js and the JMAP protocol.
|
||||||
|
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](CHANGELOG.md)
|
[](CHANGELOG.md)
|
||||||
[](https://ghcr.io/bulwarkmail/webmail)
|
[](https://ghcr.io/bulwarkmail/webmail)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
@@ -99,12 +99,14 @@ Built with Next.js and the JMAP protocol.
|
|||||||
- **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
|
||||||
- **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
|
||||||
|
- **TNEF support** — extract Outlook `winmail.dat` message bodies and attachments automatically
|
||||||
- **Folder management** — create, rename, delete folders with icon picker and subfolder support
|
- **Folder management** — create, rename, delete folders with icon picker and subfolder support
|
||||||
- **Tag counts** — unread and total counts displayed in sidebar
|
- **Tag counts** — unread and total counts displayed in sidebar
|
||||||
|
|
||||||
@@ -151,6 +153,7 @@ Built with Next.js and the JMAP protocol.
|
|||||||
|
|
||||||
- **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
|
||||||
- **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**
|
||||||
@@ -163,12 +166,13 @@ Built with Next.js and the JMAP protocol.
|
|||||||
|
|
||||||
- **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
|
||||||
|
- **Always-light email rendering** option for problematic HTML messages in dark theme
|
||||||
- **Responsive** — desktop sidebar + mobile bottom tab bar with tablet support
|
- **Responsive** — desktop sidebar + mobile bottom tab bar with tablet support
|
||||||
- **Keyboard shortcuts** — full navigation without a mouse
|
- **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
|
||||||
- **Customizable toolbar** position and login page branding
|
- **Customizable toolbar** position, custom favicon, sidebar/login logos, and login page branding
|
||||||
- **Configurable logo** with light/dark mode variants
|
- **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
|
||||||
@@ -183,6 +187,7 @@ Automatic browser detection with persistent preference.
|
|||||||
### Identity Management
|
### Identity Management
|
||||||
|
|
||||||
- **Multiple sender identities** with per-identity signatures
|
- **Multiple sender identities** with per-identity signatures
|
||||||
|
- **Identity refresh** — keep the identity manager aligned with server-side changes after edits
|
||||||
- **Sub-addressing** — `user+tag@domain.com` with contextual tag suggestions
|
- **Sub-addressing** — `user+tag@domain.com` with contextual tag suggestions
|
||||||
- **Identity badges** in viewer and email list
|
- **Identity badges** in viewer and email list
|
||||||
|
|
||||||
@@ -243,6 +248,16 @@ 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>
|
||||||
|
<summary>Server Listen Address</summary>
|
||||||
|
|
||||||
|
```env
|
||||||
|
HOSTNAME=0.0.0.0 # Default; use "::" for IPv6
|
||||||
|
PORT=3000 # Default listen port
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>OAuth2/OIDC (SSO)</summary>
|
<summary>OAuth2/OIDC (SSO)</summary>
|
||||||
|
|
||||||
|
|||||||
-301
@@ -1,301 +0,0 @@
|
|||||||
<div align="center">
|
|
||||||
|
|
||||||
<picture>
|
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="public/branding/Bulwark%20Logo%20with%20Lettering%20White%20and%20Color.svg" />
|
|
||||||
<source media="(prefers-color-scheme: light)" srcset="public/branding/Bulwark%20Logo%20with%20Lettering%20Dark%20Color.svg" />
|
|
||||||
<img src="public/branding/Bulwark%20Logo%20with%20Lettering%20Dark%20Color.svg" alt="Bulwark Webmail" width="220" />
|
|
||||||
</picture>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
# Bulwark Webmail - Roadmap
|
|
||||||
|
|
||||||
This document tracks the development status and planned features for Bulwark Webmail.
|
|
||||||
|
|
||||||
## Completed Features
|
|
||||||
|
|
||||||
### Core Infrastructure
|
|
||||||
|
|
||||||
- [x] Next.js 16 with TypeScript and App Router
|
|
||||||
- [x] Tailwind CSS v4 with Oxide engine
|
|
||||||
- [x] Zustand state management
|
|
||||||
- [x] Custom JMAP client implementation (RFC 8620)
|
|
||||||
|
|
||||||
### Authentication
|
|
||||||
|
|
||||||
- [x] Login with JMAP server authentication
|
|
||||||
- [x] Session management (no password storage for security)
|
|
||||||
- [x] Username autocomplete with history
|
|
||||||
- [x] Logout functionality
|
|
||||||
- [x] Authentication error handling
|
|
||||||
- [x] JMAP identities for sender address
|
|
||||||
- [x] TOTP two-factor authentication (Stalwart-compatible)
|
|
||||||
- [x] OAuth2/OIDC with PKCE (opt-in SSO, session persistence, RP-initiated logout)
|
|
||||||
- [x] External IdP support via explicit issuer URL (Keycloak, Authentik, etc.)
|
|
||||||
- [x] "Remember me" session persistence for Basic Auth (AES-256-GCM encrypted httpOnly cookie)
|
|
||||||
|
|
||||||
### JMAP Server Connection
|
|
||||||
|
|
||||||
- [x] Session establishment and keep-alive
|
|
||||||
- [x] Connection error handling and retries
|
|
||||||
- [x] CORS error detection with actionable user guidance
|
|
||||||
- [x] Session URL origin rewriting (fixes Docker/reverse proxy deployments where server returns internal hostname)
|
|
||||||
- [x] Storage quota display
|
|
||||||
- [x] Server capability detection
|
|
||||||
- [x] Shared folders support (multi-account access)
|
|
||||||
|
|
||||||
### Email Operations
|
|
||||||
|
|
||||||
- [x] Email fetching and display
|
|
||||||
- [x] Full HTML email rendering
|
|
||||||
- [x] Compose, reply, reply-all, forward
|
|
||||||
- [x] Draft auto-save with discard confirmation
|
|
||||||
- [x] Mark as read/unread
|
|
||||||
- [x] Star/unstar emails
|
|
||||||
- [x] Delete and archive
|
|
||||||
- [x] Color tags/labels
|
|
||||||
- [x] Full-text search
|
|
||||||
- [x] Advanced search with JMAP filter panel, search chips, and cross-mailbox queries
|
|
||||||
- [x] Attachment upload and download
|
|
||||||
- [x] Batch operations (multi-select)
|
|
||||||
- [x] Quick reply form
|
|
||||||
- [x] Email threading (Gmail-style inline expansion)
|
|
||||||
|
|
||||||
### Real-time Updates
|
|
||||||
|
|
||||||
- [x] EventSource for JMAP push notifications
|
|
||||||
- [x] State synchronization
|
|
||||||
- [x] Email arrival notifications
|
|
||||||
- [x] Real-time unread counts
|
|
||||||
- [x] Mailbox change handling
|
|
||||||
|
|
||||||
### User Interface
|
|
||||||
|
|
||||||
- [x] Three-pane layout (sidebar, list, viewer)
|
|
||||||
- [x] Minimalist design system
|
|
||||||
- [x] Dark and light theme support
|
|
||||||
- [x] Custom scrollbars
|
|
||||||
- [x] Mobile responsive design
|
|
||||||
- [x] Keyboard shortcuts
|
|
||||||
- [x] Drag-and-drop email organization
|
|
||||||
- [x] Right-click context menus
|
|
||||||
- [x] Hierarchical mailbox display
|
|
||||||
- [x] Email list with avatars and visual hierarchy
|
|
||||||
- [x] Expandable email headers
|
|
||||||
- [x] External content warning banner
|
|
||||||
- [x] SPF/DKIM/DMARC status indicators
|
|
||||||
- [x] Loading states and skeletons
|
|
||||||
- [x] Smooth transitions and animations
|
|
||||||
- [x] Infinite scroll pagination
|
|
||||||
- [x] Virtual scrolling for large email lists
|
|
||||||
- [x] Error boundaries
|
|
||||||
- [x] Settings page with preferences
|
|
||||||
- [x] Navigation rail (desktop vertical icon sidebar + mobile bottom tab bar)
|
|
||||||
- [x] Welcome banner for first-time users (one-time display, localStorage persistence)
|
|
||||||
- [x] Confirmation dialog component with promise-based useConfirmDialog hook
|
|
||||||
- [x] Toast notifications with undo action support and typed durations
|
|
||||||
- [x] Inline form validation with shake animation (email composer, contact form)
|
|
||||||
- [x] Login UX polish (error shake, discreet 2FA toggle, password visibility toggle, session expired banner)
|
|
||||||
- [x] Empty state patterns for contacts (distinct "no data" vs "no search results" with contextual actions)
|
|
||||||
- [x] WCAG AA reduced-motion media query (global animation/transition reset)
|
|
||||||
- [x] Safe area inset utilities for notched devices
|
|
||||||
- [x] Screen reader live region announcements (sr-only)
|
|
||||||
|
|
||||||
### Internationalization
|
|
||||||
|
|
||||||
- [x] English language support
|
|
||||||
- [x] French language support
|
|
||||||
- [x] Japanese language support
|
|
||||||
- [x] Spanish language support
|
|
||||||
- [x] Italian language support
|
|
||||||
- [x] German language support
|
|
||||||
- [x] Dutch language support
|
|
||||||
- [x] Portuguese language support
|
|
||||||
- [x] Automatic browser language detection
|
|
||||||
- [x] Language preference persistence
|
|
||||||
|
|
||||||
### Security & Accessibility
|
|
||||||
|
|
||||||
- [x] External content blocked by default
|
|
||||||
- [x] HTML sanitization with DOMPurify
|
|
||||||
- [x] User control for loading external content
|
|
||||||
- [x] Trusted senders list for automatic image loading
|
|
||||||
- [x] Dark mode email readability (intelligent color transformation)
|
|
||||||
- [x] WCAG 2.0 Level AA color contrast compliance
|
|
||||||
- [x] Newsletter unsubscribe support (RFC 2369)
|
|
||||||
- [x] XSS attack prevention with comprehensive validation
|
|
||||||
- [x] CSP Report-Only headers with per-request nonce
|
|
||||||
- [x] Security headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy)
|
|
||||||
- [x] Reusable focus trap hook (Tab cycling, Escape handling, focus restore)
|
|
||||||
- [x] WCAG AA prefers-reduced-motion support (global animation/transition reset)
|
|
||||||
- [x] Safe area insets for notched mobile devices
|
|
||||||
- [x] Screen reader sr-only live region for dynamic announcements
|
|
||||||
|
|
||||||
### Identity Management
|
|
||||||
|
|
||||||
- [x] Multiple sender identities (name, email, signature)
|
|
||||||
- [x] Sub-addressing support (user+tag@domain.com)
|
|
||||||
- [x] Per-identity signatures
|
|
||||||
- [x] Identity badges in email viewer and list
|
|
||||||
- [x] Tag suggestions based on context
|
|
||||||
- [x] Display name included in From header (recipients see name, not just email)
|
|
||||||
- [x] Primary identity (matching login) selected by default in composer
|
|
||||||
|
|
||||||
### Address Book & Contacts
|
|
||||||
|
|
||||||
- [x] Contact store with JMAP sync and local fallback
|
|
||||||
- [x] Contact CRUD operations (create, read, update, delete)
|
|
||||||
- [x] Contacts list view with search/filter
|
|
||||||
- [x] Contact details view/edit form
|
|
||||||
- [x] JMAP contacts sync (RFC 9553/9610 ContactCard/AddressBook)
|
|
||||||
- [x] Email autocomplete from contacts
|
|
||||||
- [x] Contacts integration in email composer (To/Cc/Bcc)
|
|
||||||
- [x] Contact groups/lists management with JMAP members map
|
|
||||||
- [x] vCard import/export (RFC 6350 parser/generator, duplicate detection)
|
|
||||||
- [x] Bulk contact operations (multi-select, delete, group add, export)
|
|
||||||
- [x] i18n support for contacts (all 8 languages)
|
|
||||||
|
|
||||||
### Vacation Responder
|
|
||||||
|
|
||||||
- [x] JMAP VacationResponse singleton management
|
|
||||||
- [x] Settings tab with date range and message configuration
|
|
||||||
- [x] Sidebar indicator when vacation auto-reply is active
|
|
||||||
- [x] i18n support (all 8 languages)
|
|
||||||
|
|
||||||
### Calendar Integration
|
|
||||||
|
|
||||||
- [x] JMAP Calendar types (RFC 8984) and client methods
|
|
||||||
- [x] Calendar capability detection (urn:ietf:params:jmap:calendars)
|
|
||||||
- [x] Calendar store with Zustand (persist middleware)
|
|
||||||
- [x] Month, week, day, and agenda views
|
|
||||||
- [x] Event modal (create/edit/delete with recurrence, reminders)
|
|
||||||
- [x] Mini-calendar sidebar with calendar visibility toggles
|
|
||||||
- [x] Calendar settings (default view, week start, time format)
|
|
||||||
- [x] Multi-day event spanning across all covered days
|
|
||||||
- [x] Column-based overlap layout for concurrent events
|
|
||||||
- [x] Locale-aware date formatting via next-intl
|
|
||||||
- [x] First day of week and time format settings wired to views
|
|
||||||
- [x] Push notification handling for calendar state changes
|
|
||||||
- [x] Calendar page capability check (redirect if unsupported)
|
|
||||||
- [x] Error handling with toast feedback on event CRUD
|
|
||||||
- [x] Timezone auto-detection on event creation
|
|
||||||
- [x] Input validation, color sanitization, focus trap
|
|
||||||
- [x] ARIA grid roles and event card accessible labels
|
|
||||||
- [x] Mobile touch targets (44px minimum)
|
|
||||||
- [x] Calendar keyboard shortcuts (m/w/d/a views, t today, n new event)
|
|
||||||
- [x] i18n support with ICU pluralization (all 8 languages)
|
|
||||||
- [x] Drag-and-drop event rescheduling (week/day time snap, month date move)
|
|
||||||
- [x] iCalendar (.ics) file import via CalendarEvent/parse with preview and bulk create
|
|
||||||
- [x] Event notifications with client-side alert evaluation and toast display
|
|
||||||
- [x] Notification sound, acknowledged alert persistence (localStorage), proactive 24h event fetch
|
|
||||||
- [x] Configurable notification settings (enable/disable, sound toggle)
|
|
||||||
- [x] Participant scheduling with iTIP invitations (organizer/attendee UI, RSVP buttons, contact autocomplete)
|
|
||||||
- [x] Inline calendar invitation banner in email viewer (auto-detect .ics attachments, RSVP, import to calendar, cancellation display)
|
|
||||||
- [x] Scheduling message support (sendSchedulingMessages flag for create/update/delete)
|
|
||||||
- [x] Click-drag to create events (pointer-based time range selection, 15-min snap, visual overlay)
|
|
||||||
- [x] Event resize by dragging bottom edge handle (15-min snap, optimistic JMAP update)
|
|
||||||
- [x] Recurring event edit/delete scope dialog (this event / this and following / all events)
|
|
||||||
- [x] Double-click quick event creation (inline title input, PT1H default)
|
|
||||||
- [x] Event duplication button in modal (clones event +1 day, opens for editing)
|
|
||||||
|
|
||||||
### Email Filters
|
|
||||||
|
|
||||||
- [x] JMAP Sieve Scripts (RFC 9661) with capability detection
|
|
||||||
- [x] Visual rule builder (conditions: From/To/Cc/Subject/Header/Size/Body, actions: Move/Copy/Forward/Mark read/Star/Label/Discard/Reject/Keep/Stop)
|
|
||||||
- [x] Raw Sieve script editor with syntax validation
|
|
||||||
- [x] Sieve generator and parser with JSON metadata round-trip
|
|
||||||
- [x] Filter store with CRUD, reorder, toggle, auto-save with rollback
|
|
||||||
- [x] Opaque script detection with reset to visual builder option
|
|
||||||
- [x] Focus trap accessibility in modals
|
|
||||||
- [x] Toast validation feedback for empty rules
|
|
||||||
- [x] Push notification handling for SieveScript state changes
|
|
||||||
- [x] i18n support (all 8 languages)
|
|
||||||
|
|
||||||
### Email Templates
|
|
||||||
|
|
||||||
- [x] Reusable email templates with local storage persistence
|
|
||||||
- [x] Category organization (General, Business, Personal, Support, Follow-up, custom)
|
|
||||||
- [x] Dynamic placeholder variables with auto-fill from composer context
|
|
||||||
- [x] Template manager modal (create, edit, duplicate, delete)
|
|
||||||
- [x] Template picker in composer toolbar with search and category filter
|
|
||||||
- [x] Custom placeholder prompt on template insertion
|
|
||||||
- [x] Settings tab for template management
|
|
||||||
- [x] Keyboard shortcut (Ctrl+Shift+T to insert template)
|
|
||||||
- [x] i18n support (all 8 languages)
|
|
||||||
|
|
||||||
### Email Display
|
|
||||||
|
|
||||||
- [x] Proper email layout without horizontal scroll or clipping
|
|
||||||
- [x] Blocked image container collapsing (no empty spaces in newsletters)
|
|
||||||
|
|
||||||
### Testing
|
|
||||||
|
|
||||||
- [x] Unit tests for validation utilities (57 tests)
|
|
||||||
- [x] Unit tests for email sanitization (27 tests)
|
|
||||||
- [x] Unit tests for color transformation (40 tests)
|
|
||||||
- [x] Unit tests for contact store (56 tests)
|
|
||||||
- [x] Unit tests for JMAP contact client (41 tests)
|
|
||||||
- [x] Unit tests for vCard parser (18 tests)
|
|
||||||
- [x] Unit tests for thread utilities (20 tests)
|
|
||||||
- [x] Unit tests for email headers (39 tests)
|
|
||||||
- [x] Component tests (contacts, UI components — 41 tests)
|
|
||||||
- [x] JMAP client method tests (identity: 20, contacts: 41)
|
|
||||||
- [x] Unit tests for Sieve generator (50 tests)
|
|
||||||
- [x] Unit tests for Sieve parser (14 tests)
|
|
||||||
- [x] Unit tests for calendar alerts (36 tests)
|
|
||||||
- [x] Unit tests for calendar notification store (8 tests)
|
|
||||||
- [x] Unit tests for calendar invitation parsing (25 tests)
|
|
||||||
- [x] Unit tests for calendar participants (26 tests)
|
|
||||||
- [x] Unit tests for template utilities (48 tests)
|
|
||||||
- [x] Unit tests for OAuth PKCE and discovery (14 tests)
|
|
||||||
- [x] XSS attack vector testing
|
|
||||||
- [x] Playwright E2E framework setup
|
|
||||||
|
|
||||||
### Deployment
|
|
||||||
|
|
||||||
- [x] Runtime environment variables (Docker-friendly configuration)
|
|
||||||
- [x] Health check endpoint
|
|
||||||
- [x] Docker support (multi-stage build, docker-compose, standalone output)
|
|
||||||
- [x] Structured server-side logger (text/JSON format, configurable level)
|
|
||||||
- [x] Pre-built Docker image on [Docker Hub](https://hub.docker.com/r/bulwarkmail/webmail) and [GHCR](https://ghcr.io/bulwarkmail/webmail) with multi-arch support (amd64/arm64)
|
|
||||||
- [x] GitHub Actions CI/CD for automated image publishing on releases
|
|
||||||
- [x] CVE remediation: remove npm from production image, upgrade Alpine packages
|
|
||||||
- [x] Server-side update check (logs newer version availability on startup)
|
|
||||||
|
|
||||||
## Planned Features
|
|
||||||
|
|
||||||
### Advanced Features
|
|
||||||
|
|
||||||
- [ ] Free/busy queries (Principal/getAvailability)
|
|
||||||
- [ ] Calendar sharing UI (JMAP Sharing RFC 9670)
|
|
||||||
- [ ] Email encryption (PGP/GPG)
|
|
||||||
|
|
||||||
### Performance Optimizations
|
|
||||||
|
|
||||||
- [ ] Email content caching
|
|
||||||
- [ ] Bundle size optimization
|
|
||||||
- [ ] Service worker for offline support
|
|
||||||
- [ ] Lazy loading for attachments
|
|
||||||
|
|
||||||
### Testing (Remaining)
|
|
||||||
|
|
||||||
- [ ] E2E tests with real JMAP server
|
|
||||||
- [ ] Accessibility testing
|
|
||||||
- [ ] Performance testing
|
|
||||||
|
|
||||||
### Deployment
|
|
||||||
|
|
||||||
- [ ] Production build optimizations
|
|
||||||
- [ ] Monitoring and logging
|
|
||||||
|
|
||||||
### Security Enhancements
|
|
||||||
|
|
||||||
- [ ] Rate limiting
|
|
||||||
|
|
||||||
## Known Issues
|
|
||||||
|
|
||||||
- [ ] Next.js workspace root warning (cosmetic)
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
Want to help implement a feature? Check out our [CONTRIBUTING.md](CONTRIBUTING.md) guide!
|
|
||||||
@@ -53,6 +53,7 @@ function OAuthCallbackInner() {
|
|||||||
sessionStorage.removeItem("oauth_state");
|
sessionStorage.removeItem("oauth_state");
|
||||||
sessionStorage.removeItem("oauth_code_verifier");
|
sessionStorage.removeItem("oauth_code_verifier");
|
||||||
sessionStorage.removeItem("oauth_server_url");
|
sessionStorage.removeItem("oauth_server_url");
|
||||||
|
sessionStorage.removeItem("oauth_add_account_mode");
|
||||||
let redirectTo = `/${params.locale}`;
|
let redirectTo = `/${params.locale}`;
|
||||||
try {
|
try {
|
||||||
const saved = sessionStorage.getItem('redirect_after_login');
|
const saved = sessionStorage.getItem('redirect_after_login');
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
format, parseISO,
|
format, parseISO,
|
||||||
} from "date-fns";
|
} from "date-fns";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
|
import { isCalendarViewMode } from "@/stores/calendar-store";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { useSettingsStore } from "@/stores/settings-store";
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
@@ -30,6 +31,9 @@ import { ICalImportModal } from "@/components/calendar/ical-import-modal";
|
|||||||
import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal";
|
import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal";
|
||||||
import { RecurrenceScopeDialog, type RecurrenceEditScope } from "@/components/calendar/recurrence-scope-dialog";
|
import { RecurrenceScopeDialog, type RecurrenceEditScope } from "@/components/calendar/recurrence-scope-dialog";
|
||||||
import { NavigationRail } from "@/components/layout/navigation-rail";
|
import { NavigationRail } from "@/components/layout/navigation-rail";
|
||||||
|
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
|
||||||
|
import { InlineAppView } from "@/components/layout/inline-app-view";
|
||||||
|
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
|
||||||
import { ResizeHandle } from "@/components/layout/resize-handle";
|
import { ResizeHandle } from "@/components/layout/resize-handle";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
|
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
|
||||||
@@ -48,6 +52,7 @@ export default function CalendarPage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
|
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
||||||
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
||||||
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
||||||
const { quota, isPushConnected } = useEmailStore();
|
const { quota, isPushConnected } = useEmailStore();
|
||||||
@@ -60,6 +65,7 @@ export default function CalendarPage() {
|
|||||||
} = useCalendarStore();
|
} = useCalendarStore();
|
||||||
const { firstDayOfWeek, timeFormat } = useSettingsStore();
|
const { firstDayOfWeek, timeFormat } = useSettingsStore();
|
||||||
const { identities } = useIdentityStore();
|
const { identities } = useIdentityStore();
|
||||||
|
const normalizedViewMode = isCalendarViewMode(viewMode) ? viewMode : "month";
|
||||||
|
|
||||||
const currentUserEmails = useMemo(() =>
|
const currentUserEmails = useMemo(() =>
|
||||||
identities.map(id => id.email).filter(Boolean),
|
identities.map(id => id.email).filter(Boolean),
|
||||||
@@ -129,7 +135,7 @@ export default function CalendarPage() {
|
|||||||
|
|
||||||
const dateRange = useMemo(() => {
|
const dateRange = useMemo(() => {
|
||||||
const d = selectedDate;
|
const d = selectedDate;
|
||||||
switch (viewMode) {
|
switch (normalizedViewMode) {
|
||||||
case "month": {
|
case "month": {
|
||||||
const ms = startOfMonth(d);
|
const ms = startOfMonth(d);
|
||||||
const me = endOfMonth(d);
|
const me = endOfMonth(d);
|
||||||
@@ -156,17 +162,17 @@ export default function CalendarPage() {
|
|||||||
end: format(addDays(d, 30), "yyyy-MM-dd'T'23:59:59"),
|
end: format(addDays(d, 30), "yyyy-MM-dd'T'23:59:59"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}, [selectedDate, viewMode, firstDayOfWeek]);
|
}, [selectedDate, normalizedViewMode, firstDayOfWeek]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (client && calendars.length > 0) {
|
if (client && calendars.length > 0 && dateRange) {
|
||||||
fetchEvents(client, dateRange.start, dateRange.end);
|
fetchEvents(client, dateRange.start, dateRange.end);
|
||||||
}
|
}
|
||||||
}, [client, calendars.length, dateRange, fetchEvents]);
|
}, [client, calendars.length, dateRange, fetchEvents]);
|
||||||
|
|
||||||
const navigatePrev = useCallback(() => {
|
const navigatePrev = useCallback(() => {
|
||||||
let next: Date;
|
let next: Date;
|
||||||
switch (viewMode) {
|
switch (normalizedViewMode) {
|
||||||
case "month": next = subMonths(selectedDate, 1); break;
|
case "month": next = subMonths(selectedDate, 1); break;
|
||||||
case "week": next = subWeeks(selectedDate, 1); break;
|
case "week": next = subWeeks(selectedDate, 1); break;
|
||||||
case "day": next = subDays(selectedDate, 1); break;
|
case "day": next = subDays(selectedDate, 1); break;
|
||||||
@@ -174,11 +180,11 @@ export default function CalendarPage() {
|
|||||||
}
|
}
|
||||||
setSelectedDate(next);
|
setSelectedDate(next);
|
||||||
setMiniMonth(next);
|
setMiniMonth(next);
|
||||||
}, [viewMode, selectedDate, setSelectedDate]);
|
}, [normalizedViewMode, selectedDate, setSelectedDate]);
|
||||||
|
|
||||||
const navigateNext = useCallback(() => {
|
const navigateNext = useCallback(() => {
|
||||||
let next: Date;
|
let next: Date;
|
||||||
switch (viewMode) {
|
switch (normalizedViewMode) {
|
||||||
case "month": next = addMonths(selectedDate, 1); break;
|
case "month": next = addMonths(selectedDate, 1); break;
|
||||||
case "week": next = addWeeks(selectedDate, 1); break;
|
case "week": next = addWeeks(selectedDate, 1); break;
|
||||||
case "day": next = addDays(selectedDate, 1); break;
|
case "day": next = addDays(selectedDate, 1); break;
|
||||||
@@ -186,7 +192,7 @@ export default function CalendarPage() {
|
|||||||
}
|
}
|
||||||
setSelectedDate(next);
|
setSelectedDate(next);
|
||||||
setMiniMonth(next);
|
setMiniMonth(next);
|
||||||
}, [viewMode, selectedDate, setSelectedDate]);
|
}, [normalizedViewMode, selectedDate, setSelectedDate]);
|
||||||
|
|
||||||
const goToToday = useCallback(() => {
|
const goToToday = useCallback(() => {
|
||||||
setSelectedDate(new Date());
|
setSelectedDate(new Date());
|
||||||
@@ -218,10 +224,10 @@ export default function CalendarPage() {
|
|||||||
setSelectedDate(date);
|
setSelectedDate(date);
|
||||||
setMiniMonth(date);
|
setMiniMonth(date);
|
||||||
// On mobile month view, tapping a date switches to day view
|
// On mobile month view, tapping a date switches to day view
|
||||||
if (isMobile && viewMode === "month") {
|
if (isMobile && normalizedViewMode === "month") {
|
||||||
setViewMode("day");
|
setViewMode("day");
|
||||||
}
|
}
|
||||||
}, [setSelectedDate, isMobile, viewMode, setViewMode]);
|
}, [setSelectedDate, isMobile, normalizedViewMode, setViewMode]);
|
||||||
|
|
||||||
const handleMiniMonthChange = useCallback((date: Date) => {
|
const handleMiniMonthChange = useCallback((date: Date) => {
|
||||||
setMiniMonth(date);
|
setMiniMonth(date);
|
||||||
@@ -230,10 +236,12 @@ export default function CalendarPage() {
|
|||||||
|
|
||||||
const openCreateModal = useCallback((date?: Date, endDate?: Date) => {
|
const openCreateModal = useCallback((date?: Date, endDate?: Date) => {
|
||||||
setEditEvent(null);
|
setEditEvent(null);
|
||||||
setDefaultModalDate(date || selectedDate);
|
const d = date || selectedDate;
|
||||||
|
setDefaultModalDate(d);
|
||||||
setDefaultModalEndDate(endDate);
|
setDefaultModalEndDate(endDate);
|
||||||
|
setSelectedDate(d);
|
||||||
setShowEventModal(true);
|
setShowEventModal(true);
|
||||||
}, [selectedDate]);
|
}, [selectedDate, setSelectedDate]);
|
||||||
|
|
||||||
const openEditModal = useCallback((event: CalendarEvent) => {
|
const openEditModal = useCallback((event: CalendarEvent) => {
|
||||||
setEditEvent(event);
|
setEditEvent(event);
|
||||||
@@ -603,6 +611,7 @@ export default function CalendarPage() {
|
|||||||
|
|
||||||
const visibleEvents = useMemo(() =>
|
const visibleEvents = useMemo(() =>
|
||||||
events.filter((e) => {
|
events.filter((e) => {
|
||||||
|
if (!e.calendarIds) return false;
|
||||||
const calIds = Object.keys(e.calendarIds);
|
const calIds = Object.keys(e.calendarIds);
|
||||||
return calIds.some((id) => selectedCalendarIds.includes(id));
|
return calIds.some((id) => selectedCalendarIds.includes(id));
|
||||||
}),
|
}),
|
||||||
@@ -621,7 +630,7 @@ export default function CalendarPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const viewContent = (() => {
|
const viewContent = (() => {
|
||||||
switch (viewMode) {
|
switch (normalizedViewMode) {
|
||||||
case "month":
|
case "month":
|
||||||
return (
|
return (
|
||||||
<CalendarMonthView
|
<CalendarMonthView
|
||||||
@@ -632,6 +641,7 @@ export default function CalendarPage() {
|
|||||||
onSelectEvent={handleSelectEvent}
|
onSelectEvent={handleSelectEvent}
|
||||||
onHoverEvent={handleHoverEvent}
|
onHoverEvent={handleHoverEvent}
|
||||||
onHoverLeave={handleHoverLeave}
|
onHoverLeave={handleHoverLeave}
|
||||||
|
onCreateAtTime={openCreateModal}
|
||||||
firstDayOfWeek={firstDayOfWeek}
|
firstDayOfWeek={firstDayOfWeek}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
/>
|
/>
|
||||||
@@ -684,7 +694,7 @@ export default function CalendarPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="relative flex-1 flex flex-col overflow-hidden">
|
<div className="relative flex-1 flex flex-col overflow-hidden">
|
||||||
{viewContent}
|
{viewContent}
|
||||||
{isLoadingEvents && calendars.length > 0 && (
|
{isLoadingEvents && calendars.length > 0 && events.length === 0 && (
|
||||||
<div className="absolute inset-0 bg-background/50 flex items-center justify-center pointer-events-none">
|
<div className="absolute inset-0 bg-background/50 flex items-center justify-center pointer-events-none">
|
||||||
<div className="h-5 w-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
|
<div className="h-5 w-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
|
||||||
</div>
|
</div>
|
||||||
@@ -702,13 +712,21 @@ export default function CalendarPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); router.push('/login'); }}
|
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{inlineApp && (
|
||||||
|
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Sidebar - full height */}
|
{/* Sidebar - full height */}
|
||||||
{!isMobile && (
|
{!isMobile && !inlineApp && (
|
||||||
<>
|
<>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -748,10 +766,11 @@ export default function CalendarPage() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!inlineApp && (
|
||||||
<div className="flex flex-col flex-1 min-w-0">
|
<div className="flex flex-col flex-1 min-w-0">
|
||||||
<CalendarToolbar
|
<CalendarToolbar
|
||||||
selectedDate={selectedDate}
|
selectedDate={selectedDate}
|
||||||
viewMode={viewMode}
|
viewMode={normalizedViewMode}
|
||||||
onPrev={navigatePrev}
|
onPrev={navigatePrev}
|
||||||
onNext={navigateNext}
|
onNext={navigateNext}
|
||||||
onToday={goToToday}
|
onToday={goToToday}
|
||||||
@@ -776,6 +795,7 @@ export default function CalendarPage() {
|
|||||||
{!isMobile && showEventModal && (
|
{!isMobile && showEventModal && (
|
||||||
<div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden">
|
<div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden">
|
||||||
<EventModal
|
<EventModal
|
||||||
|
key={editEvent?.id ?? 'new'}
|
||||||
event={editEvent}
|
event={editEvent}
|
||||||
calendars={calendars}
|
calendars={calendars}
|
||||||
defaultDate={defaultModalDate}
|
defaultDate={defaultModalDate}
|
||||||
@@ -802,12 +822,19 @@ export default function CalendarPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mobile Bottom Navigation */}
|
|
||||||
{isMobile && (
|
|
||||||
<NavigationRail orientation="horizontal" />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Mobile Bottom Navigation */}
|
||||||
|
{isMobile && (
|
||||||
|
<NavigationRail
|
||||||
|
orientation="horizontal"
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{detailEvent && detailAnchorRect && (
|
{detailEvent && detailAnchorRect && (
|
||||||
<EventDetailPopover
|
<EventDetailPopover
|
||||||
@@ -830,6 +857,7 @@ export default function CalendarPage() {
|
|||||||
|
|
||||||
{showEventModal && isMobile && (
|
{showEventModal && isMobile && (
|
||||||
<EventModal
|
<EventModal
|
||||||
|
key={editEvent?.id ?? 'new'}
|
||||||
event={editEvent}
|
event={editEvent}
|
||||||
calendars={calendars}
|
calendars={calendars}
|
||||||
defaultDate={defaultModalDate}
|
defaultDate={defaultModalDate}
|
||||||
@@ -859,6 +887,7 @@ export default function CalendarPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
<RecurrenceScopeDialog
|
<RecurrenceScopeDialog
|
||||||
isOpen={!!pendingScopeAction}
|
isOpen={!!pendingScopeAction}
|
||||||
actionType={pendingScopeAction?.type || "edit"}
|
actionType={pendingScopeAction?.type || "edit"}
|
||||||
|
|||||||
+119
-12
@@ -13,6 +13,7 @@ import { ContactForm } from "@/components/contacts/contact-form";
|
|||||||
import { ContactGroupForm } from "@/components/contacts/contact-group-form";
|
import { ContactGroupForm } from "@/components/contacts/contact-group-form";
|
||||||
import { ContactGroupDetail } from "@/components/contacts/contact-group-detail";
|
import { ContactGroupDetail } from "@/components/contacts/contact-group-detail";
|
||||||
import { ContactsSidebar, type ContactCategory } from "@/components/contacts/contacts-sidebar";
|
import { ContactsSidebar, type ContactCategory } from "@/components/contacts/contacts-sidebar";
|
||||||
|
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
|
||||||
import { exportContacts } from "@/components/contacts/contact-export";
|
import { exportContacts } from "@/components/contacts/contact-export";
|
||||||
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
|
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
@@ -20,9 +21,12 @@ import { useEmailStore } from "@/stores/email-store";
|
|||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { NavigationRail } from "@/components/layout/navigation-rail";
|
import { NavigationRail } from "@/components/layout/navigation-rail";
|
||||||
|
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
|
||||||
|
import { InlineAppView } from "@/components/layout/inline-app-view";
|
||||||
|
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
|
||||||
import { ResizeHandle } from "@/components/layout/resize-handle";
|
import { ResizeHandle } from "@/components/layout/resize-handle";
|
||||||
import { useIsMobile } from "@/hooks/use-media-query";
|
import { useIsMobile } from "@/hooks/use-media-query";
|
||||||
import type { ContactCard } from "@/lib/jmap/types";
|
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
|
||||||
|
|
||||||
type View =
|
type View =
|
||||||
| "list"
|
| "list"
|
||||||
@@ -38,10 +42,12 @@ export default function ContactsPage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations("contacts");
|
const t = useTranslations("contacts");
|
||||||
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
||||||
|
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
||||||
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
||||||
const { quota, isPushConnected } = useEmailStore();
|
const { quota, isPushConnected } = useEmailStore();
|
||||||
const {
|
const {
|
||||||
contacts,
|
contacts,
|
||||||
|
addressBooks,
|
||||||
selectedContactId,
|
selectedContactId,
|
||||||
searchQuery,
|
searchQuery,
|
||||||
supportsSync,
|
supportsSync,
|
||||||
@@ -67,10 +73,13 @@ export default function ContactsPage() {
|
|||||||
clearSelection,
|
clearSelection,
|
||||||
bulkDeleteContacts,
|
bulkDeleteContacts,
|
||||||
bulkAddToGroup,
|
bulkAddToGroup,
|
||||||
|
moveContactToAddressBook,
|
||||||
|
importContacts,
|
||||||
} = useContactStore();
|
} = useContactStore();
|
||||||
|
|
||||||
const [view, setView] = useState<View>("list");
|
const [view, setView] = useState<View>("list");
|
||||||
const [activeCategory, setActiveCategory] = useState<ContactCategory>("all");
|
const [activeCategory, setActiveCategory] = useState<ContactCategory>("all");
|
||||||
|
const [showImportDialog, setShowImportDialog] = useState(false);
|
||||||
const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null);
|
const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null);
|
||||||
const hasFetched = useRef(false);
|
const hasFetched = useRef(false);
|
||||||
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
||||||
@@ -78,10 +87,10 @@ export default function ContactsPage() {
|
|||||||
|
|
||||||
// Panel resize state - sidebar (categories)
|
// Panel resize state - sidebar (categories)
|
||||||
const [sidebarWidth, setSidebarWidth] = useState(() => {
|
const [sidebarWidth, setSidebarWidth] = useState(() => {
|
||||||
try { const v = localStorage.getItem("contacts-sidebar-width"); return v ? Number(v) : 180; } catch { return 180; }
|
try { const v = localStorage.getItem("contacts-sidebar-width"); return v ? Number(v) : 256; } catch { return 256; }
|
||||||
});
|
});
|
||||||
const [isSidebarResizing, setIsSidebarResizing] = useState(false);
|
const [isSidebarResizing, setIsSidebarResizing] = useState(false);
|
||||||
const sidebarDragStartWidth = useRef(180);
|
const sidebarDragStartWidth = useRef(256);
|
||||||
|
|
||||||
// Panel resize state - contact list
|
// Panel resize state - contact list
|
||||||
const [listWidth, setListWidth] = useState(() => {
|
const [listWidth, setListWidth] = useState(() => {
|
||||||
@@ -120,6 +129,16 @@ export default function ContactsPage() {
|
|||||||
// Contacts to display based on active category
|
// Contacts to display based on active category
|
||||||
const displayedContacts = useMemo(() => {
|
const displayedContacts = useMemo(() => {
|
||||||
if (activeCategory === "all") return individuals;
|
if (activeCategory === "all") return individuals;
|
||||||
|
if ("addressBookId" in activeCategory) {
|
||||||
|
const bookId = activeCategory.addressBookId;
|
||||||
|
return individuals.filter(c => {
|
||||||
|
if (!c.addressBookIds) return false;
|
||||||
|
return c.addressBookIds[bookId] === true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if ("keyword" in activeCategory) {
|
||||||
|
return individuals.filter(c => c.keywords?.[activeCategory.keyword]);
|
||||||
|
}
|
||||||
// Show members of the selected group
|
// Show members of the selected group
|
||||||
return getGroupMembers(activeCategory.groupId);
|
return getGroupMembers(activeCategory.groupId);
|
||||||
}, [activeCategory, individuals, getGroupMembers]);
|
}, [activeCategory, individuals, getGroupMembers]);
|
||||||
@@ -127,20 +146,49 @@ export default function ContactsPage() {
|
|||||||
// Label for the current category
|
// Label for the current category
|
||||||
const categoryLabel = useMemo(() => {
|
const categoryLabel = useMemo(() => {
|
||||||
if (activeCategory === "all") return t("tabs.all");
|
if (activeCategory === "all") return t("tabs.all");
|
||||||
|
if ("addressBookId" in activeCategory) {
|
||||||
|
const book = addressBooks.find(b => b.id === activeCategory.addressBookId);
|
||||||
|
return book?.name || t("tabs.all");
|
||||||
|
}
|
||||||
|
if ("keyword" in activeCategory) {
|
||||||
|
return activeCategory.keyword;
|
||||||
|
}
|
||||||
const group = contacts.find(c => c.id === activeCategory.groupId);
|
const group = contacts.find(c => c.id === activeCategory.groupId);
|
||||||
return group ? getContactDisplayName(group) : t("tabs.all");
|
return group ? getContactDisplayName(group) : t("tabs.all");
|
||||||
}, [activeCategory, contacts, t]);
|
}, [activeCategory, contacts, addressBooks, t]);
|
||||||
|
|
||||||
const handleSelectCategory = useCallback((category: ContactCategory) => {
|
const handleSelectCategory = useCallback((category: ContactCategory) => {
|
||||||
setActiveCategory(category);
|
setActiveCategory(category);
|
||||||
clearSelection();
|
clearSelection();
|
||||||
if (typeof category === "object") {
|
if (typeof category === "object" && "groupId" in category) {
|
||||||
setSelectedGroupId(category.groupId);
|
setSelectedGroupId(category.groupId);
|
||||||
|
setView("group-detail");
|
||||||
} else {
|
} else {
|
||||||
setSelectedGroupId(null);
|
setSelectedGroupId(null);
|
||||||
}
|
}
|
||||||
}, [clearSelection]);
|
}, [clearSelection]);
|
||||||
|
|
||||||
|
const handleDropContacts = useCallback(async (contactIds: string[], addressBook: AddressBook) => {
|
||||||
|
if (!client) return;
|
||||||
|
try {
|
||||||
|
await moveContactToAddressBook(client, contactIds, addressBook);
|
||||||
|
const msg = contactIds.length === 1
|
||||||
|
? t("address_books.moved", { name: addressBook.name })
|
||||||
|
: t("address_books.moved_plural", { count: contactIds.length, name: addressBook.name });
|
||||||
|
toast.success(msg);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to move contacts:', error);
|
||||||
|
toast.error(t("address_books.move_failed"));
|
||||||
|
}
|
||||||
|
}, [client, moveContactToAddressBook, t]);
|
||||||
|
|
||||||
|
const handleImportContacts = useCallback(async (importedContacts: ContactCard[]) => {
|
||||||
|
return importContacts(
|
||||||
|
supportsSync && client ? client : null,
|
||||||
|
importedContacts
|
||||||
|
);
|
||||||
|
}, [supportsSync, client, importContacts]);
|
||||||
|
|
||||||
const handleSelectContact = (id: string) => {
|
const handleSelectContact = (id: string) => {
|
||||||
setSelectedContact(id);
|
setSelectedContact(id);
|
||||||
clearSelection();
|
clearSelection();
|
||||||
@@ -235,6 +283,35 @@ export default function ContactsPage() {
|
|||||||
setView("group-edit");
|
setView("group-edit");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleEditGroupFromSidebar = useCallback((groupId: string) => {
|
||||||
|
setSelectedGroupId(groupId);
|
||||||
|
setActiveCategory({ groupId });
|
||||||
|
setView("group-edit");
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDeleteGroupFromSidebar = useCallback(async (groupId: string) => {
|
||||||
|
const confirmed = await confirmDialog({
|
||||||
|
title: t("groups.delete_confirm_title"),
|
||||||
|
message: t("groups.delete_confirm"),
|
||||||
|
confirmText: t("form.delete"),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deleteGroup(supportsSync && client ? client : null, groupId);
|
||||||
|
toast.success(t("toast.deleted"));
|
||||||
|
if (selectedGroupId === groupId) {
|
||||||
|
setSelectedGroupId(null);
|
||||||
|
setActiveCategory("all");
|
||||||
|
setView("list");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete group:', error);
|
||||||
|
toast.error(t("toast.error_delete"));
|
||||||
|
}
|
||||||
|
}, [confirmDialog, deleteGroup, supportsSync, client, selectedGroupId, t]);
|
||||||
|
|
||||||
const handleDeleteGroup = async () => {
|
const handleDeleteGroup = async () => {
|
||||||
if (!selectedGroup) return;
|
if (!selectedGroup) return;
|
||||||
|
|
||||||
@@ -353,13 +430,14 @@ export default function ContactsPage() {
|
|||||||
const renderRightPanel = () => {
|
const renderRightPanel = () => {
|
||||||
switch (view) {
|
switch (view) {
|
||||||
case "create":
|
case "create":
|
||||||
return <ContactForm onSave={handleSaveNew} onCancel={handleCancel} />;
|
return <ContactForm addressBooks={addressBooks} onSave={handleSaveNew} onCancel={handleCancel} />;
|
||||||
|
|
||||||
case "edit":
|
case "edit":
|
||||||
if (!selectedContact) return null;
|
if (!selectedContact) return null;
|
||||||
return (
|
return (
|
||||||
<ContactForm
|
<ContactForm
|
||||||
contact={selectedContact}
|
contact={selectedContact}
|
||||||
|
addressBooks={addressBooks}
|
||||||
onSave={handleSaveEdit}
|
onSave={handleSaveEdit}
|
||||||
onCancel={handleCancel}
|
onCancel={handleCancel}
|
||||||
/>
|
/>
|
||||||
@@ -377,7 +455,6 @@ export default function ContactsPage() {
|
|||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
onSelectMember={(id) => {
|
onSelectMember={(id) => {
|
||||||
setSelectedContact(id);
|
setSelectedContact(id);
|
||||||
setActiveCategory("all");
|
|
||||||
setView("detail");
|
setView("detail");
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -475,13 +552,20 @@ export default function ContactsPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); router.push('/login'); }}
|
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-col flex-1 min-w-0">
|
<div className="flex flex-col flex-1 min-w-0">
|
||||||
<div className="flex flex-1 min-h-0">
|
{inlineApp && (
|
||||||
|
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} />
|
||||||
|
)}
|
||||||
|
<div className={cn("flex flex-1 min-h-0", inlineApp && "hidden")}>
|
||||||
{showListPanel && (
|
{showListPanel && (
|
||||||
<>
|
<>
|
||||||
{/* Panel 1: Categories sidebar */}
|
{/* Panel 1: Categories sidebar */}
|
||||||
@@ -497,20 +581,25 @@ export default function ContactsPage() {
|
|||||||
<ContactsSidebar
|
<ContactsSidebar
|
||||||
groups={groups}
|
groups={groups}
|
||||||
individuals={individuals}
|
individuals={individuals}
|
||||||
|
addressBooks={addressBooks}
|
||||||
activeCategory={activeCategory}
|
activeCategory={activeCategory}
|
||||||
onSelectCategory={handleSelectCategory}
|
onSelectCategory={handleSelectCategory}
|
||||||
onCreateGroup={handleCreateGroup}
|
onCreateGroup={handleCreateGroup}
|
||||||
onCreateContact={handleCreateNew}
|
onCreateContact={handleCreateNew}
|
||||||
|
onImport={() => setShowImportDialog(true)}
|
||||||
|
onEditGroup={handleEditGroupFromSidebar}
|
||||||
|
onDeleteGroup={handleDeleteGroupFromSidebar}
|
||||||
|
onDropContacts={handleDropContacts}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<ResizeHandle
|
<ResizeHandle
|
||||||
onResizeStart={() => { sidebarDragStartWidth.current = sidebarWidth; setIsSidebarResizing(true); }}
|
onResizeStart={() => { sidebarDragStartWidth.current = sidebarWidth; setIsSidebarResizing(true); }}
|
||||||
onResize={(delta) => setSidebarWidth(Math.max(140, Math.min(300, sidebarDragStartWidth.current + delta)))}
|
onResize={(delta) => setSidebarWidth(Math.max(180, Math.min(400, sidebarDragStartWidth.current + delta)))}
|
||||||
onResizeEnd={() => {
|
onResizeEnd={() => {
|
||||||
setIsSidebarResizing(false);
|
setIsSidebarResizing(false);
|
||||||
localStorage.setItem("contacts-sidebar-width", String(sidebarWidth));
|
localStorage.setItem("contacts-sidebar-width", String(sidebarWidth));
|
||||||
}}
|
}}
|
||||||
onDoubleClick={() => { setSidebarWidth(180); localStorage.setItem("contacts-sidebar-width", "180"); }}
|
onDoubleClick={() => { setSidebarWidth(256); localStorage.setItem("contacts-sidebar-width", "256"); }}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
@@ -582,11 +671,29 @@ export default function ContactsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isMobile && (
|
{isMobile && (
|
||||||
<NavigationRail orientation="horizontal" />
|
<NavigationRail
|
||||||
|
orientation="horizontal"
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
<ConfirmDialog {...confirmDialogProps} />
|
<ConfirmDialog {...confirmDialogProps} />
|
||||||
|
{showImportDialog && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
|
||||||
|
<div className="bg-background rounded-lg border border-border shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden">
|
||||||
|
<ContactImportDialog
|
||||||
|
existingContacts={contacts}
|
||||||
|
onImport={handleImportContacts}
|
||||||
|
onClose={() => setShowImportDialog(false)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import { useFileStore } from "@/stores/file-store";
|
|||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { NavigationRail } from "@/components/layout/navigation-rail";
|
import { NavigationRail } from "@/components/layout/navigation-rail";
|
||||||
|
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
|
||||||
|
import { InlineAppView } from "@/components/layout/inline-app-view";
|
||||||
|
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
|
||||||
import { useIsMobile } from "@/hooks/use-media-query";
|
import { useIsMobile } from "@/hooks/use-media-query";
|
||||||
import { FileBrowser } from "@/components/files/file-browser";
|
import { FileBrowser } from "@/components/files/file-browser";
|
||||||
import { ImagePreviewModal } from "@/components/files/image-preview-modal";
|
import { ImagePreviewModal } from "@/components/files/image-preview-modal";
|
||||||
@@ -24,6 +27,7 @@ export default function FilesPage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations("files");
|
const t = useTranslations("files");
|
||||||
const { isAuthenticated, logout, checkAuth, isLoading: authLoading, client } = useAuthStore();
|
const { isAuthenticated, logout, checkAuth, isLoading: authLoading, client } = useAuthStore();
|
||||||
|
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
||||||
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
||||||
const { quota, isPushConnected } = useEmailStore();
|
const { quota, isPushConnected } = useEmailStore();
|
||||||
const {
|
const {
|
||||||
@@ -353,13 +357,20 @@ export default function FilesPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); router.push('/login'); }}
|
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-col flex-1 min-w-0">
|
<div className="flex flex-col flex-1 min-w-0">
|
||||||
<div className="flex flex-1 min-h-0">
|
{inlineApp && (
|
||||||
|
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} />
|
||||||
|
)}
|
||||||
|
<div className={cn("flex flex-1 min-h-0", inlineApp && "hidden")}>
|
||||||
<div className="flex-1 min-w-0 flex flex-col">
|
<div className="flex-1 min-w-0 flex flex-col">
|
||||||
{folderLayout !== "sidebar" && (
|
{folderLayout !== "sidebar" && (
|
||||||
<div className={cn("p-4 border-b border-border", isMobile && "px-3 py-3")}>
|
<div className={cn("p-4 border-b border-border", isMobile && "px-3 py-3")}>
|
||||||
@@ -433,7 +444,13 @@ export default function FilesPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isMobile && (
|
{isMobile && (
|
||||||
<NavigationRail orientation="horizontal" />
|
<NavigationRail
|
||||||
|
orientation="horizontal"
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -457,6 +474,7 @@ export default function FilesPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
<ConfirmDialog {...confirmDialogProps} />
|
<ConfirmDialog {...confirmDialogProps} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
+25
-15
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
import { useState, useEffect, useRef, useCallback } from "react";
|
||||||
import { useRouter } from "@/i18n/navigation";
|
import { useRouter } from "@/i18n/navigation";
|
||||||
import { useParams } from "next/navigation";
|
import { useParams, useSearchParams } from "next/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -16,7 +16,7 @@ import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
|
|||||||
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
|
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
|
||||||
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
|
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
|
||||||
|
|
||||||
const APP_VERSION = "1.2.4";
|
const APP_VERSION = "1.4.3";
|
||||||
|
|
||||||
const THEME_OPTIONS = [
|
const THEME_OPTIONS = [
|
||||||
{ value: "light" as const, icon: Sun, label: "Light" },
|
{ value: "light" as const, icon: Sun, label: "Light" },
|
||||||
@@ -28,6 +28,8 @@ export default function LoginPage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations("login");
|
const t = useTranslations("login");
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const isAddAccountMode = searchParams.get("mode") === "add-account";
|
||||||
const { login, isLoading, error, clearError, isAuthenticated } = useAuthStore();
|
const { login, isLoading, error, clearError, isAuthenticated } = useAuthStore();
|
||||||
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
|
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
|
||||||
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError } = useConfig();
|
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError } = useConfig();
|
||||||
@@ -102,7 +104,7 @@ export default function LoginPage() {
|
|||||||
}, [serverUrl]);
|
}, [serverUrl]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isAuthenticated) {
|
if (isAuthenticated && !isAddAccountMode) {
|
||||||
let redirectTo = '/';
|
let redirectTo = '/';
|
||||||
try {
|
try {
|
||||||
const saved = sessionStorage.getItem('redirect_after_login');
|
const saved = sessionStorage.getItem('redirect_after_login');
|
||||||
@@ -113,7 +115,7 @@ export default function LoginPage() {
|
|||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
router.push(redirectTo);
|
router.push(redirectTo);
|
||||||
}
|
}
|
||||||
}, [isAuthenticated, router]);
|
}, [isAuthenticated, router, isAddAccountMode]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
clearError();
|
clearError();
|
||||||
@@ -303,6 +305,9 @@ export default function LoginPage() {
|
|||||||
sessionStorage.setItem("oauth_code_verifier", verifier);
|
sessionStorage.setItem("oauth_code_verifier", verifier);
|
||||||
sessionStorage.setItem("oauth_state", state);
|
sessionStorage.setItem("oauth_state", state);
|
||||||
sessionStorage.setItem("oauth_server_url", serverUrl!);
|
sessionStorage.setItem("oauth_server_url", serverUrl!);
|
||||||
|
if (isAddAccountMode) {
|
||||||
|
sessionStorage.setItem("oauth_add_account_mode", "true");
|
||||||
|
}
|
||||||
|
|
||||||
const authUrl = new URL(oauthMetadata.authorization_endpoint);
|
const authUrl = new URL(oauthMetadata.authorization_endpoint);
|
||||||
authUrl.searchParams.set("response_type", "code");
|
authUrl.searchParams.set("response_type", "code");
|
||||||
@@ -329,15 +334,7 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
if (success) {
|
if (success) {
|
||||||
saveUsername(formData.username);
|
saveUsername(formData.username);
|
||||||
let redirectTo = '/';
|
router.push('/');
|
||||||
try {
|
|
||||||
const saved = sessionStorage.getItem('redirect_after_login');
|
|
||||||
if (saved) {
|
|
||||||
sessionStorage.removeItem('redirect_after_login');
|
|
||||||
redirectTo = saved;
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
router.push(redirectTo);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -426,10 +423,10 @@ export default function LoginPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
|
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
|
||||||
{appName}
|
{isAddAccountMode ? t("add_account_title") : appName}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-muted-foreground mt-1.5">
|
<p className="text-sm text-muted-foreground mt-1.5">
|
||||||
{t("title") !== appName ? t("title") : "Sign in to your account"}
|
{isAddAccountMode ? t("add_account_subtitle") : (t("title") !== appName ? t("title") : "Sign in to your account")}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -737,6 +734,19 @@ export default function LoginPage() {
|
|||||||
)}
|
)}
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{isAddAccountMode && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className="w-full h-10 text-sm text-muted-foreground hover:text-foreground"
|
||||||
|
onClick={() => router.push('/')}
|
||||||
|
>
|
||||||
|
{t("cancel")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+113
-21
@@ -35,22 +35,29 @@ import { DragDropProvider } from "@/contexts/drag-drop-context";
|
|||||||
import { isFilterEmpty, activeFilterCount } from "@/lib/jmap/search-utils";
|
import { isFilterEmpty, activeFilterCount } from "@/lib/jmap/search-utils";
|
||||||
import { WelcomeBanner } from "@/components/ui/welcome-banner";
|
import { WelcomeBanner } from "@/components/ui/welcome-banner";
|
||||||
import { NavigationRail } from "@/components/layout/navigation-rail";
|
import { NavigationRail } from "@/components/layout/navigation-rail";
|
||||||
|
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
|
||||||
|
import { InlineAppView } from "@/components/layout/inline-app-view";
|
||||||
|
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";
|
||||||
|
import { useConfig } from "@/hooks/use-config";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const tCommon = useTranslations('common');
|
const tCommon = useTranslations('common');
|
||||||
|
const { appName } = useConfig();
|
||||||
const [showComposer, setShowComposer] = useState(false);
|
const [showComposer, setShowComposer] = useState(false);
|
||||||
const [composerMode, setComposerMode] = useState<'compose' | 'reply' | 'replyAll' | 'forward'>('compose');
|
const [composerMode, setComposerMode] = useState<'compose' | 'reply' | 'replyAll' | 'forward'>('compose');
|
||||||
const [composerDraftText, setComposerDraftText] = useState("");
|
const [composerDraftText, setComposerDraftText] = useState("");
|
||||||
const [pendingDraft, setPendingDraft] = useState<ComposerDraftData | null>(null);
|
const [pendingDraft, setPendingDraft] = useState<ComposerDraftData | null>(null);
|
||||||
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
||||||
|
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
||||||
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
||||||
const [showShortcutsModal, setShowShortcutsModal] = useState(false);
|
const [showShortcutsModal, setShowShortcutsModal] = useState(false);
|
||||||
const [showAdvancedFields, setShowAdvancedFields] = useState(false);
|
const [showAdvancedFields, setShowAdvancedFields] = useState(false);
|
||||||
@@ -224,7 +231,7 @@ export default function Home() {
|
|||||||
|
|
||||||
// Update page title based on context
|
// Update page title based on context
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let title = tCommon('app_title');
|
let title = appName;
|
||||||
|
|
||||||
if (showComposer) {
|
if (showComposer) {
|
||||||
// Composing email
|
// Composing email
|
||||||
@@ -234,11 +241,11 @@ export default function Home() {
|
|||||||
replyAll: t('email_composer.reply_all'),
|
replyAll: t('email_composer.reply_all'),
|
||||||
forward: t('email_composer.forward'),
|
forward: t('email_composer.forward'),
|
||||||
}[composerMode] || t('email_composer.new_message');
|
}[composerMode] || t('email_composer.new_message');
|
||||||
title = `${modeText} - ${tCommon('app_title')}`;
|
title = `${modeText} - ${appName}`;
|
||||||
} else if (selectedEmail) {
|
} else if (selectedEmail) {
|
||||||
// Reading email
|
// Reading email
|
||||||
const subject = selectedEmail.subject || t('email_viewer.no_subject');
|
const subject = selectedEmail.subject || t('email_viewer.no_subject');
|
||||||
title = `${subject} - ${tCommon('app_title')}`;
|
title = `${subject} - ${appName}`;
|
||||||
} else if (selectedMailbox && mailboxes.length > 0) {
|
} else if (selectedMailbox && mailboxes.length > 0) {
|
||||||
// Mailbox view
|
// Mailbox view
|
||||||
const mailbox = mailboxes.find(mb => mb.id === selectedMailbox);
|
const mailbox = mailboxes.find(mb => mb.id === selectedMailbox);
|
||||||
@@ -246,13 +253,13 @@ export default function Home() {
|
|||||||
const mailboxName = mailbox.name;
|
const mailboxName = mailbox.name;
|
||||||
const unreadCount = mailbox.unreadEmails || 0;
|
const unreadCount = mailbox.unreadEmails || 0;
|
||||||
title = unreadCount > 0
|
title = unreadCount > 0
|
||||||
? `${mailboxName} (${unreadCount}) - ${tCommon('app_title')}`
|
? `${mailboxName} (${unreadCount}) - ${appName}`
|
||||||
: `${mailboxName} - ${tCommon('app_title')}`;
|
: `${mailboxName} - ${appName}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.title = title;
|
document.title = title;
|
||||||
}, [showComposer, composerMode, selectedEmail, selectedMailbox, mailboxes, t, tCommon]);
|
}, [showComposer, composerMode, selectedEmail, selectedMailbox, mailboxes, t, appName]);
|
||||||
|
|
||||||
// Check auth on mount
|
// Check auth on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -431,11 +438,12 @@ export default function Home() {
|
|||||||
fromEmail?: string;
|
fromEmail?: string;
|
||||||
fromName?: string;
|
fromName?: string;
|
||||||
identityId?: string;
|
identityId?: string;
|
||||||
|
attachments?: Array<{ blobId: string; name: string; type: string; size: number }>;
|
||||||
}) => {
|
}) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await sendEmail(client, data.to, data.subject, data.body, data.cc, data.bcc, data.identityId, data.fromEmail, data.draftId, data.fromName, data.htmlBody);
|
await sendEmail(client, data.to, data.subject, data.body, data.cc, data.bcc, data.identityId, data.fromEmail, data.draftId, data.fromName, data.htmlBody, data.attachments);
|
||||||
setShowComposer(false);
|
setShowComposer(false);
|
||||||
|
|
||||||
// Refresh the current mailbox to update the UI
|
// Refresh the current mailbox to update the UI
|
||||||
@@ -462,6 +470,33 @@ export default function Home() {
|
|||||||
if (isMobile) setActiveView('viewer');
|
if (isMobile) setActiveView('viewer');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleEditDraft = (email?: Email) => {
|
||||||
|
const draft = email || selectedEmail;
|
||||||
|
if (!draft) return;
|
||||||
|
const bodyText = draft.bodyValues
|
||||||
|
? Object.values(draft.bodyValues).map(v => v.value).join('\n')
|
||||||
|
: '';
|
||||||
|
const htmlBody = draft.htmlBody?.[0]?.partId && draft.bodyValues?.[draft.htmlBody[0].partId]
|
||||||
|
? draft.bodyValues[draft.htmlBody[0].partId].value
|
||||||
|
: undefined;
|
||||||
|
setPendingDraft({
|
||||||
|
to: draft.to?.map(a => a.email).filter(Boolean).join(', ') || '',
|
||||||
|
cc: draft.cc?.map(a => a.email).filter(Boolean).join(', ') || '',
|
||||||
|
bcc: draft.bcc?.map(a => a.email).filter(Boolean).join(', ') || '',
|
||||||
|
subject: draft.subject || '',
|
||||||
|
body: htmlBody || bodyText,
|
||||||
|
showCc: (draft.cc?.length || 0) > 0,
|
||||||
|
showBcc: (draft.bcc?.length || 0) > 0,
|
||||||
|
selectedIdentityId: null,
|
||||||
|
subAddressTag: '',
|
||||||
|
mode: 'compose',
|
||||||
|
draftId: draft.id,
|
||||||
|
});
|
||||||
|
setComposerMode('compose');
|
||||||
|
setShowComposer(true);
|
||||||
|
if (isMobile) setActiveView('viewer');
|
||||||
|
};
|
||||||
|
|
||||||
const handleReplyAll = () => {
|
const handleReplyAll = () => {
|
||||||
setComposerMode('replyAll');
|
setComposerMode('replyAll');
|
||||||
setShowComposer(true);
|
setShowComposer(true);
|
||||||
@@ -516,12 +551,46 @@ export default function Home() {
|
|||||||
|
|
||||||
// Find archive mailbox
|
// Find archive mailbox
|
||||||
const archiveMailbox = mailboxes.find(m => m.role === "archive" || m.name.toLowerCase() === "archive");
|
const archiveMailbox = mailboxes.find(m => m.role === "archive" || m.name.toLowerCase() === "archive");
|
||||||
if (archiveMailbox) {
|
if (!archiveMailbox) return;
|
||||||
try {
|
|
||||||
|
const { archiveMode } = useSettingsStore.getState();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (archiveMode === 'single') {
|
||||||
await moveToMailbox(client, selectedEmail.id, archiveMailbox.id);
|
await moveToMailbox(client, selectedEmail.id, archiveMailbox.id);
|
||||||
} catch (error) {
|
} else {
|
||||||
console.error("Failed to archive email:", error);
|
// Determine year/month from the email's received date
|
||||||
|
const emailDate = new Date(selectedEmail.receivedAt);
|
||||||
|
const year = emailDate.getFullYear().toString();
|
||||||
|
const month = (emailDate.getMonth() + 1).toString().padStart(2, '0');
|
||||||
|
const archiveId = archiveMailbox.originalId || archiveMailbox.id;
|
||||||
|
|
||||||
|
// Find or create year subfolder under archive
|
||||||
|
let yearMailbox = mailboxes.find(
|
||||||
|
m => m.name === year && m.parentId === archiveId
|
||||||
|
);
|
||||||
|
if (!yearMailbox) {
|
||||||
|
yearMailbox = await client.createMailbox(year, archiveId);
|
||||||
|
await fetchMailboxes(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (archiveMode === 'year') {
|
||||||
|
await moveToMailbox(client, selectedEmail.id, yearMailbox.id);
|
||||||
|
} else {
|
||||||
|
// archiveMode === 'month' — find or create month subfolder under year
|
||||||
|
const yearId = yearMailbox.originalId || yearMailbox.id;
|
||||||
|
let monthMailbox = mailboxes.find(
|
||||||
|
m => m.name === month && m.parentId === yearId
|
||||||
|
);
|
||||||
|
if (!monthMailbox) {
|
||||||
|
monthMailbox = await client.createMailbox(month, yearId);
|
||||||
|
await fetchMailboxes(client);
|
||||||
|
}
|
||||||
|
await moveToMailbox(client, selectedEmail.id, monthMailbox.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to archive email:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -701,7 +770,9 @@ export default function Home() {
|
|||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
logout();
|
logout();
|
||||||
router.push('/login');
|
if (!useAuthStore.getState().isAuthenticated) {
|
||||||
|
router.push('/login');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSearch = async (query: string) => {
|
const handleSearch = async (query: string) => {
|
||||||
@@ -792,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(
|
||||||
@@ -952,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">
|
||||||
@@ -971,12 +1043,20 @@ export default function Home() {
|
|||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={handleLogout}
|
onLogout={handleLogout}
|
||||||
onShowShortcuts={() => setShowShortcutsModal(true)}
|
onShowShortcuts={() => setShowShortcutsModal(true)}
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{inlineApp && (
|
||||||
|
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Mobile/Tablet Sidebar Overlay Backdrop */}
|
{/* Mobile/Tablet Sidebar Overlay Backdrop */}
|
||||||
{(isMobile || isTablet) && sidebarOpen && (
|
{(isMobile || isTablet) && sidebarOpen && !inlineApp && (
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 bg-black/50 z-40 lg:hidden"
|
className="fixed inset-0 bg-black/50 z-40 lg:hidden"
|
||||||
onClick={() => setSidebarOpen(false)}
|
onClick={() => setSidebarOpen(false)}
|
||||||
@@ -993,7 +1073,8 @@ export default function Home() {
|
|||||||
"max-lg:transform max-lg:transition-transform max-lg:duration-300 max-lg:ease-in-out",
|
"max-lg:transform max-lg:transition-transform max-lg:duration-300 max-lg:ease-in-out",
|
||||||
!sidebarOpen && "max-lg:-translate-x-full",
|
!sidebarOpen && "max-lg:-translate-x-full",
|
||||||
// Desktop: normal flow
|
// Desktop: normal flow
|
||||||
"lg:relative lg:translate-x-0"
|
"lg:relative lg:translate-x-0",
|
||||||
|
inlineApp && "hidden"
|
||||||
)}
|
)}
|
||||||
style={!isMobile && !isTablet ? { width: sidebarCollapsed ? 64 : sidebarWidth } : undefined}
|
style={!isMobile && !isTablet ? { width: sidebarCollapsed ? 64 : sidebarWidth } : undefined}
|
||||||
>
|
>
|
||||||
@@ -1019,7 +1100,7 @@ export default function Home() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sidebar resize handle (desktop only, hidden when collapsed) */}
|
{/* Sidebar resize handle (desktop only, hidden when collapsed) */}
|
||||||
{!isMobile && !isTablet && !sidebarCollapsed && (
|
{!isMobile && !isTablet && !sidebarCollapsed && !inlineApp && (
|
||||||
<ResizeHandle
|
<ResizeHandle
|
||||||
onResizeStart={() => { dragStartWidth.current = sidebarWidth; setIsResizing(true); }}
|
onResizeStart={() => { dragStartWidth.current = sidebarWidth; setIsResizing(true); }}
|
||||||
onResize={(delta) => setSidebarWidth(dragStartWidth.current + delta)}
|
onResize={(delta) => setSidebarWidth(dragStartWidth.current + delta)}
|
||||||
@@ -1029,7 +1110,7 @@ export default function Home() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Main Content Area */}
|
{/* Main Content Area */}
|
||||||
<div className="flex flex-col flex-1 min-w-0 h-full">
|
<div className={cn("flex flex-col flex-1 min-w-0 h-full", inlineApp && "hidden")}>
|
||||||
<div className="flex flex-1 min-h-0">
|
<div className="flex flex-1 min-h-0">
|
||||||
{/* Email List - full width on mobile, fixed width on tablet/desktop */}
|
{/* Email List - full width on mobile, fixed width on tablet/desktop */}
|
||||||
<div
|
<div
|
||||||
@@ -1321,6 +1402,9 @@ export default function Home() {
|
|||||||
selectEmail(email);
|
selectEmail(email);
|
||||||
await handleUndoSpam();
|
await handleUndoSpam();
|
||||||
}}
|
}}
|
||||||
|
onEditDraft={(email) => {
|
||||||
|
handleEditDraft(email);
|
||||||
|
}}
|
||||||
className="flex-1 min-h-0"
|
className="flex-1 min-h-0"
|
||||||
/>
|
/>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
@@ -1494,6 +1578,7 @@ export default function Home() {
|
|||||||
onNavigateNext={handleNavigateNext}
|
onNavigateNext={handleNavigateNext}
|
||||||
onNavigatePrev={handleNavigatePrev}
|
onNavigatePrev={handleNavigatePrev}
|
||||||
onShowShortcuts={() => setShowShortcutsModal(true)}
|
onShowShortcuts={() => setShowShortcutsModal(true)}
|
||||||
|
onEditDraft={handleEditDraft}
|
||||||
currentUserEmail={client?.["username"]}
|
currentUserEmail={client?.["username"]}
|
||||||
currentUserName={client?.["username"]?.split("@")[0]}
|
currentUserName={client?.["username"]?.split("@")[0]}
|
||||||
currentMailboxRole={mailboxes.find(m => m.id === selectedMailbox)?.role}
|
currentMailboxRole={mailboxes.find(m => m.id === selectedMailbox)?.role}
|
||||||
@@ -1516,7 +1601,13 @@ export default function Home() {
|
|||||||
|
|
||||||
{/* Bottom Navigation - mobile and tablet */}
|
{/* Bottom Navigation - mobile and tablet */}
|
||||||
{(isMobile || isTablet) && activeView !== "viewer" && (
|
{(isMobile || isTablet) && activeView !== "viewer" && (
|
||||||
<NavigationRail orientation="horizontal" />
|
<NavigationRail
|
||||||
|
orientation="horizontal"
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1539,6 +1630,7 @@ export default function Home() {
|
|||||||
{/* Screen reader live region for dynamic status announcements */}
|
{/* Screen reader live region for dynamic status announcements */}
|
||||||
<div className="sr-only" aria-live="polite" aria-atomic="true" id="sr-status" />
|
<div className="sr-only" aria-live="polite" aria-atomic="true" id="sr-status" />
|
||||||
|
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
<ConfirmDialog {...confirmDialogProps} />
|
<ConfirmDialog {...confirmDialogProps} />
|
||||||
</div>
|
</div>
|
||||||
</DragDropProvider>
|
</DragDropProvider>
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ import {
|
|||||||
HardDrive,
|
HardDrive,
|
||||||
Wrench,
|
Wrench,
|
||||||
BookUser,
|
BookUser,
|
||||||
|
KeyRound,
|
||||||
|
PanelLeftClose,
|
||||||
type LucideIcon,
|
type LucideIcon,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -40,15 +42,20 @@ import { KeywordSettings } from '@/components/settings/keyword-settings';
|
|||||||
import { AccountSecuritySettings } from '@/components/settings/account-security-settings';
|
import { AccountSecuritySettings } from '@/components/settings/account-security-settings';
|
||||||
import { FilesSettingsComponent } from '@/components/settings/files-settings';
|
import { FilesSettingsComponent } from '@/components/settings/files-settings';
|
||||||
import { ContactsSettings } from '@/components/settings/contacts-settings';
|
import { ContactsSettings } from '@/components/settings/contacts-settings';
|
||||||
|
import { SmimeSettings } from '@/components/settings/smime-settings';
|
||||||
|
import { SidebarAppsSettings } from '@/components/settings/sidebar-apps-settings';
|
||||||
import { useAuthStore } from '@/stores/auth-store';
|
import { useAuthStore } from '@/stores/auth-store';
|
||||||
import { useEmailStore } from '@/stores/email-store';
|
import { useEmailStore } from '@/stores/email-store';
|
||||||
import { useIsDesktop } from '@/hooks/use-media-query';
|
import { useIsDesktop } from '@/hooks/use-media-query';
|
||||||
import { NavigationRail } from '@/components/layout/navigation-rail';
|
import { NavigationRail } from '@/components/layout/navigation-rail';
|
||||||
|
import { SidebarAppsModal } from '@/components/layout/sidebar-apps-modal';
|
||||||
|
import { InlineAppView } from '@/components/layout/inline-app-view';
|
||||||
|
import { useSidebarApps } from '@/hooks/use-sidebar-apps';
|
||||||
import { ResizeHandle } from '@/components/layout/resize-handle';
|
import { ResizeHandle } from '@/components/layout/resize-handle';
|
||||||
import { useConfig } from '@/hooks/use-config';
|
import { useConfig } from '@/hooks/use-config';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
type Tab = 'appearance' | 'email' | 'account' | 'security' | 'identities' | 'vacation' | 'calendar' | 'contacts' | 'filters' | 'templates' | 'folders' | 'keywords' | 'files' | 'advanced';
|
type Tab = 'appearance' | 'email' | 'account' | 'security' | 'identities' | 'encryption' | 'vacation' | 'calendar' | 'contacts' | 'filters' | 'templates' | 'folders' | 'keywords' | 'files' | 'sidebar_apps' | 'advanced';
|
||||||
type TabGroup = 'general' | 'account' | 'organization' | 'apps' | 'system';
|
type TabGroup = 'general' | 'account' | 'organization' | 'apps' | 'system';
|
||||||
|
|
||||||
interface TabDef {
|
interface TabDef {
|
||||||
@@ -64,6 +71,7 @@ const tabIcons: Record<Tab, LucideIcon> = {
|
|||||||
account: User,
|
account: User,
|
||||||
security: Shield,
|
security: Shield,
|
||||||
identities: UserPen,
|
identities: UserPen,
|
||||||
|
encryption: KeyRound,
|
||||||
vacation: PalmtreeIcon,
|
vacation: PalmtreeIcon,
|
||||||
calendar: Calendar,
|
calendar: Calendar,
|
||||||
contacts: BookUser,
|
contacts: BookUser,
|
||||||
@@ -72,6 +80,7 @@ const tabIcons: Record<Tab, LucideIcon> = {
|
|||||||
folders: FolderOpen,
|
folders: FolderOpen,
|
||||||
keywords: Tags,
|
keywords: Tags,
|
||||||
files: HardDrive,
|
files: HardDrive,
|
||||||
|
sidebar_apps: PanelLeftClose,
|
||||||
advanced: Wrench,
|
advanced: Wrench,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,6 +91,7 @@ export default function SettingsPage() {
|
|||||||
const t = useTranslations('settings');
|
const t = useTranslations('settings');
|
||||||
const tSidebar = useTranslations('sidebar');
|
const tSidebar = useTranslations('sidebar');
|
||||||
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
||||||
|
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
||||||
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
|
||||||
const { quota, isPushConnected } = useEmailStore();
|
const { quota, isPushConnected } = useEmailStore();
|
||||||
const { stalwartFeaturesEnabled } = useConfig();
|
const { stalwartFeaturesEnabled } = useConfig();
|
||||||
@@ -131,6 +141,7 @@ export default function SettingsPage() {
|
|||||||
{ id: 'account', label: t('tabs.account'), icon: tabIcons.account, group: 'account' },
|
{ id: 'account', label: t('tabs.account'), icon: tabIcons.account, group: 'account' },
|
||||||
...(stalwartFeaturesEnabled ? [{ id: 'security' as Tab, label: t('tabs.security'), icon: tabIcons.security, group: 'account' as TabGroup }] : []),
|
...(stalwartFeaturesEnabled ? [{ id: 'security' as Tab, label: t('tabs.security'), icon: tabIcons.security, group: 'account' as TabGroup }] : []),
|
||||||
{ id: 'identities', label: t('tabs.identities'), icon: tabIcons.identities, group: 'account' },
|
{ id: 'identities', label: t('tabs.identities'), icon: tabIcons.identities, group: 'account' },
|
||||||
|
{ id: 'encryption', label: t('tabs.encryption'), icon: tabIcons.encryption, group: 'account' },
|
||||||
...(supportsVacation ? [{ id: 'vacation' as Tab, label: t('tabs.vacation'), icon: tabIcons.vacation, group: 'account' as TabGroup }] : []),
|
...(supportsVacation ? [{ id: 'vacation' as Tab, label: t('tabs.vacation'), icon: tabIcons.vacation, group: 'account' as TabGroup }] : []),
|
||||||
...(supportsSieve ? [{ id: 'filters' as Tab, label: t('tabs.filters'), icon: tabIcons.filters, group: 'organization' as TabGroup }] : []),
|
...(supportsSieve ? [{ id: 'filters' as Tab, label: t('tabs.filters'), icon: tabIcons.filters, group: 'organization' as TabGroup }] : []),
|
||||||
{ id: 'templates', label: t('tabs.templates'), icon: tabIcons.templates, group: 'organization' },
|
{ id: 'templates', label: t('tabs.templates'), icon: tabIcons.templates, group: 'organization' },
|
||||||
@@ -139,6 +150,7 @@ export default function SettingsPage() {
|
|||||||
...(supportsCalendar ? [{ id: 'calendar' as Tab, label: t('tabs.calendar'), icon: tabIcons.calendar, group: 'apps' as TabGroup }] : []),
|
...(supportsCalendar ? [{ id: 'calendar' as Tab, label: t('tabs.calendar'), icon: tabIcons.calendar, group: 'apps' as TabGroup }] : []),
|
||||||
{ id: 'contacts', label: t('tabs.contacts'), icon: tabIcons.contacts, group: 'apps' },
|
{ id: 'contacts', label: t('tabs.contacts'), icon: tabIcons.contacts, group: 'apps' },
|
||||||
...(supportsFiles ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []),
|
...(supportsFiles ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []),
|
||||||
|
{ id: 'sidebar_apps', label: t('tabs.sidebar_apps'), icon: tabIcons.sidebar_apps, group: 'apps' },
|
||||||
{ id: 'advanced', label: t('tabs.advanced'), icon: tabIcons.advanced, group: 'system' },
|
{ id: 'advanced', label: t('tabs.advanced'), icon: tabIcons.advanced, group: 'system' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -168,6 +180,7 @@ export default function SettingsPage() {
|
|||||||
{activeTab === 'account' && <AccountSettings />}
|
{activeTab === 'account' && <AccountSettings />}
|
||||||
{activeTab === 'security' && <AccountSecuritySettings />}
|
{activeTab === 'security' && <AccountSecuritySettings />}
|
||||||
{activeTab === 'identities' && <IdentitySettings />}
|
{activeTab === 'identities' && <IdentitySettings />}
|
||||||
|
{activeTab === 'encryption' && <SmimeSettings />}
|
||||||
{activeTab === 'vacation' && <VacationSettings />}
|
{activeTab === 'vacation' && <VacationSettings />}
|
||||||
{activeTab === 'calendar' && <><CalendarSettings /><div className="mt-8"><CalendarManagementSettings /></div></>}
|
{activeTab === 'calendar' && <><CalendarSettings /><div className="mt-8"><CalendarManagementSettings /></div></>}
|
||||||
{activeTab === 'contacts' && <ContactsSettings />}
|
{activeTab === 'contacts' && <ContactsSettings />}
|
||||||
@@ -176,6 +189,7 @@ export default function SettingsPage() {
|
|||||||
{activeTab === 'folders' && <FolderSettings />}
|
{activeTab === 'folders' && <FolderSettings />}
|
||||||
{activeTab === 'keywords' && <KeywordSettings />}
|
{activeTab === 'keywords' && <KeywordSettings />}
|
||||||
{activeTab === 'files' && <FilesSettingsComponent />}
|
{activeTab === 'files' && <FilesSettingsComponent />}
|
||||||
|
{activeTab === 'sidebar_apps' && <SidebarAppsSettings />}
|
||||||
{activeTab === 'advanced' && <AdvancedSettings />}
|
{activeTab === 'advanced' && <AdvancedSettings />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -207,7 +221,14 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Bottom Navigation */}
|
{/* Bottom Navigation */}
|
||||||
<NavigationRail orientation="horizontal" />
|
<NavigationRail
|
||||||
|
orientation="horizontal"
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -265,7 +286,7 @@ export default function SettingsPage() {
|
|||||||
{/* Logout */}
|
{/* Logout */}
|
||||||
<div className="border-t border-border px-5 py-3">
|
<div className="border-t border-border px-5 py-3">
|
||||||
<button
|
<button
|
||||||
onClick={() => { logout(); router.push('/login'); }}
|
onClick={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
||||||
className="w-full flex items-center gap-3 py-2.5 text-sm text-destructive hover:bg-muted rounded-md px-2 transition-colors duration-150"
|
className="w-full flex items-center gap-3 py-2.5 text-sm text-destructive hover:bg-muted rounded-md px-2 transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<LogOut className="w-4 h-4" />
|
<LogOut className="w-4 h-4" />
|
||||||
@@ -275,7 +296,14 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Bottom Navigation */}
|
{/* Bottom Navigation */}
|
||||||
<NavigationRail orientation="horizontal" />
|
<NavigationRail
|
||||||
|
orientation="horizontal"
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -289,10 +317,19 @@ export default function SettingsPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); router.push('/login'); }}
|
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
||||||
|
onManageApps={handleManageApps}
|
||||||
|
onInlineApp={handleInlineApp}
|
||||||
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
activeAppId={inlineApp?.id ?? null}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{inlineApp && (
|
||||||
|
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
|
||||||
|
)}
|
||||||
|
{!inlineApp && (
|
||||||
|
<>
|
||||||
{/* Settings Sidebar */}
|
{/* Settings Sidebar */}
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -380,6 +417,9 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
|||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
|
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
|
||||||
import { SESSION_COOKIE, SESSION_COOKIE_MAX_AGE } from '@/lib/auth/session-cookie';
|
import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie';
|
||||||
|
|
||||||
const COOKIE_OPTIONS = {
|
const COOKIE_OPTIONS = {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
@@ -12,20 +12,30 @@ const COOKIE_OPTIONS = {
|
|||||||
maxAge: SESSION_COOKIE_MAX_AGE,
|
maxAge: SESSION_COOKIE_MAX_AGE,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function getSlot(request: NextRequest): number {
|
||||||
|
const raw = request.nextUrl.searchParams.get('slot');
|
||||||
|
if (raw === null) return 0;
|
||||||
|
const slot = parseInt(raw, 10);
|
||||||
|
if (isNaN(slot) || slot < 0 || slot > 4) return 0;
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
if (process.env.OAUTH_ENABLED === 'true' && process.env.OAUTH_ONLY === 'true') {
|
if (process.env.OAUTH_ENABLED === 'true' && process.env.OAUTH_ONLY === 'true') {
|
||||||
return NextResponse.json({ error: 'Basic authentication is disabled' }, { status: 403 });
|
return NextResponse.json({ error: 'Basic authentication is disabled' }, { status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { serverUrl, username, password } = await request.json();
|
const { serverUrl, username, password, slot: bodySlot } = await request.json();
|
||||||
if (!serverUrl || !username || !password) {
|
if (!serverUrl || !username || !password) {
|
||||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
|
||||||
|
const cookieName = sessionCookieName(slot);
|
||||||
const token = encryptSession(serverUrl, username, password);
|
const token = encryptSession(serverUrl, username, password);
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
cookieStore.set(SESSION_COOKIE, token, COOKIE_OPTIONS);
|
cookieStore.set(cookieName, token, COOKIE_OPTIONS);
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -34,10 +44,12 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const slot = getSlot(request);
|
||||||
|
const cookieName = sessionCookieName(slot);
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const token = cookieStore.get(SESSION_COOKIE)?.value;
|
const token = cookieStore.get(cookieName)?.value;
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return NextResponse.json({ error: 'No session' }, { status: 401 });
|
return NextResponse.json({ error: 'No session' }, { status: 401 });
|
||||||
@@ -45,7 +57,7 @@ export async function GET() {
|
|||||||
|
|
||||||
const credentials = decryptSession(token);
|
const credentials = decryptSession(token);
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
cookieStore.delete(SESSION_COOKIE);
|
cookieStore.delete(cookieName);
|
||||||
return NextResponse.json({ error: 'Invalid session' }, { status: 401 });
|
return NextResponse.json({ error: 'Invalid session' }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,10 +70,21 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE() {
|
export async function DELETE(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
cookieStore.delete(SESSION_COOKIE);
|
const all = request.nextUrl.searchParams.get('all') === 'true';
|
||||||
|
|
||||||
|
if (all) {
|
||||||
|
// Delete all session cookies (slots 0-4)
|
||||||
|
for (let i = 0; i <= 4; i++) {
|
||||||
|
cookieStore.delete(sessionCookieName(i));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const slot = getSlot(request);
|
||||||
|
cookieStore.delete(sessionCookieName(slot));
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Session clear error', { error: error instanceof Error ? error.message : 'Unknown error' });
|
logger.error('Session clear error', { error: error instanceof Error ? error.message : 'Unknown error' });
|
||||||
|
|||||||
+52
-10
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
|||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
import { discoverOAuth } from '@/lib/oauth/discovery';
|
import { discoverOAuth } from '@/lib/oauth/discovery';
|
||||||
import { REFRESH_TOKEN_COOKIE } from '@/lib/oauth/tokens';
|
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
|
||||||
|
|
||||||
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
|
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
|
||||||
|
|
||||||
@@ -14,6 +14,15 @@ const COOKIE_OPTIONS = {
|
|||||||
maxAge: 30 * 24 * 60 * 60,
|
maxAge: 30 * 24 * 60 * 60,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function getSlot(request: NextRequest): number {
|
||||||
|
const raw = request.nextUrl.searchParams.get('slot');
|
||||||
|
if (raw === null) return 0;
|
||||||
|
const slot = parseInt(raw, 10);
|
||||||
|
if (isNaN(slot) || slot < 0 || slot > 4) return 0;
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function getRequiredConfig() {
|
function getRequiredConfig() {
|
||||||
const clientId = process.env.OAUTH_CLIENT_ID;
|
const clientId = process.env.OAUTH_CLIENT_ID;
|
||||||
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
|
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
|
||||||
@@ -53,12 +62,13 @@ function buildOAuthParams(base: Record<string, string>): URLSearchParams {
|
|||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const { code, code_verifier, redirect_uri } = await request.json();
|
const { code, code_verifier, redirect_uri, slot: bodySlot } = await request.json();
|
||||||
|
|
||||||
if (!code || !code_verifier || !redirect_uri) {
|
if (!code || !code_verifier || !redirect_uri) {
|
||||||
return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 });
|
return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
|
||||||
const tokenEndpoint = await getTokenEndpoint();
|
const tokenEndpoint = await getTokenEndpoint();
|
||||||
|
|
||||||
const params = buildOAuthParams({
|
const params = buildOAuthParams({
|
||||||
@@ -93,8 +103,9 @@ export async function POST(request: NextRequest) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (tokens.refresh_token) {
|
if (tokens.refresh_token) {
|
||||||
|
const cookieName = refreshTokenCookieName(slot);
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
cookieStore.set(REFRESH_TOKEN_COOKIE, tokens.refresh_token, COOKIE_OPTIONS);
|
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
|
||||||
}
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
@@ -104,10 +115,12 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT() {
|
export async function PUT(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const slot = getSlot(request);
|
||||||
|
const cookieName = refreshTokenCookieName(slot);
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value;
|
const refreshToken = cookieStore.get(cookieName)?.value;
|
||||||
|
|
||||||
if (!refreshToken) {
|
if (!refreshToken) {
|
||||||
return NextResponse.json({ error: 'No refresh token' }, { status: 401 });
|
return NextResponse.json({ error: 'No refresh token' }, { status: 401 });
|
||||||
@@ -129,7 +142,7 @@ export async function PUT() {
|
|||||||
if (!tokenResponse.ok) {
|
if (!tokenResponse.ok) {
|
||||||
const errorText = await tokenResponse.text();
|
const errorText = await tokenResponse.text();
|
||||||
logger.error('Token refresh failed', { status: tokenResponse.status, error: errorText });
|
logger.error('Token refresh failed', { status: tokenResponse.status, error: errorText });
|
||||||
cookieStore.delete(REFRESH_TOKEN_COOKIE);
|
cookieStore.delete(cookieName);
|
||||||
return NextResponse.json({ error: 'Refresh failed' }, { status: 401 });
|
return NextResponse.json({ error: 'Refresh failed' }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +154,7 @@ export async function PUT() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (tokens.refresh_token) {
|
if (tokens.refresh_token) {
|
||||||
cookieStore.set(REFRESH_TOKEN_COOKIE, tokens.refresh_token, COOKIE_OPTIONS);
|
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
@@ -154,10 +167,39 @@ export async function PUT() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE() {
|
export async function DELETE(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const all = request.nextUrl.searchParams.get('all') === 'true';
|
||||||
|
|
||||||
|
if (all) {
|
||||||
|
// Revoke and delete all refresh token cookies (slots 0-4)
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
for (let i = 0; i <= 4; i++) {
|
||||||
|
const name = refreshTokenCookieName(i);
|
||||||
|
const token = cookieStore.get(name)?.value;
|
||||||
|
if (token) {
|
||||||
|
// Best-effort revocation
|
||||||
|
try {
|
||||||
|
const metadata = await getMetadata().catch(() => null);
|
||||||
|
if (metadata?.revocation_endpoint) {
|
||||||
|
const params = buildOAuthParams({ token, token_type_hint: 'refresh_token' });
|
||||||
|
await fetch(metadata.revocation_endpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: params.toString(),
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
} catch { /* best effort */ }
|
||||||
|
cookieStore.delete(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const slot = getSlot(request);
|
||||||
|
const cookieName = refreshTokenCookieName(slot);
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value;
|
const refreshToken = cookieStore.get(cookieName)?.value;
|
||||||
const metadata = await getMetadata().catch((err) => {
|
const metadata = await getMetadata().catch((err) => {
|
||||||
logger.warn('Failed to discover OAuth metadata during logout', {
|
logger.warn('Failed to discover OAuth metadata during logout', {
|
||||||
error: err instanceof Error ? err.message : 'Unknown error',
|
error: err instanceof Error ? err.message : 'Unknown error',
|
||||||
@@ -186,7 +228,7 @@ export async function DELETE() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cookieStore.delete(REFRESH_TOKEN_COOKIE);
|
cookieStore.delete(cookieName);
|
||||||
}
|
}
|
||||||
|
|
||||||
let end_session_url: string | undefined;
|
let end_session_url: string | undefined;
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,9 @@ export async function GET() {
|
|||||||
settingsSyncEnabled: process.env.SETTINGS_SYNC_ENABLED === 'true' && !!process.env.SESSION_SECRET,
|
settingsSyncEnabled: process.env.SETTINGS_SYNC_ENABLED === 'true' && !!process.env.SESSION_SECRET,
|
||||||
stalwartFeaturesEnabled: process.env.STALWART_FEATURES !== 'false',
|
stalwartFeaturesEnabled: process.env.STALWART_FEATURES !== 'false',
|
||||||
devMode: process.env.DEV_MOCK_JMAP === 'true',
|
devMode: process.env.DEV_MOCK_JMAP === 'true',
|
||||||
|
faviconUrl: process.env.FAVICON_URL || '/branding/Bulwark_Favicon.svg',
|
||||||
|
appLogoLightUrl: process.env.APP_LOGO_LIGHT_URL || '',
|
||||||
|
appLogoDarkUrl: process.env.APP_LOGO_DARK_URL || '',
|
||||||
loginLogoLightUrl: process.env.LOGIN_LOGO_LIGHT_URL || '/branding/Bulwark_Logo_Color.svg',
|
loginLogoLightUrl: process.env.LOGIN_LOGO_LIGHT_URL || '/branding/Bulwark_Logo_Color.svg',
|
||||||
loginLogoDarkUrl: process.env.LOGIN_LOGO_DARK_URL || '/branding/Bulwark_Logo_White.svg',
|
loginLogoDarkUrl: process.env.LOGIN_LOGO_DARK_URL || '/branding/Bulwark_Logo_White.svg',
|
||||||
loginCompanyName: process.env.LOGIN_COMPANY_NAME || '',
|
loginCompanyName: process.env.LOGIN_COMPANY_NAME || '',
|
||||||
|
|||||||
@@ -47,7 +47,9 @@ export async function GET(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
return NextResponse.json({ settings });
|
return NextResponse.json({ settings });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Settings load error', { error: error instanceof Error ? error.message : 'Unknown error' });
|
const message = error instanceof Error ? error.message : 'Unknown error';
|
||||||
|
const code = (error as NodeJS.ErrnoException).code;
|
||||||
|
logger.error('Settings load error', { error: message, code });
|
||||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,7 +76,9 @@ export async function POST(request: NextRequest) {
|
|||||||
await saveUserSettings(username, serverUrl, settings);
|
await saveUserSettings(username, serverUrl, settings);
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Settings save error', { error: error instanceof Error ? error.message : 'Unknown error' });
|
const message = error instanceof Error ? error.message : 'Unknown error';
|
||||||
|
const code = (error as NodeJS.ErrnoException).code;
|
||||||
|
logger.error('Settings save error', { error: message, code });
|
||||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-4
@@ -14,10 +14,15 @@ const geistMono = Geist_Mono({
|
|||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
title: "Bulwark Webmail",
|
const faviconUrl = process.env.FAVICON_URL;
|
||||||
description: "Minimalist webmail client using JMAP protocol",
|
|
||||||
};
|
return {
|
||||||
|
title: process.env.APP_NAME || process.env.NEXT_PUBLIC_APP_NAME || "Webmail",
|
||||||
|
description: "Minimalist webmail client using JMAP protocol",
|
||||||
|
...(faviconUrl ? { icons: { icon: faviconUrl } } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default async function RootLayout({
|
export default async function RootLayout({
|
||||||
children,
|
children,
|
||||||
|
|||||||
@@ -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";
|
||||||
@@ -22,6 +22,7 @@ interface CalendarMonthViewProps {
|
|||||||
onSelectEvent: (event: CalendarEvent, anchorRect: DOMRect) => void;
|
onSelectEvent: (event: CalendarEvent, anchorRect: DOMRect) => void;
|
||||||
onHoverEvent?: (event: CalendarEvent, anchorRect: DOMRect) => void;
|
onHoverEvent?: (event: CalendarEvent, anchorRect: DOMRect) => void;
|
||||||
onHoverLeave?: () => void;
|
onHoverLeave?: () => void;
|
||||||
|
onCreateAtTime?: (date: Date) => void;
|
||||||
firstDayOfWeek?: number;
|
firstDayOfWeek?: number;
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
}
|
}
|
||||||
@@ -34,6 +35,7 @@ export function CalendarMonthView({
|
|||||||
onSelectEvent,
|
onSelectEvent,
|
||||||
onHoverEvent,
|
onHoverEvent,
|
||||||
onHoverLeave,
|
onHoverLeave,
|
||||||
|
onCreateAtTime,
|
||||||
firstDayOfWeek = 1,
|
firstDayOfWeek = 1,
|
||||||
isMobile,
|
isMobile,
|
||||||
}: CalendarMonthViewProps) {
|
}: CalendarMonthViewProps) {
|
||||||
@@ -165,6 +167,7 @@ export function CalendarMonthView({
|
|||||||
aria-selected={selected}
|
aria-selected={selected}
|
||||||
aria-label={fullDateLabel}
|
aria-label={fullDateLabel}
|
||||||
onClick={() => onSelectDate(day)}
|
onClick={() => onSelectDate(day)}
|
||||||
|
onDoubleClick={() => onCreateAtTime?.(day)}
|
||||||
onDragOver={(e) => handleCellDragOver(e, key)}
|
onDragOver={(e) => handleCellDragOver(e, key)}
|
||||||
onDragLeave={handleCellDragLeave}
|
onDragLeave={handleCellDragLeave}
|
||||||
onDrop={(e) => handleCellDrop(e, day)}
|
onDrop={(e) => handleCellDrop(e, day)}
|
||||||
@@ -194,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
|
||||||
@@ -219,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}`}
|
||||||
@@ -233,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}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useRef, useEffect } from "react";
|
import { useState, useRef, useEffect, useMemo } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Globe, Plus, RefreshCw, Trash2 } from "lucide-react";
|
import { Globe, Plus, RefreshCw, Share2, Trash2 } from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn, formatDateTime } from "@/lib/utils";
|
||||||
import type { Calendar } from "@/lib/jmap/types";
|
import type { Calendar } from "@/lib/jmap/types";
|
||||||
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
|
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import type { JMAPClient } from "@/lib/jmap/client";
|
import type { JMAPClient } from "@/lib/jmap/client";
|
||||||
|
|
||||||
@@ -33,6 +34,7 @@ export function CalendarSidebarPanel({
|
|||||||
const icalSubscriptions = useCalendarStore((s) => s.icalSubscriptions);
|
const icalSubscriptions = useCalendarStore((s) => s.icalSubscriptions);
|
||||||
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
|
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
|
||||||
const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription);
|
const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription);
|
||||||
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
|
|
||||||
const [colorPickerId, setColorPickerId] = useState<string | null>(null);
|
const [colorPickerId, setColorPickerId] = useState<string | null>(null);
|
||||||
const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
|
const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
|
||||||
@@ -40,6 +42,20 @@ export function CalendarSidebarPanel({
|
|||||||
const colorPickerRef = useRef<HTMLDivElement>(null);
|
const colorPickerRef = useRef<HTMLDivElement>(null);
|
||||||
const contextMenuRef = useRef<HTMLDivElement>(null);
|
const contextMenuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const personalCalendars = useMemo(() => calendars.filter(c => !c.isShared), [calendars]);
|
||||||
|
const sharedAccountGroups = useMemo(() => {
|
||||||
|
const shared = calendars.filter(c => c.isShared);
|
||||||
|
const groups = new Map<string, { accountName: string; calendars: Calendar[] }>();
|
||||||
|
for (const cal of shared) {
|
||||||
|
const key = cal.accountId || cal.accountName || cal.id;
|
||||||
|
if (!groups.has(key)) {
|
||||||
|
groups.set(key, { accountName: cal.accountName || key, calendars: [] });
|
||||||
|
}
|
||||||
|
groups.get(key)!.calendars.push(cal);
|
||||||
|
}
|
||||||
|
return Array.from(groups.values());
|
||||||
|
}, [calendars]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!colorPickerId && !contextMenuCalId) return;
|
if (!colorPickerId && !contextMenuCalId) return;
|
||||||
const handleClick = (e: MouseEvent) => {
|
const handleClick = (e: MouseEvent) => {
|
||||||
@@ -95,108 +111,122 @@ export function CalendarSidebarPanel({
|
|||||||
|
|
||||||
if (calendars.length === 0 && !onSubscribe) return null;
|
if (calendars.length === 0 && !onSubscribe) return null;
|
||||||
|
|
||||||
|
const renderCalendarItem = (cal: Calendar) => {
|
||||||
|
const isVisible = selectedCalendarIds.includes(cal.id);
|
||||||
|
const color = cal.color || "#3b82f6";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={cal.id} className="relative">
|
||||||
|
<button
|
||||||
|
onClick={() => onToggleVisibility(cal.id)}
|
||||||
|
onContextMenu={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (isSubscriptionCalendar(cal.id) && client) {
|
||||||
|
setContextMenuCalId(contextMenuCalId === cal.id ? null : cal.id);
|
||||||
|
setColorPickerId(null);
|
||||||
|
} else if (onColorChange) {
|
||||||
|
setColorPickerId(colorPickerId === cal.id ? null : cal.id);
|
||||||
|
setContextMenuCalId(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 w-full px-1.5 py-1 rounded-md text-sm transition-colors duration-150",
|
||||||
|
"hover:bg-muted"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"w-3 h-3 rounded-sm border-2 flex-shrink-0 transition-colors",
|
||||||
|
isVisible ? "border-transparent" : "border-muted-foreground/40 bg-transparent"
|
||||||
|
)}
|
||||||
|
style={isVisible ? { backgroundColor: color, borderColor: color } : undefined}
|
||||||
|
/>
|
||||||
|
<span className={cn("truncate", !isVisible && "text-muted-foreground")}>
|
||||||
|
{cal.name}
|
||||||
|
</span>
|
||||||
|
{isSubscriptionCalendar(cal.id) && (
|
||||||
|
<>
|
||||||
|
<Globe className="w-3 h-3 text-muted-foreground flex-shrink-0" />
|
||||||
|
{refreshingSubId === getSubscriptionForCalendar(cal.id)?.id && (
|
||||||
|
<RefreshCw className="w-3 h-3 text-muted-foreground flex-shrink-0 animate-spin" />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Subscription context menu on right-click */}
|
||||||
|
{contextMenuCalId === cal.id && isSubscriptionCalendar(cal.id) && client && (() => {
|
||||||
|
const sub = getSubscriptionForCalendar(cal.id);
|
||||||
|
if (!sub) return null;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={contextMenuRef}
|
||||||
|
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg py-1 w-48"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={() => handleRefreshSubscription(sub.id)}
|
||||||
|
className="flex items-center gap-2 w-full px-3 py-1.5 text-sm hover:bg-muted transition-colors"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-3.5 h-3.5" />
|
||||||
|
{tSub('refresh')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleUnsubscribe(sub.id)}
|
||||||
|
className="flex items-center gap-2 w-full px-3 py-1.5 text-sm text-destructive hover:bg-destructive/10 transition-colors"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
{tSub('unsubscribe')}
|
||||||
|
</button>
|
||||||
|
{sub.lastRefreshed && (
|
||||||
|
<div className="px-3 py-1.5 text-xs text-muted-foreground border-t border-border mt-1 pt-1">
|
||||||
|
{tSub('last_refreshed', { time: formatDateTime(sub.lastRefreshed, timeFormat, { month: 'short', day: 'numeric', year: 'numeric' }) })}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{/* Color picker popover on right-click */}
|
||||||
|
{colorPickerId === cal.id && onColorChange && (
|
||||||
|
<div
|
||||||
|
ref={colorPickerRef}
|
||||||
|
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-3 w-56"
|
||||||
|
>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground mb-2">{t("management.change_color")}</p>
|
||||||
|
<CalendarColorPicker
|
||||||
|
value={color}
|
||||||
|
onChange={(c) => {
|
||||||
|
onColorChange(cal.id, c);
|
||||||
|
setColorPickerId(null);
|
||||||
|
}}
|
||||||
|
allowCustom
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1">
|
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1">
|
||||||
{t("my_calendars")}
|
{t("my_calendars")}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
{calendars.map((cal) => {
|
{personalCalendars.map(renderCalendarItem)}
|
||||||
const isVisible = selectedCalendarIds.includes(cal.id);
|
|
||||||
const color = cal.color || "#3b82f6";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div key={cal.id} className="relative">
|
|
||||||
<button
|
|
||||||
onClick={() => onToggleVisibility(cal.id)}
|
|
||||||
onContextMenu={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (isSubscriptionCalendar(cal.id) && client) {
|
|
||||||
setContextMenuCalId(contextMenuCalId === cal.id ? null : cal.id);
|
|
||||||
setColorPickerId(null);
|
|
||||||
} else if (onColorChange) {
|
|
||||||
setColorPickerId(colorPickerId === cal.id ? null : cal.id);
|
|
||||||
setContextMenuCalId(null);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center gap-2 w-full px-1.5 py-1 rounded-md text-sm transition-colors duration-150",
|
|
||||||
"hover:bg-muted"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"w-3 h-3 rounded-sm border-2 flex-shrink-0 transition-colors",
|
|
||||||
isVisible ? "border-transparent" : "border-muted-foreground/40 bg-transparent"
|
|
||||||
)}
|
|
||||||
style={isVisible ? { backgroundColor: color, borderColor: color } : undefined}
|
|
||||||
/>
|
|
||||||
<span className={cn("truncate", !isVisible && "text-muted-foreground")}>
|
|
||||||
{cal.name}
|
|
||||||
</span>
|
|
||||||
{isSubscriptionCalendar(cal.id) && (
|
|
||||||
<>
|
|
||||||
<Globe className="w-3 h-3 text-muted-foreground flex-shrink-0" />
|
|
||||||
{refreshingSubId === getSubscriptionForCalendar(cal.id)?.id && (
|
|
||||||
<RefreshCw className="w-3 h-3 text-muted-foreground flex-shrink-0 animate-spin" />
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Subscription context menu on right-click */}
|
|
||||||
{contextMenuCalId === cal.id && isSubscriptionCalendar(cal.id) && client && (() => {
|
|
||||||
const sub = getSubscriptionForCalendar(cal.id);
|
|
||||||
if (!sub) return null;
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
ref={contextMenuRef}
|
|
||||||
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg py-1 w-48"
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
onClick={() => handleRefreshSubscription(sub.id)}
|
|
||||||
className="flex items-center gap-2 w-full px-3 py-1.5 text-sm hover:bg-muted transition-colors"
|
|
||||||
>
|
|
||||||
<RefreshCw className="w-3.5 h-3.5" />
|
|
||||||
{tSub('refresh')}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => handleUnsubscribe(sub.id)}
|
|
||||||
className="flex items-center gap-2 w-full px-3 py-1.5 text-sm text-destructive hover:bg-destructive/10 transition-colors"
|
|
||||||
>
|
|
||||||
<Trash2 className="w-3.5 h-3.5" />
|
|
||||||
{tSub('unsubscribe')}
|
|
||||||
</button>
|
|
||||||
{sub.lastRefreshed && (
|
|
||||||
<div className="px-3 py-1.5 text-xs text-muted-foreground border-t border-border mt-1 pt-1">
|
|
||||||
{tSub('last_refreshed', { time: new Date(sub.lastRefreshed).toLocaleString() })}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
|
|
||||||
{/* Color picker popover on right-click */}
|
|
||||||
{colorPickerId === cal.id && onColorChange && (
|
|
||||||
<div
|
|
||||||
ref={colorPickerRef}
|
|
||||||
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-3 w-56"
|
|
||||||
>
|
|
||||||
<p className="text-xs font-medium text-muted-foreground mb-2">{t("management.change_color")}</p>
|
|
||||||
<CalendarColorPicker
|
|
||||||
value={color}
|
|
||||||
onChange={(c) => {
|
|
||||||
onColorChange(cal.id, c);
|
|
||||||
setColorPickerId(null);
|
|
||||||
}}
|
|
||||||
allowCustom
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{sharedAccountGroups.map((group) => (
|
||||||
|
<div key={group.accountName} className="mt-4">
|
||||||
|
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1 flex items-center gap-1.5">
|
||||||
|
<Share2 className="w-3 h-3" />
|
||||||
|
{group.accountName}
|
||||||
|
</h3>
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
{group.calendars.map(renderCalendarItem)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,7 +153,7 @@ export function CalendarToolbar({
|
|||||||
{t("my_calendars")}
|
{t("my_calendars")}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
{calendars.map((cal) => {
|
{calendars.filter(c => !c.isShared).map((cal) => {
|
||||||
const isVisible = selectedCalendarIds.includes(cal.id);
|
const isVisible = selectedCalendarIds.includes(cal.id);
|
||||||
const color = cal.color || "#3b82f6";
|
const color = cal.color || "#3b82f6";
|
||||||
return (
|
return (
|
||||||
@@ -179,6 +179,49 @@ export function CalendarToolbar({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
{(() => {
|
||||||
|
const shared = calendars.filter(c => c.isShared);
|
||||||
|
const groups = new Map<string, { accountName: string; cals: typeof shared }>();
|
||||||
|
for (const c of shared) {
|
||||||
|
const key = c.accountId || c.accountName || c.id;
|
||||||
|
if (!groups.has(key)) groups.set(key, { accountName: c.accountName || key, cals: [] });
|
||||||
|
groups.get(key)!.cals.push(c);
|
||||||
|
}
|
||||||
|
return Array.from(groups.values()).map((group) => (
|
||||||
|
<div key={group.accountName} className="mt-2">
|
||||||
|
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1 px-1">
|
||||||
|
{group.accountName}
|
||||||
|
</h3>
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
{group.cals.map((cal) => {
|
||||||
|
const isVisible = selectedCalendarIds.includes(cal.id);
|
||||||
|
const color = cal.color || "#3b82f6";
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={cal.id}
|
||||||
|
onClick={() => onToggleVisibility(cal.id)}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 w-full px-2 py-2 rounded-md text-sm transition-colors duration-150 touch-manipulation",
|
||||||
|
"hover:bg-muted"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"w-3.5 h-3.5 rounded-sm border-2 flex-shrink-0 transition-colors",
|
||||||
|
isVisible ? "border-transparent" : "border-muted-foreground/40 bg-transparent"
|
||||||
|
)}
|
||||||
|
style={isVisible ? { backgroundColor: color, borderColor: color } : undefined}
|
||||||
|
/>
|
||||||
|
<span className={cn("truncate", !isVisible && "text-muted-foreground")}>
|
||||||
|
{cal.name}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
));
|
||||||
|
})()}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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)}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
|||||||
import { format, parseISO } from "date-fns";
|
import { format, parseISO } from "date-fns";
|
||||||
import { Users } from "lucide-react";
|
import { Users } from "lucide-react";
|
||||||
import { getParticipantCount } from "@/lib/calendar-participants";
|
import { getParticipantCount } from "@/lib/calendar-participants";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
|
||||||
interface EventCardProps {
|
interface EventCardProps {
|
||||||
event: CalendarEvent;
|
event: CalendarEvent;
|
||||||
@@ -68,11 +69,13 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
|
|||||||
const [isBeingDragged, setIsBeingDragged] = useState(false);
|
const [isBeingDragged, setIsBeingDragged] = useState(false);
|
||||||
const color = getEventColor(event, calendar);
|
const color = getEventColor(event, calendar);
|
||||||
const startDate = parseISO(event.start);
|
const startDate = parseISO(event.start);
|
||||||
|
const timeFormat = useSettingsStore((state) => state.timeFormat);
|
||||||
|
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
|
||||||
|
|
||||||
const calendarName = calendar?.name || "";
|
const calendarName = calendar?.name || "";
|
||||||
const durationMinutes = parseDuration(event.duration);
|
const durationMinutes = parseDuration(event.duration);
|
||||||
const endTime = new Date(startDate.getTime() + durationMinutes * 60000);
|
const endTime = new Date(startDate.getTime() + durationMinutes * 60000);
|
||||||
const timeString = `${format(startDate, "HH:mm")} – ${format(endTime, "HH:mm")}`;
|
const timeString = `${format(startDate, timeFmt)} – ${format(endTime, timeFmt)}`;
|
||||||
const ariaLabel = `${event.title || t("events.no_title")}, ${timeString}${calendarName ? `, ${calendarName}` : ""}`;
|
const ariaLabel = `${event.title || t("events.no_title")}, ${timeString}${calendarName ? `, ${calendarName}` : ""}`;
|
||||||
|
|
||||||
const handleDragStart = useCallback((e: DragEvent) => {
|
const handleDragStart = useCallback((e: DragEvent) => {
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -18,13 +18,14 @@ import {
|
|||||||
getStatusCounts,
|
getStatusCounts,
|
||||||
buildParticipantMap,
|
buildParticipantMap,
|
||||||
} from "@/lib/calendar-participants";
|
} from "@/lib/calendar-participants";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
|
||||||
interface EventModalProps {
|
interface EventModalProps {
|
||||||
event?: CalendarEvent | null;
|
event?: CalendarEvent | null;
|
||||||
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;
|
||||||
@@ -108,6 +109,8 @@ export function EventModal({
|
|||||||
isMobile = false,
|
isMobile = false,
|
||||||
}: EventModalProps) {
|
}: EventModalProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
|
const timeDisplayFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
|
||||||
const isEdit = !!event;
|
const isEdit = !!event;
|
||||||
const [mode, setMode] = useState<"view" | "edit">(isEdit ? "view" : "edit");
|
const [mode, setMode] = useState<"view" | "edit">(isEdit ? "view" : "edit");
|
||||||
|
|
||||||
@@ -181,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 || "";
|
||||||
});
|
});
|
||||||
@@ -206,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 [];
|
||||||
@@ -228,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
|
||||||
@@ -340,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;
|
||||||
@@ -452,7 +461,7 @@ export function EventModal({
|
|||||||
<span className="font-medium">{format(startD, "EEE, MMM d, yyyy")}</span>
|
<span className="font-medium">{format(startD, "EEE, MMM d, yyyy")}</span>
|
||||||
{!event.showWithoutTime && (
|
{!event.showWithoutTime && (
|
||||||
<span className="text-muted-foreground ml-2">
|
<span className="text-muted-foreground ml-2">
|
||||||
{format(startD, "HH:mm")} – {format(endD, "HH:mm")}
|
{format(startD, timeDisplayFmt)} – {format(endD, timeDisplayFmt)}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -576,7 +585,7 @@ export function EventModal({
|
|||||||
<span className="text-muted-foreground ml-1.5">{t("events.all_day")}</span>
|
<span className="text-muted-foreground ml-1.5">{t("events.all_day")}</span>
|
||||||
) : (
|
) : (
|
||||||
<div className="text-muted-foreground">
|
<div className="text-muted-foreground">
|
||||||
{format(startD, "HH:mm")} – {format(endD, "HH:mm")}
|
{format(startD, timeDisplayFmt)} – {format(endD, timeDisplayFmt)}
|
||||||
<span className="ml-1.5 text-xs">({formatDurationDisplay(durMin)})</span>
|
<span className="ml-1.5 text-xs">({formatDurationDisplay(durMin)})</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -942,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>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { format, parseISO } from "date-fns";
|
|||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
import type { JMAPClient } from "@/lib/jmap/client";
|
import type { JMAPClient } from "@/lib/jmap/client";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
|
|
||||||
interface ICalImportModalProps {
|
interface ICalImportModalProps {
|
||||||
@@ -28,6 +29,7 @@ export function ICalImportModal({ calendars, client, onClose }: ICalImportModalP
|
|||||||
const tCommon = useTranslations("common");
|
const tCommon = useTranslations("common");
|
||||||
const tForm = useTranslations("calendar.form");
|
const tForm = useTranslations("calendar.form");
|
||||||
const importEvents = useCalendarStore((s) => s.importEvents);
|
const importEvents = useCalendarStore((s) => s.importEvents);
|
||||||
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
|
|
||||||
const [step, setStep] = useState<ImportStep>("select");
|
const [step, setStep] = useState<ImportStep>("select");
|
||||||
const [parsedEvents, setParsedEvents] = useState<Partial<CalendarEvent>[]>([]);
|
const [parsedEvents, setParsedEvents] = useState<Partial<CalendarEvent>[]>([]);
|
||||||
@@ -194,9 +196,10 @@ export function ICalImportModal({ calendars, client, onClose }: ICalImportModalP
|
|||||||
if (!event.start) return "";
|
if (!event.start) return "";
|
||||||
try {
|
try {
|
||||||
const date = parseISO(event.start);
|
const date = parseISO(event.start);
|
||||||
|
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
|
||||||
return event.showWithoutTime
|
return event.showWithoutTime
|
||||||
? format(date, "MMM d, yyyy")
|
? format(date, "MMM d, yyyy")
|
||||||
: format(date, "MMM d, yyyy HH:mm");
|
: format(date, `MMM d, yyyy ${timeFmt}`);
|
||||||
} catch {
|
} catch {
|
||||||
return event.start;
|
return event.start;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMemo, useCallback } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { format, parseISO, isPast, isToday, isTomorrow } from "date-fns";
|
||||||
|
import { Check, Circle, Flag, CalendarDays, ListTodo } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import type { CalendarTask, Calendar } from "@/lib/jmap/types";
|
||||||
|
import type { TaskViewFilter } from "@/stores/task-store";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
|
||||||
|
interface TaskListViewProps {
|
||||||
|
tasks: CalendarTask[];
|
||||||
|
calendars: Calendar[];
|
||||||
|
selectedCalendarIds: string[];
|
||||||
|
filter: TaskViewFilter;
|
||||||
|
showCompleted: boolean;
|
||||||
|
onSelectTask: (task: CalendarTask) => void;
|
||||||
|
onToggleComplete: (task: CalendarTask) => void;
|
||||||
|
selectedTaskId?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTaskPriorityIcon(priority: number) {
|
||||||
|
if (priority >= 1 && priority <= 4) return <Flag className="h-3.5 w-3.5 text-red-500" />;
|
||||||
|
if (priority === 5) return <Flag className="h-3.5 w-3.5 text-orange-500" />;
|
||||||
|
if (priority >= 6 && priority <= 9) return <Flag className="h-3.5 w-3.5 text-gray-400" />;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDueDateLabel(due: string, showWithoutTime: boolean, t: ReturnType<typeof useTranslations>, timeFormat: string): { label: string; className: string } {
|
||||||
|
const dueDate = parseISO(due);
|
||||||
|
const overdue = isPast(dueDate) && !isToday(dueDate);
|
||||||
|
|
||||||
|
if (isToday(dueDate)) {
|
||||||
|
return {
|
||||||
|
label: t("tasks.due_today"),
|
||||||
|
className: "text-blue-600 dark:text-blue-400",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (isTomorrow(dueDate)) {
|
||||||
|
return {
|
||||||
|
label: t("tasks.due_tomorrow"),
|
||||||
|
className: "text-muted-foreground",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (overdue) {
|
||||||
|
return {
|
||||||
|
label: t("tasks.overdue"),
|
||||||
|
className: "text-red-600 dark:text-red-400",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatted = showWithoutTime
|
||||||
|
? format(dueDate, "MMM d")
|
||||||
|
: format(dueDate, timeFormat === "12h" ? "MMM d, h:mm a" : "MMM d, HH:mm");
|
||||||
|
|
||||||
|
return {
|
||||||
|
label: formatted,
|
||||||
|
className: "text-muted-foreground",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TaskListView({
|
||||||
|
tasks,
|
||||||
|
calendars,
|
||||||
|
selectedCalendarIds,
|
||||||
|
filter,
|
||||||
|
showCompleted,
|
||||||
|
onSelectTask,
|
||||||
|
onToggleComplete,
|
||||||
|
selectedTaskId,
|
||||||
|
}: TaskListViewProps) {
|
||||||
|
const t = useTranslations("calendar");
|
||||||
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
|
|
||||||
|
const filteredTasks = useMemo(() => {
|
||||||
|
let result = tasks.filter(task => {
|
||||||
|
const calIds = Object.keys(task.calendarIds);
|
||||||
|
return calIds.some(id => selectedCalendarIds.includes(id));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!showCompleted) {
|
||||||
|
result = result.filter(task => task.progress !== "completed" && task.progress !== "cancelled");
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (filter) {
|
||||||
|
case "pending":
|
||||||
|
result = result.filter(task => task.progress === "needs-action" || task.progress === "in-process");
|
||||||
|
break;
|
||||||
|
case "completed":
|
||||||
|
result = result.filter(task => task.progress === "completed");
|
||||||
|
break;
|
||||||
|
case "overdue":
|
||||||
|
result = result.filter(task => {
|
||||||
|
if (!task.due || task.progress === "completed" || task.progress === "cancelled") return false;
|
||||||
|
return isPast(parseISO(task.due)) && !isToday(parseISO(task.due));
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort: overdue first, then by due date (no due date last), then by priority
|
||||||
|
result.sort((a, b) => {
|
||||||
|
// Completed tasks at the bottom
|
||||||
|
if (a.progress === "completed" && b.progress !== "completed") return 1;
|
||||||
|
if (a.progress !== "completed" && b.progress === "completed") return -1;
|
||||||
|
|
||||||
|
// Tasks with due dates before those without
|
||||||
|
if (a.due && !b.due) return -1;
|
||||||
|
if (!a.due && b.due) return 1;
|
||||||
|
if (a.due && b.due) {
|
||||||
|
const dateCompare = new Date(a.due).getTime() - new Date(b.due).getTime();
|
||||||
|
if (dateCompare !== 0) return dateCompare;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Higher priority first (lower number = higher priority, but 0 = no priority goes last)
|
||||||
|
const aPri = a.priority || 10;
|
||||||
|
const bPri = b.priority || 10;
|
||||||
|
return aPri - bPri;
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}, [tasks, selectedCalendarIds, filter, showCompleted]);
|
||||||
|
|
||||||
|
const handleToggle = useCallback((e: React.MouseEvent, task: CalendarTask) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onToggleComplete(task);
|
||||||
|
}, [onToggleComplete]);
|
||||||
|
|
||||||
|
if (filteredTasks.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground py-12">
|
||||||
|
<ListTodo className="h-12 w-12 mb-3 opacity-30" />
|
||||||
|
<p className="text-sm">{t("tasks.no_tasks")}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-1 overflow-y-auto">
|
||||||
|
<div className="divide-y divide-border">
|
||||||
|
{filteredTasks.map(task => {
|
||||||
|
const cal = calendars.find(c => task.calendarIds[c.id]);
|
||||||
|
const isCompleted = task.progress === "completed";
|
||||||
|
const priorityIcon = getTaskPriorityIcon(task.priority);
|
||||||
|
const dueDateInfo = task.due ? getDueDateLabel(task.due, task.showWithoutTime, t, timeFormat) : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={task.id}
|
||||||
|
onClick={() => onSelectTask(task)}
|
||||||
|
className={cn(
|
||||||
|
"flex items-start gap-3 px-4 py-3 cursor-pointer hover:bg-muted/50 transition-colors",
|
||||||
|
selectedTaskId === task.id && "bg-muted",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{/* Checkbox */}
|
||||||
|
<button
|
||||||
|
onClick={(e) => handleToggle(e, task)}
|
||||||
|
className={cn(
|
||||||
|
"mt-0.5 flex-shrink-0 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors",
|
||||||
|
isCompleted
|
||||||
|
? "bg-green-500 border-green-500 text-white"
|
||||||
|
: "border-muted-foreground/40 hover:border-primary"
|
||||||
|
)}
|
||||||
|
aria-label={isCompleted ? t("tasks.mark_incomplete") : t("tasks.mark_complete")}
|
||||||
|
>
|
||||||
|
{isCompleted && <Check className="h-3 w-3" />}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className={cn(
|
||||||
|
"text-sm font-medium truncate",
|
||||||
|
isCompleted && "line-through text-muted-foreground"
|
||||||
|
)}>
|
||||||
|
{task.title || t("tasks.no_title")}
|
||||||
|
</span>
|
||||||
|
{priorityIcon}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 mt-0.5">
|
||||||
|
{dueDateInfo && (
|
||||||
|
<span className={cn("text-xs flex items-center gap-1", dueDateInfo.className)}>
|
||||||
|
<CalendarDays className="h-3 w-3" />
|
||||||
|
{dueDateInfo.label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{cal && (
|
||||||
|
<span className="text-xs text-muted-foreground flex items-center gap-1">
|
||||||
|
<span className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: cal.color || "#3b82f6" }} />
|
||||||
|
{cal.name}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ describe('ContactListItem', () => {
|
|||||||
density: 'regular' as const,
|
density: 'regular' as const,
|
||||||
onClick: vi.fn(),
|
onClick: vi.fn(),
|
||||||
onCheckboxClick: vi.fn(),
|
onCheckboxClick: vi.fn(),
|
||||||
|
selectedContactIds: new Set<string>(),
|
||||||
};
|
};
|
||||||
|
|
||||||
it('renders contact name and email', () => {
|
it('renders contact name and email', () => {
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Mail, Phone, Building, MapPin, StickyNote, Pencil, Trash2, BookUser, Copy, Send, Globe, Cake, Tag, KeyRound, Link, Users, Briefcase, Heart, Languages, MessageCircle, User, Calendar, UserCircle } from "lucide-react";
|
import { Mail, Phone, Building, MapPin, StickyNote, Pencil, Trash2, BookUser, Copy, Send, Globe, Cake, Tag, KeyRound, Link, Users, Briefcase, Heart, Languages, MessageCircle, User, Calendar, UserCircle, ShieldCheck, ShieldAlert, Download } from "lucide-react";
|
||||||
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 { parseCertificatePemOrDer, extractCertificateInfo } from "@/lib/smime/certificate-utils";
|
||||||
|
import type { CertificateInfo } from "@/lib/smime/types";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
|
|
||||||
interface ContactDetailProps {
|
interface ContactDetailProps {
|
||||||
@@ -22,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]);
|
||||||
@@ -56,6 +71,50 @@ function formatDate(dateInput: string | Record<string, unknown>): string {
|
|||||||
|
|
||||||
export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }: ContactDetailProps) {
|
export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }: ContactDetailProps) {
|
||||||
const t = useTranslations("contacts");
|
const t = useTranslations("contacts");
|
||||||
|
const smimeStore = useSmimeStore();
|
||||||
|
const [parsedCerts, setParsedCerts] = useState<Map<number, CertificateInfo>>(new Map());
|
||||||
|
|
||||||
|
const cryptoKeys = contact?.cryptoKeys ? Object.values(contact.cryptoKeys) : [];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!contact) return;
|
||||||
|
let cancelled = false;
|
||||||
|
const parseCerts = async () => {
|
||||||
|
const results = new Map<number, CertificateInfo>();
|
||||||
|
for (let i = 0; i < cryptoKeys.length; i++) {
|
||||||
|
const key = cryptoKeys[i];
|
||||||
|
if (typeof key.uri !== 'string') continue;
|
||||||
|
try {
|
||||||
|
let derBytes: ArrayBuffer | string | null = null;
|
||||||
|
if (key.uri.startsWith('data:')) {
|
||||||
|
// data URI — extract base64 content
|
||||||
|
const commaIdx = key.uri.indexOf(',');
|
||||||
|
if (commaIdx === -1) continue;
|
||||||
|
const b64 = key.uri.substring(commaIdx + 1);
|
||||||
|
const binary = atob(b64);
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let j = 0; j < binary.length; j++) bytes[j] = binary.charCodeAt(j);
|
||||||
|
derBytes = bytes.buffer;
|
||||||
|
} else if (key.uri.startsWith('-----BEGIN')) {
|
||||||
|
// PEM-encoded certificate inline
|
||||||
|
derBytes = key.uri;
|
||||||
|
}
|
||||||
|
if (!derBytes) continue;
|
||||||
|
const cert = parseCertificatePemOrDer(derBytes);
|
||||||
|
const der = typeof derBytes === 'string' ? cert.toSchema(true).toBER(false) : derBytes;
|
||||||
|
const info = await extractCertificateInfo(cert, der);
|
||||||
|
if (!cancelled) results.set(i, info);
|
||||||
|
} catch { /* skip unparseable keys */ }
|
||||||
|
}
|
||||||
|
if (!cancelled) setParsedCerts(results);
|
||||||
|
};
|
||||||
|
if (cryptoKeys.length > 0) {
|
||||||
|
parseCerts();
|
||||||
|
} else {
|
||||||
|
setParsedCerts(new Map());
|
||||||
|
}
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [contact?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
if (!contact) {
|
if (!contact) {
|
||||||
return (
|
return (
|
||||||
@@ -79,7 +138,31 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
|
|||||||
const onlineServices = contact.onlineServices ? Object.values(contact.onlineServices) : [];
|
const onlineServices = contact.onlineServices ? Object.values(contact.onlineServices) : [];
|
||||||
const anniversaries = contact.anniversaries ? Object.values(contact.anniversaries) : [];
|
const anniversaries = contact.anniversaries ? Object.values(contact.anniversaries) : [];
|
||||||
const keywords = contact.keywords ? Object.keys(contact.keywords).filter(k => contact.keywords![k]) : [];
|
const keywords = contact.keywords ? Object.keys(contact.keywords).filter(k => contact.keywords![k]) : [];
|
||||||
const cryptoKeys = contact.cryptoKeys ? Object.values(contact.cryptoKeys) : [];
|
|
||||||
|
const handleImportContactCert = async (keyIndex: number) => {
|
||||||
|
const key = cryptoKeys[keyIndex];
|
||||||
|
if (!key?.uri || typeof key.uri !== 'string') return;
|
||||||
|
try {
|
||||||
|
let derBytes: ArrayBuffer | string;
|
||||||
|
if (key.uri.startsWith('data:')) {
|
||||||
|
const commaIdx = key.uri.indexOf(',');
|
||||||
|
if (commaIdx === -1) return;
|
||||||
|
const b64 = key.uri.substring(commaIdx + 1);
|
||||||
|
const binary = atob(b64);
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let j = 0; j < binary.length; j++) bytes[j] = binary.charCodeAt(j);
|
||||||
|
derBytes = bytes.buffer;
|
||||||
|
} else if (key.uri.startsWith('-----BEGIN')) {
|
||||||
|
derBytes = key.uri;
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await smimeStore.importPublicCert(derBytes, 'contact', contact.id);
|
||||||
|
toast.success(t("detail.cert_imported"));
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : t("detail.cert_import_failed"));
|
||||||
|
}
|
||||||
|
};
|
||||||
const relatedTo = contact.relatedTo ? Object.entries(contact.relatedTo) : [];
|
const relatedTo = contact.relatedTo ? Object.entries(contact.relatedTo) : [];
|
||||||
const preferredLanguages = contact.preferredLanguages ? Object.values(contact.preferredLanguages) : [];
|
const preferredLanguages = contact.preferredLanguages ? Object.values(contact.preferredLanguages) : [];
|
||||||
const personalInfo = contact.personalInfo ? Object.values(contact.personalInfo) : [];
|
const personalInfo = contact.personalInfo ? Object.values(contact.personalInfo) : [];
|
||||||
@@ -210,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 && (
|
||||||
@@ -279,13 +364,16 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
|
|||||||
</Section>
|
</Section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{contact.gender && (contact.gender.sex || contact.gender.identity) && (
|
{contact.speakToAs && (contact.speakToAs.grammaticalGender || contact.speakToAs.pronouns) && (
|
||||||
<Section icon={UserCircle} title={t("detail.gender")} category="personal">
|
<Section icon={UserCircle} title={t("detail.gender")} category="personal">
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
{contact.gender.sex && <span>{t(`detail.gender_${contact.gender.sex.toUpperCase()}`, { defaultValue: contact.gender.sex })}</span>}
|
{contact.speakToAs.grammaticalGender && <span>{t(`detail.gender_${contact.speakToAs.grammaticalGender}`, { defaultValue: contact.speakToAs.grammaticalGender })}</span>}
|
||||||
{contact.gender.identity && (
|
{contact.speakToAs.pronouns && (() => {
|
||||||
<span className="text-muted-foreground">{contact.gender.sex ? " — " : ""}{contact.gender.identity}</span>
|
const firstPronoun = Object.values(contact.speakToAs!.pronouns!)[0]?.pronouns;
|
||||||
)}
|
return firstPronoun ? (
|
||||||
|
<span className="text-muted-foreground">{contact.speakToAs!.grammaticalGender ? " — " : ""}{firstPronoun}</span>
|
||||||
|
) : null;
|
||||||
|
})()}
|
||||||
</div>
|
</div>
|
||||||
</Section>
|
</Section>
|
||||||
)}
|
)}
|
||||||
@@ -331,17 +419,63 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
|
|||||||
|
|
||||||
{cryptoKeys.length > 0 && (
|
{cryptoKeys.length > 0 && (
|
||||||
<Section icon={KeyRound} title={t("detail.crypto_keys")} category="digital">
|
<Section icon={KeyRound} title={t("detail.crypto_keys")} category="digital">
|
||||||
{cryptoKeys.map((key, i) => (
|
{cryptoKeys.map((key, i) => {
|
||||||
<div key={i} className="text-sm break-all">
|
const certInfo = parsedCerts.get(i);
|
||||||
{typeof key.uri === 'string' && key.uri.startsWith("http") ? (
|
const isExpired = certInfo ? new Date(certInfo.notAfter) < new Date() : false;
|
||||||
<a href={key.uri} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
|
const alreadyImported = certInfo?.emailAddresses?.[0]
|
||||||
{key.uri}
|
? !!smimeStore.getPublicCertForEmail(certInfo.emailAddresses[0])
|
||||||
</a>
|
: false;
|
||||||
) : (
|
|
||||||
<span className="text-muted-foreground">{typeof key.uri === 'string' ? `${key.uri.substring(0, 80)}${key.uri.length > 80 ? "…" : ""}` : String(key.uri ?? '')}</span>
|
return (
|
||||||
)}
|
<div key={i} className="p-3 rounded-lg border border-border space-y-1">
|
||||||
</div>
|
{certInfo ? (
|
||||||
))}
|
<>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isExpired ? (
|
||||||
|
<ShieldAlert className="w-4 h-4 text-destructive flex-shrink-0" />
|
||||||
|
) : (
|
||||||
|
<ShieldCheck className="w-4 h-4 text-primary flex-shrink-0" />
|
||||||
|
)}
|
||||||
|
<span className="text-sm font-medium truncate">{certInfo.subject}</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground space-y-0.5 pl-6">
|
||||||
|
<p>{t("detail.cert_issuer")}: {certInfo.issuer}</p>
|
||||||
|
<p>
|
||||||
|
{t("detail.cert_expires")}: {new Date(certInfo.notAfter).toLocaleDateString()}
|
||||||
|
{isExpired && <span className="text-destructive ml-1">({t("detail.cert_expired")})</span>}
|
||||||
|
</p>
|
||||||
|
<p>{t("detail.cert_fingerprint")}: {certInfo.fingerprint.substring(0, 20)}...</p>
|
||||||
|
{certInfo.algorithm && <p>{t("detail.cert_algorithm")}: {certInfo.algorithm}</p>}
|
||||||
|
</div>
|
||||||
|
{!alreadyImported && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="ml-4 mt-1"
|
||||||
|
onClick={() => handleImportContactCert(i)}
|
||||||
|
>
|
||||||
|
<Download className="w-3 h-3 mr-1" />
|
||||||
|
{t("detail.import_to_smime")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{alreadyImported && (
|
||||||
|
<p className="text-xs text-green-600 pl-6 mt-1">{t("detail.cert_already_imported")}</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="text-sm break-all">
|
||||||
|
{typeof key.uri === 'string' && key.uri.startsWith("http") ? (
|
||||||
|
<a href={key.uri} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
|
||||||
|
{key.uri}
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">{typeof key.uri === 'string' ? `${key.uri.substring(0, 80)}${key.uri.length > 80 ? "…" : ""}` : String(key.uri ?? '')}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</Section>
|
</Section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState, useMemo } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake, Heart, Tag, StickyNote, Mail, Phone, Calendar, UserCircle } from "lucide-react";
|
import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake, Heart, Tag, StickyNote, Mail, Phone, Calendar, UserCircle, Book } from "lucide-react";
|
||||||
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 } 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;
|
||||||
@@ -47,6 +47,7 @@ interface AddressEntry {
|
|||||||
|
|
||||||
interface ContactFormProps {
|
interface ContactFormProps {
|
||||||
contact?: ContactCard | null;
|
contact?: ContactCard | null;
|
||||||
|
addressBooks?: AddressBook[];
|
||||||
onSave: (data: Partial<ContactCard>) => Promise<void>;
|
onSave: (data: Partial<ContactCard>) => Promise<void>;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
}
|
}
|
||||||
@@ -122,12 +123,73 @@ function Select({ value, onChange, children, className }: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
export function ContactForm({ contact, addressBooks, onSave, onCancel }: ContactFormProps) {
|
||||||
const t = useTranslations("contacts.form");
|
const t = useTranslations("contacts.form");
|
||||||
const isEditing = !!contact;
|
const isEditing = !!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"));
|
||||||
@@ -183,14 +245,7 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
|
|
||||||
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 [];
|
||||||
});
|
});
|
||||||
@@ -209,7 +264,7 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
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,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -235,12 +290,31 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
contact?.notes ? Object.values(contact.notes)[0]?.note || "" : ""
|
contact?.notes ? Object.values(contact.notes)[0]?.note || "" : ""
|
||||||
);
|
);
|
||||||
|
|
||||||
const [genderSex, setGenderSex] = useState(contact?.gender?.sex || "");
|
const [genderSex, setGenderSex] = useState(contact?.speakToAs?.grammaticalGender || "");
|
||||||
const [genderIdentity, setGenderIdentity] = useState(contact?.gender?.identity || "");
|
const [genderIdentity, setGenderIdentity] = useState(
|
||||||
|
contact?.speakToAs?.pronouns ? Object.values(contact.speakToAs.pronouns)[0]?.pronouns || "" : ""
|
||||||
|
);
|
||||||
const [calendarUri, setCalendarUri] = useState(contact?.calendarUri || "");
|
const [calendarUri, setCalendarUri] = useState(contact?.calendarUri || "");
|
||||||
const [schedulingUri, setSchedulingUri] = useState(contact?.schedulingUri || "");
|
const [schedulingUri, setSchedulingUri] = useState(contact?.schedulingUri || "");
|
||||||
const [freeBusyUri, setFreeBusyUri] = useState(contact?.freeBusyUri || "");
|
const [freeBusyUri, setFreeBusyUri] = useState(contact?.freeBusyUri || "");
|
||||||
|
|
||||||
|
// Address book selection
|
||||||
|
const currentBookId = useMemo(() => {
|
||||||
|
if (contact?.addressBookIds) {
|
||||||
|
const ids = Object.keys(contact.addressBookIds).filter(k => contact.addressBookIds[k]);
|
||||||
|
if (ids.length > 0) {
|
||||||
|
// For shared contacts, the addressBookIds uses the original (non-namespaced) id
|
||||||
|
// but we need the namespaced id to match addressBooks entries
|
||||||
|
if (contact.isShared && contact.accountId) {
|
||||||
|
return `${contact.accountId}:${ids[0]}`;
|
||||||
|
}
|
||||||
|
return ids[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}, [contact]);
|
||||||
|
const [selectedBookId, setSelectedBookId] = useState(currentBookId);
|
||||||
|
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [emailErrors, setEmailErrors] = useState<Record<number, string>>({});
|
const [emailErrors, setEmailErrors] = useState<Record<number, string>>({});
|
||||||
@@ -316,12 +390,13 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
|
|
||||||
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;
|
||||||
@@ -337,7 +412,7 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
|
|
||||||
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> = {};
|
||||||
@@ -371,12 +446,16 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
notes: note.trim()
|
notes: note.trim()
|
||||||
? { n0: { note: note.trim() } }
|
? { n0: { note: note.trim() } }
|
||||||
: undefined,
|
: undefined,
|
||||||
gender: (genderSex.trim() || genderIdentity.trim())
|
speakToAs: (genderSex.trim() || genderIdentity.trim())
|
||||||
? { sex: genderSex.trim() || undefined, identity: genderIdentity.trim() || undefined }
|
? {
|
||||||
|
grammaticalGender: genderSex.trim() || undefined,
|
||||||
|
pronouns: genderIdentity.trim() ? { p0: { pronouns: genderIdentity.trim() } } : undefined,
|
||||||
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
calendarUri: calendarUri.trim() || undefined,
|
calendarUri: calendarUri.trim() || undefined,
|
||||||
schedulingUri: schedulingUri.trim() || undefined,
|
schedulingUri: schedulingUri.trim() || undefined,
|
||||||
freeBusyUri: freeBusyUri.trim() || undefined,
|
freeBusyUri: freeBusyUri.trim() || undefined,
|
||||||
|
...(selectedBookId ? { addressBookIds: { [selectedBookId]: true } } : {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
@@ -410,6 +489,26 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
|
||||||
|
|
||||||
|
{/* Address Book Selector */}
|
||||||
|
{addressBooks && addressBooks.length > 1 && (
|
||||||
|
<div className="md:col-span-2 xl:col-span-3">
|
||||||
|
<FormSection icon={Book} title={t("section_address_book") || "Directory"} category="contact">
|
||||||
|
<select
|
||||||
|
value={selectedBookId}
|
||||||
|
onChange={(e) => setSelectedBookId(e.target.value)}
|
||||||
|
className="w-full px-3 py-2 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
|
||||||
|
>
|
||||||
|
<option value="">{t("select_address_book") || "Select a directory..."}</option>
|
||||||
|
{addressBooks.map((book) => (
|
||||||
|
<option key={book.id} value={book.id}>
|
||||||
|
{book.accountName ? `${book.name} (${book.accountName})` : book.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</FormSection>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Name & Identity — full width */}
|
{/* Name & Identity — full width */}
|
||||||
<div className="md:col-span-2 xl:col-span-3">
|
<div className="md:col-span-2 xl:col-span-3">
|
||||||
<FormSection icon={User} title={t("section_identity")} category="contact">
|
<FormSection icon={User} title={t("section_identity")} category="contact">
|
||||||
@@ -737,11 +836,11 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
|
|||||||
<label className="text-xs text-muted-foreground mb-1 block">{t("gender_sex")}</label>
|
<label className="text-xs text-muted-foreground mb-1 block">{t("gender_sex")}</label>
|
||||||
<Select value={genderSex} onChange={(e) => setGenderSex(e.target.value)} className="w-full">
|
<Select value={genderSex} onChange={(e) => setGenderSex(e.target.value)} className="w-full">
|
||||||
<option value="">—</option>
|
<option value="">—</option>
|
||||||
<option value="M">{t("gender_male")}</option>
|
<option value="masculine">{t("gender_male")}</option>
|
||||||
<option value="F">{t("gender_female")}</option>
|
<option value="feminine">{t("gender_female")}</option>
|
||||||
<option value="O">{t("gender_other")}</option>
|
<option value="other">{t("gender_other")}</option>
|
||||||
<option value="N">{t("gender_none")}</option>
|
<option value="none">{t("gender_none")}</option>
|
||||||
<option value="U">{t("gender_unknown")}</option>
|
<option value="unknown">{t("gender_unknown")}</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, type DragEvent } from "react";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { ContactCard } from "@/lib/jmap/types";
|
import type { ContactCard } from "@/lib/jmap/types";
|
||||||
@@ -13,19 +14,47 @@ interface ContactListItemProps {
|
|||||||
isChecked: boolean;
|
isChecked: boolean;
|
||||||
hasSelection: boolean;
|
hasSelection: boolean;
|
||||||
density: Density;
|
density: Density;
|
||||||
|
selectedContactIds: Set<string>;
|
||||||
onClick: (e: React.MouseEvent) => void;
|
onClick: (e: React.MouseEvent) => void;
|
||||||
onCheckboxClick: (e: React.MouseEvent) => void;
|
onCheckboxClick: (e: React.MouseEvent) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ContactListItem({ contact, isSelected, isChecked, hasSelection, density, onClick, onCheckboxClick }: ContactListItemProps) {
|
export function ContactListItem({ contact, isSelected, isChecked, hasSelection, density, selectedContactIds, onClick, onCheckboxClick }: ContactListItemProps) {
|
||||||
const name = getContactDisplayName(contact);
|
const name = getContactDisplayName(contact);
|
||||||
const email = getContactPrimaryEmail(contact);
|
const email = getContactPrimaryEmail(contact);
|
||||||
const org = contact.organizations
|
const org = contact.organizations
|
||||||
? Object.values(contact.organizations)[0]?.name
|
? Object.values(contact.organizations)[0]?.name
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
|
const handleDragStart = useCallback((e: DragEvent<HTMLDivElement>) => {
|
||||||
|
// Drag all selected contacts if this one is selected, otherwise just this one
|
||||||
|
const ids = selectedContactIds.has(contact.id)
|
||||||
|
? Array.from(selectedContactIds)
|
||||||
|
: [contact.id];
|
||||||
|
|
||||||
|
e.dataTransfer.effectAllowed = "move";
|
||||||
|
e.dataTransfer.setData("application/x-contact-ids", JSON.stringify(ids));
|
||||||
|
e.dataTransfer.setData("text/plain", name || email || contact.id);
|
||||||
|
|
||||||
|
// Custom drag preview
|
||||||
|
const preview = document.createElement("div");
|
||||||
|
preview.style.cssText = `
|
||||||
|
position: fixed; top: -9999px; left: 0;
|
||||||
|
padding: 8px 16px; background-color: var(--color-primary, #3b82f6);
|
||||||
|
color: var(--color-primary-foreground, #ffffff); border-radius: 8px;
|
||||||
|
box-shadow: 0 4px 12px rgba(0,0,0,0.15); font-size: 14px; font-weight: 500;
|
||||||
|
z-index: 9999; white-space: nowrap; pointer-events: none;
|
||||||
|
`;
|
||||||
|
preview.textContent = ids.length === 1 ? (name || "1 contact") : `${ids.length} contacts`;
|
||||||
|
document.body.appendChild(preview);
|
||||||
|
e.dataTransfer.setDragImage(preview, 0, 0);
|
||||||
|
requestAnimationFrame(() => preview.remove());
|
||||||
|
}, [contact.id, name, email, selectedContactIds]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
draggable
|
||||||
|
onDragStart={handleDragStart}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
className={cn(
|
className={cn(
|
||||||
"w-full flex items-center cursor-pointer select-none transition-all duration-200 border-b border-border",
|
"w-full flex items-center cursor-pointer select-none transition-all duration-200 border-b border-border",
|
||||||
|
|||||||
@@ -193,6 +193,7 @@ export function ContactList({
|
|||||||
isChecked={selectedContactIds.has(contact.id)}
|
isChecked={selectedContactIds.has(contact.id)}
|
||||||
hasSelection={hasSelection}
|
hasSelection={hasSelection}
|
||||||
density={density}
|
density={density}
|
||||||
|
selectedContactIds={selectedContactIds}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
if (e.ctrlKey || e.metaKey) {
|
if (e.ctrlKey || e.metaKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -1,35 +1,93 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useMemo } from "react";
|
import { useMemo, useState, useCallback, useEffect, useRef, type DragEvent } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { BookUser, Users, Plus, UserPlus } from "lucide-react";
|
import { BookUser, Users, Plus, Share2, Book, ChevronRight, ChevronDown, UserPlus, UsersRound, Upload, Tag, Pencil, Trash2 } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { ContextMenu, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu";
|
||||||
|
import { useContextMenu } from "@/hooks/use-context-menu";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { ContactCard } from "@/lib/jmap/types";
|
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
|
||||||
import { getContactDisplayName } from "@/stores/contact-store";
|
import { getContactDisplayName } from "@/stores/contact-store";
|
||||||
|
|
||||||
export type ContactCategory = "all" | { groupId: string };
|
export type ContactCategory = "all" | { groupId: string } | { addressBookId: string } | { keyword: string };
|
||||||
|
|
||||||
interface ContactsSidebarProps {
|
interface ContactsSidebarProps {
|
||||||
groups: ContactCard[];
|
groups: ContactCard[];
|
||||||
individuals: ContactCard[];
|
individuals: ContactCard[];
|
||||||
|
addressBooks: AddressBook[];
|
||||||
activeCategory: ContactCategory;
|
activeCategory: ContactCategory;
|
||||||
onSelectCategory: (category: ContactCategory) => void;
|
onSelectCategory: (category: ContactCategory) => void;
|
||||||
onCreateGroup: () => void;
|
onCreateGroup: () => void;
|
||||||
onCreateContact: () => void;
|
onCreateContact: () => void;
|
||||||
|
onImport?: () => void;
|
||||||
|
onEditGroup?: (groupId: string) => void;
|
||||||
|
onDeleteGroup?: (groupId: string) => void;
|
||||||
|
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const COLLAPSED_KEY = "contacts-sidebar-collapsed";
|
||||||
|
|
||||||
|
function loadCollapsed(): Record<string, boolean> {
|
||||||
|
try {
|
||||||
|
const v = localStorage.getItem(COLLAPSED_KEY);
|
||||||
|
return v ? JSON.parse(v) : {};
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveCollapsed(state: Record<string, boolean>) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(COLLAPSED_KEY, JSON.stringify(state));
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
export function ContactsSidebar({
|
export function ContactsSidebar({
|
||||||
groups,
|
groups,
|
||||||
individuals,
|
individuals,
|
||||||
|
addressBooks,
|
||||||
activeCategory,
|
activeCategory,
|
||||||
onSelectCategory,
|
onSelectCategory,
|
||||||
onCreateGroup,
|
onCreateGroup,
|
||||||
onCreateContact,
|
onCreateContact,
|
||||||
|
onImport,
|
||||||
|
onEditGroup,
|
||||||
|
onDeleteGroup,
|
||||||
|
onDropContacts,
|
||||||
className,
|
className,
|
||||||
}: ContactsSidebarProps) {
|
}: ContactsSidebarProps) {
|
||||||
const t = useTranslations("contacts");
|
const t = useTranslations("contacts");
|
||||||
|
const { contextMenu: groupContextMenu, openContextMenu: openGroupContextMenu, closeContextMenu: closeGroupContextMenu, menuRef: groupMenuRef } = useContextMenu<ContactCard>();
|
||||||
|
|
||||||
|
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(loadCollapsed);
|
||||||
|
const [showMenu, setShowMenu] = useState(false);
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null);
|
||||||
|
const menuBtnRef = useRef<HTMLButtonElement>(null);
|
||||||
|
|
||||||
|
const toggleSection = useCallback((key: string) => {
|
||||||
|
setCollapsed(prev => {
|
||||||
|
const next = { ...prev, [key]: !prev[key] };
|
||||||
|
saveCollapsed(next);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Close dropdown on outside click
|
||||||
|
useEffect(() => {
|
||||||
|
if (!showMenu) return;
|
||||||
|
const handler = (e: MouseEvent) => {
|
||||||
|
if (
|
||||||
|
menuRef.current && !menuRef.current.contains(e.target as Node) &&
|
||||||
|
menuBtnRef.current && !menuBtnRef.current.contains(e.target as Node)
|
||||||
|
) {
|
||||||
|
setShowMenu(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("mousedown", handler);
|
||||||
|
return () => document.removeEventListener("mousedown", handler);
|
||||||
|
}, [showMenu]);
|
||||||
|
|
||||||
const sortedGroups = useMemo(() => {
|
const sortedGroups = useMemo(() => {
|
||||||
return [...groups].sort((a, b) =>
|
return [...groups].sort((a, b) =>
|
||||||
@@ -39,17 +97,126 @@ export function ContactsSidebar({
|
|||||||
|
|
||||||
const isAllActive = activeCategory === "all";
|
const isAllActive = activeCategory === "all";
|
||||||
|
|
||||||
|
// Group address books: personal vs shared accounts
|
||||||
|
const personalBooks = useMemo(() =>
|
||||||
|
addressBooks.filter(b => !b.isShared),
|
||||||
|
[addressBooks]);
|
||||||
|
|
||||||
|
const sharedBookGroups = useMemo(() => {
|
||||||
|
const map = new Map<string, { accountId: string; accountName: string; books: AddressBook[] }>();
|
||||||
|
for (const book of addressBooks) {
|
||||||
|
if (!book.isShared || !book.accountId) continue;
|
||||||
|
const existing = map.get(book.accountId);
|
||||||
|
if (existing) {
|
||||||
|
existing.books.push(book);
|
||||||
|
} else {
|
||||||
|
map.set(book.accountId, {
|
||||||
|
accountId: book.accountId,
|
||||||
|
accountName: book.accountName || book.accountId,
|
||||||
|
books: [book],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(map.values());
|
||||||
|
}, [addressBooks]);
|
||||||
|
|
||||||
|
// Count contacts per address book
|
||||||
|
const contactCountByBook = useMemo(() => {
|
||||||
|
const counts: Record<string, number> = {};
|
||||||
|
for (const contact of individuals) {
|
||||||
|
if (!contact.addressBookIds) continue;
|
||||||
|
for (const bookId of Object.keys(contact.addressBookIds)) {
|
||||||
|
if (!contact.addressBookIds[bookId]) continue;
|
||||||
|
counts[bookId] = (counts[bookId] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}, [individuals]);
|
||||||
|
|
||||||
|
// Auto-collect keywords from all contacts
|
||||||
|
const allKeywords = useMemo(() => {
|
||||||
|
const counts: Record<string, number> = {};
|
||||||
|
for (const contact of individuals) {
|
||||||
|
if (!contact.keywords) continue;
|
||||||
|
for (const [kw, active] of Object.entries(contact.keywords)) {
|
||||||
|
if (!active) continue;
|
||||||
|
counts[kw] = (counts[kw] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Object.entries(counts).sort(([a], [b]) => a.localeCompare(b));
|
||||||
|
}, [individuals]);
|
||||||
|
|
||||||
|
// Resolve actual group member counts against living contacts
|
||||||
|
const memberCountByGroup = useMemo(() => {
|
||||||
|
const counts: Record<string, number> = {};
|
||||||
|
for (const group of groups) {
|
||||||
|
if (!group.members) {
|
||||||
|
counts[group.id] = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const memberKeys = Object.keys(group.members).filter(k => group.members![k]);
|
||||||
|
const normalizedKeys = memberKeys.map(k => k.startsWith('urn:uuid:') ? k.slice(9) : k);
|
||||||
|
counts[group.id] = individuals.filter(c => {
|
||||||
|
if (memberKeys.includes(c.id) || normalizedKeys.includes(c.id)) return true;
|
||||||
|
if (c.uid) {
|
||||||
|
const bareUid = c.uid.startsWith('urn:uuid:') ? c.uid.slice(9) : c.uid;
|
||||||
|
return memberKeys.includes(c.uid) || normalizedKeys.includes(bareUid);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}).length;
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}, [groups, individuals]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col h-full bg-secondary", className)}>
|
<div className={cn("flex flex-col h-full bg-secondary", className)}>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="px-3 border-b border-border flex items-center justify-between" style={{ paddingBlock: 'var(--density-header-py)' }}>
|
<div className="px-3 border-b border-border flex items-center justify-between" style={{ paddingBlock: 'var(--density-header-py)' }}>
|
||||||
<span className="text-sm font-semibold truncate">{t("title")}</span>
|
<span className="text-sm font-semibold truncate">{t("title")}</span>
|
||||||
<Button size="icon" variant="ghost" onClick={onCreateContact} className="h-7 w-7 flex-shrink-0">
|
<div className="relative flex-shrink-0">
|
||||||
<UserPlus className="w-4 h-4" />
|
<Button
|
||||||
</Button>
|
ref={menuBtnRef}
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setShowMenu(v => !v)}
|
||||||
|
className="h-7 w-7"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
{showMenu && (
|
||||||
|
<div
|
||||||
|
ref={menuRef}
|
||||||
|
className="absolute right-0 top-full mt-1 w-44 rounded-md border border-border bg-background text-foreground shadow-md z-50 py-1"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
|
||||||
|
onClick={() => { setShowMenu(false); onCreateContact(); }}
|
||||||
|
>
|
||||||
|
<UserPlus className="w-4 h-4" />
|
||||||
|
{t("create_new")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
|
||||||
|
onClick={() => { setShowMenu(false); onCreateGroup(); }}
|
||||||
|
>
|
||||||
|
<UsersRound className="w-4 h-4" />
|
||||||
|
{t("groups.create")}
|
||||||
|
</button>
|
||||||
|
{onImport && (
|
||||||
|
<button
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
|
||||||
|
onClick={() => { setShowMenu(false); onImport(); }}
|
||||||
|
>
|
||||||
|
<Upload className="w-4 h-4" />
|
||||||
|
{t("import.title")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Categories */}
|
{/* Navigation */}
|
||||||
<div className="flex-1 overflow-y-auto py-1">
|
<div className="flex-1 overflow-y-auto py-1">
|
||||||
{/* All contacts */}
|
{/* All contacts */}
|
||||||
<button
|
<button
|
||||||
@@ -69,30 +236,63 @@ export function ContactsSidebar({
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Groups section */}
|
{/* My Address Books */}
|
||||||
{(sortedGroups.length > 0) && (
|
{personalBooks.length > 0 && (
|
||||||
<div className="mt-2">
|
<div className="mt-2">
|
||||||
<div className="flex items-center justify-between px-3 py-1">
|
<button
|
||||||
|
onClick={() => toggleSection("addressBooks")}
|
||||||
|
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
|
||||||
|
>
|
||||||
|
{collapsed.addressBooks ? (
|
||||||
|
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||||
|
{t("address_books.title")}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{!collapsed.addressBooks && personalBooks.map((book) => (
|
||||||
|
<AddressBookItem
|
||||||
|
key={book.id}
|
||||||
|
book={book}
|
||||||
|
isActive={typeof activeCategory === "object" && "addressBookId" in activeCategory && activeCategory.addressBookId === book.id}
|
||||||
|
contactCount={contactCountByBook[book.id] || 0}
|
||||||
|
onSelect={() => onSelectCategory({ addressBookId: book.id })}
|
||||||
|
onDropContacts={onDropContacts}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Groups section */}
|
||||||
|
{sortedGroups.length > 0 && (
|
||||||
|
<div className="mt-2">
|
||||||
|
<button
|
||||||
|
onClick={() => toggleSection("groups")}
|
||||||
|
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
|
||||||
|
>
|
||||||
|
{collapsed.groups ? (
|
||||||
|
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
||||||
|
)}
|
||||||
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||||
{t("tabs.groups")}
|
{t("tabs.groups")}
|
||||||
</span>
|
</span>
|
||||||
<Button size="icon" variant="ghost" onClick={onCreateGroup} className="h-5 w-5">
|
</button>
|
||||||
<Plus className="w-3 h-3" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{sortedGroups.map((group) => {
|
{!collapsed.groups && sortedGroups.map((group) => {
|
||||||
const isActive = typeof activeCategory === "object" && activeCategory.groupId === group.id;
|
const isActive = typeof activeCategory === "object" && "groupId" in activeCategory && activeCategory.groupId === group.id;
|
||||||
const memberCount = group.members
|
const memberCount = memberCountByGroup[group.id] || 0;
|
||||||
? Object.values(group.members).filter(Boolean).length
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={group.id}
|
key={group.id}
|
||||||
onClick={() => onSelectCategory({ groupId: group.id })}
|
onClick={() => onSelectCategory({ groupId: group.id })}
|
||||||
|
onContextMenu={(e) => openGroupContextMenu(e, group)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"w-full flex items-center gap-2 px-3 text-sm transition-colors",
|
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
|
||||||
isActive
|
isActive
|
||||||
? "bg-accent text-accent-foreground font-medium"
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
: "text-foreground/80 hover:bg-muted"
|
: "text-foreground/80 hover:bg-muted"
|
||||||
@@ -110,25 +310,172 @@ export function ContactsSidebar({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{sortedGroups.length === 0 && (
|
{/* Categories section (from contact keywords) */}
|
||||||
<div className="mt-2 px-3">
|
{allKeywords.length > 0 && (
|
||||||
<div className="flex items-center justify-between py-1">
|
<div className="mt-2">
|
||||||
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
<button
|
||||||
{t("tabs.groups")}
|
onClick={() => toggleSection("categories")}
|
||||||
</span>
|
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="ghost"
|
|
||||||
onClick={onCreateGroup}
|
|
||||||
className="w-full justify-start text-xs text-muted-foreground h-7"
|
|
||||||
>
|
>
|
||||||
<Plus className="w-3 h-3 mr-1.5" />
|
{collapsed.categories ? (
|
||||||
{t("groups.create")}
|
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
||||||
</Button>
|
) : (
|
||||||
|
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||||
|
{t("detail.categories")}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{!collapsed.categories && allKeywords.map(([keyword, count]) => {
|
||||||
|
const isActive = typeof activeCategory === "object" && "keyword" in activeCategory && activeCategory.keyword === keyword;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={keyword}
|
||||||
|
onClick={() => onSelectCategory({ keyword })}
|
||||||
|
className={cn(
|
||||||
|
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
|
||||||
|
isActive
|
||||||
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
|
: "text-foreground/80 hover:bg-muted"
|
||||||
|
)}
|
||||||
|
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
|
||||||
|
>
|
||||||
|
<Tag className="w-3.5 h-3.5 flex-shrink-0" />
|
||||||
|
<span className="truncate">{keyword}</span>
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
|
||||||
|
{count}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Shared accounts with address books */}
|
||||||
|
{sharedBookGroups.map((group) => (
|
||||||
|
<div key={group.accountId} className="mt-2">
|
||||||
|
<button
|
||||||
|
onClick={() => toggleSection(`shared-${group.accountId}`)}
|
||||||
|
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
|
||||||
|
>
|
||||||
|
{collapsed[`shared-${group.accountId}`] ? (
|
||||||
|
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
<Share2 className="w-3 h-3 text-muted-foreground" />
|
||||||
|
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider truncate">
|
||||||
|
{t("address_books.shared_prefix", { name: group.accountName })}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{!collapsed[`shared-${group.accountId}`] && group.books.map((book) => (
|
||||||
|
<AddressBookItem
|
||||||
|
key={book.id}
|
||||||
|
book={book}
|
||||||
|
isActive={typeof activeCategory === "object" && "addressBookId" in activeCategory && activeCategory.addressBookId === book.id}
|
||||||
|
contactCount={contactCountByBook[book.id] || 0}
|
||||||
|
onSelect={() => onSelectCategory({ addressBookId: book.id })}
|
||||||
|
onDropContacts={onDropContacts}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Group context menu */}
|
||||||
|
{groupContextMenu.data && (
|
||||||
|
<ContextMenu
|
||||||
|
ref={groupMenuRef}
|
||||||
|
isOpen={groupContextMenu.isOpen}
|
||||||
|
position={groupContextMenu.position}
|
||||||
|
onClose={closeGroupContextMenu}
|
||||||
|
>
|
||||||
|
<ContextMenuItem
|
||||||
|
icon={Pencil}
|
||||||
|
label={t("groups.edit")}
|
||||||
|
onClick={() => {
|
||||||
|
closeGroupContextMenu();
|
||||||
|
onEditGroup?.(groupContextMenu.data!.id);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<ContextMenuSeparator />
|
||||||
|
<ContextMenuItem
|
||||||
|
icon={Trash2}
|
||||||
|
label={t("form.delete")}
|
||||||
|
onClick={() => {
|
||||||
|
closeGroupContextMenu();
|
||||||
|
onDeleteGroup?.(groupContextMenu.data!.id);
|
||||||
|
}}
|
||||||
|
destructive
|
||||||
|
/>
|
||||||
|
</ContextMenu>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AddressBookItem({
|
||||||
|
book,
|
||||||
|
isActive,
|
||||||
|
contactCount,
|
||||||
|
onSelect,
|
||||||
|
onDropContacts,
|
||||||
|
}: {
|
||||||
|
book: AddressBook;
|
||||||
|
isActive: boolean;
|
||||||
|
contactCount: number;
|
||||||
|
onSelect: () => void;
|
||||||
|
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
|
||||||
|
}) {
|
||||||
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
|
|
||||||
|
const handleDragOver = useCallback((e: DragEvent<HTMLButtonElement>) => {
|
||||||
|
if (!e.dataTransfer.types.includes("application/x-contact-ids")) return;
|
||||||
|
e.preventDefault();
|
||||||
|
e.dataTransfer.dropEffect = "move";
|
||||||
|
setIsDragOver(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragLeave = useCallback(() => {
|
||||||
|
setIsDragOver(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDrop = useCallback((e: DragEvent<HTMLButtonElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(false);
|
||||||
|
const data = e.dataTransfer.getData("application/x-contact-ids");
|
||||||
|
if (!data || !onDropContacts) return;
|
||||||
|
try {
|
||||||
|
const contactIds = JSON.parse(data) as string[];
|
||||||
|
if (contactIds.length > 0) {
|
||||||
|
onDropContacts(contactIds, book);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore invalid data
|
||||||
|
}
|
||||||
|
}, [book, onDropContacts]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={onSelect}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
className={cn(
|
||||||
|
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
|
||||||
|
isActive
|
||||||
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
|
: "text-foreground/80 hover:bg-muted",
|
||||||
|
isDragOver && "bg-primary/20 ring-2 ring-primary/50"
|
||||||
|
)}
|
||||||
|
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
|
||||||
|
>
|
||||||
|
<Book className="w-4 h-4 flex-shrink-0" />
|
||||||
|
<span className="truncate">{book.name}</span>
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
|
||||||
|
{contactCount}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -360,6 +360,7 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
|
|||||||
const client = useAuthStore((s) => s.client);
|
const client = useAuthStore((s) => s.client);
|
||||||
const currentUserEmail = useAuthStore((s) => s.primaryIdentity?.email);
|
const currentUserEmail = useAuthStore((s) => s.primaryIdentity?.email);
|
||||||
const calendarInvitationParsingEnabled = useSettingsStore((s) => s.calendarInvitationParsingEnabled);
|
const calendarInvitationParsingEnabled = useSettingsStore((s) => s.calendarInvitationParsingEnabled);
|
||||||
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
const { calendars, supportsCalendar, importEvents, rsvpEvent, updateEvent, events: storeEvents, setSelectedDate } = useCalendarStore();
|
const { calendars, supportsCalendar, importEvents, rsvpEvent, updateEvent, events: storeEvents, setSelectedDate } = useCalendarStore();
|
||||||
|
|
||||||
const [state, setState] = useState<BannerState>('loading');
|
const [state, setState] = useState<BannerState>('loading');
|
||||||
@@ -544,6 +545,7 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
|
|||||||
dtStart: parsedEvent.start || undefined,
|
dtStart: parsedEvent.start || undefined,
|
||||||
dtEnd: summary?.end || undefined,
|
dtEnd: summary?.end || undefined,
|
||||||
timeZone: parsedEvent.timeZone || undefined,
|
timeZone: parsedEvent.timeZone || undefined,
|
||||||
|
isAllDay: parsedEvent.showWithoutTime || false,
|
||||||
sequence: parsedEvent.sequence,
|
sequence: parsedEvent.sequence,
|
||||||
status: imipStatus,
|
status: imipStatus,
|
||||||
});
|
});
|
||||||
@@ -659,16 +661,26 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isAllDayEvent = parsedEvent?.showWithoutTime ?? false;
|
||||||
|
|
||||||
const formatDateTime = (dateStr: string | null) => {
|
const formatDateTime = (dateStr: string | null) => {
|
||||||
if (!dateStr) return '';
|
if (!dateStr) return '';
|
||||||
const date = new Date(dateStr);
|
const date = new Date(dateStr);
|
||||||
if (isNaN(date.getTime())) return dateStr;
|
if (isNaN(date.getTime())) return dateStr;
|
||||||
|
if (isAllDayEvent) {
|
||||||
|
return format.dateTime(date, {
|
||||||
|
weekday: 'short',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
});
|
||||||
|
}
|
||||||
return format.dateTime(date, {
|
return format.dateTime(date, {
|
||||||
weekday: 'short',
|
weekday: 'short',
|
||||||
month: 'short',
|
month: 'short',
|
||||||
day: 'numeric',
|
day: 'numeric',
|
||||||
hour: 'numeric',
|
hour: 'numeric',
|
||||||
minute: '2-digit',
|
minute: '2-digit',
|
||||||
|
hour12: timeFormat === '12h',
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -5,13 +5,20 @@ import { useFocusTrap } from "@/hooks/use-focus-trap";
|
|||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
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 { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus } from "lucide-react";
|
import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus, ShieldCheck, Lock } from "lucide-react";
|
||||||
import { cn, formatFileSize } from "@/lib/utils";
|
import { cn, formatFileSize, formatDateTime } from "@/lib/utils";
|
||||||
import { debug } from "@/lib/debug";
|
import { debug } from "@/lib/debug";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import { sanitizeEmailHtml } from "@/lib/email-sanitization";
|
import { sanitizeEmailHtml } from "@/lib/email-sanitization";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
import { useIdentityStore } from "@/stores/identity-store";
|
import { useIdentityStore } from "@/stores/identity-store";
|
||||||
|
import { useSmimeStore } from "@/stores/smime-store";
|
||||||
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
import { buildMimeMessage, wrapCmsAsSmimeMessage } from "@/lib/smime/mime-builder";
|
||||||
|
import type { MimeAttachment } from "@/lib/smime/mime-builder";
|
||||||
|
import { smimeSign } from "@/lib/smime/smime-sign";
|
||||||
|
import { smimeEncrypt } from "@/lib/smime/smime-encrypt";
|
||||||
import { useContactStore } from "@/stores/contact-store";
|
import { useContactStore } from "@/stores/contact-store";
|
||||||
import { useTemplateStore } from "@/stores/template-store";
|
import { useTemplateStore } from "@/stores/template-store";
|
||||||
import { SubAddressHelper } from "@/components/identity/sub-address-helper";
|
import { SubAddressHelper } from "@/components/identity/sub-address-helper";
|
||||||
@@ -20,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;
|
||||||
@@ -48,6 +56,7 @@ interface EmailComposerProps {
|
|||||||
fromEmail?: string;
|
fromEmail?: string;
|
||||||
fromName?: string;
|
fromName?: string;
|
||||||
identityId?: string;
|
identityId?: string;
|
||||||
|
attachments?: Array<{ blobId: string; name: string; type: string; size: number }>;
|
||||||
}) => void | Promise<void>;
|
}) => void | Promise<void>;
|
||||||
onClose?: () => void;
|
onClose?: () => void;
|
||||||
onDiscardDraft?: (draftId: string) => void;
|
onDiscardDraft?: (draftId: string) => void;
|
||||||
@@ -80,6 +89,7 @@ export function EmailComposer({
|
|||||||
}: EmailComposerProps) {
|
}: EmailComposerProps) {
|
||||||
const t = useTranslations('email_composer');
|
const t = useTranslations('email_composer');
|
||||||
const tCommon = useTranslations('common');
|
const tCommon = useTranslations('common');
|
||||||
|
const timeFormat = useSettingsStore((state) => state.timeFormat);
|
||||||
|
|
||||||
// Initialize with reply/forward data if provided
|
// Initialize with reply/forward data if provided
|
||||||
const getInitialTo = () => {
|
const getInitialTo = () => {
|
||||||
@@ -118,7 +128,7 @@ export function EmailComposer({
|
|||||||
const prefix = initialDraftText || "";
|
const prefix = initialDraftText || "";
|
||||||
if (!replyTo?.body && !replyTo?.htmlBody) return prefix;
|
if (!replyTo?.body && !replyTo?.htmlBody) return prefix;
|
||||||
|
|
||||||
const date = replyTo.receivedAt ? new Date(replyTo.receivedAt).toLocaleString() : "";
|
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : "";
|
||||||
const from = replyTo.from?.[0];
|
const from = replyTo.from?.[0];
|
||||||
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
|
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
|
||||||
|
|
||||||
@@ -169,6 +179,11 @@ export function EmailComposer({
|
|||||||
const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false);
|
const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false);
|
||||||
const [showCloseDialog, setShowCloseDialog] = useState(false);
|
const [showCloseDialog, setShowCloseDialog] = useState(false);
|
||||||
const [showAllAttachments, setShowAllAttachments] = useState(false);
|
const [showAllAttachments, setShowAllAttachments] = useState(false);
|
||||||
|
const [smimeSign_, setSmimeSign] = useState(false);
|
||||||
|
const [smimeEncrypt_, setSmimeEncrypt] = useState(false);
|
||||||
|
const [smimePassphrasePrompt, setSmimePassphrasePrompt] = useState<{ keyId: string; resolve: (passphrase: string) => void; reject: () => void } | null>(null);
|
||||||
|
const [smimePassphraseInput, setSmimePassphraseInput] = useState('');
|
||||||
|
const [smimePassphraseError, setSmimePassphraseError] = useState('');
|
||||||
|
|
||||||
const saveTemplateModalRef = useFocusTrap({
|
const saveTemplateModalRef = useFocusTrap({
|
||||||
isActive: showSaveAsTemplate,
|
isActive: showSaveAsTemplate,
|
||||||
@@ -185,8 +200,43 @@ 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 smimeStore = useSmimeStore();
|
||||||
|
|
||||||
|
// Determine S/MIME availability for the selected identity
|
||||||
|
const currentSmimeIdentityId = selectedIdentityId || primaryIdentity?.id;
|
||||||
|
const smimeKeyRecord = currentSmimeIdentityId ? smimeStore.getKeyRecordForIdentity(currentSmimeIdentityId) : undefined;
|
||||||
|
const canSmimeSign = !!smimeKeyRecord;
|
||||||
|
const canSmimeEncrypt = (() => {
|
||||||
|
if (!smimeKeyRecord) return false;
|
||||||
|
const toAddrs = to.split(',').map(e => e.trim()).filter(Boolean);
|
||||||
|
const ccAddrs = cc.split(',').map(e => e.trim()).filter(Boolean);
|
||||||
|
const bccAddrs = bcc.split(',').map(e => e.trim()).filter(Boolean);
|
||||||
|
const allRecipients = [...toAddrs, ...ccAddrs, ...bccAddrs];
|
||||||
|
if (allRecipients.length === 0) return false;
|
||||||
|
const { missing } = smimeStore.getRecipientCerts(allRecipients);
|
||||||
|
return missing.length === 0;
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Initialize S/MIME defaults from store when identity changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (currentSmimeIdentityId) {
|
||||||
|
setSmimeSign(!!smimeStore.defaultSignIdentity[currentSmimeIdentityId] && canSmimeSign);
|
||||||
|
}
|
||||||
|
setSmimeEncrypt(smimeStore.defaultEncrypt && canSmimeEncrypt);
|
||||||
|
// Only run when identity changes, not on every recipient edit
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [currentSmimeIdentityId]);
|
||||||
|
|
||||||
// Keep a ref to current state for the unmount save
|
// Keep a ref to current state for the unmount save
|
||||||
const stateRef = useRef({ to, cc, bcc, subject, body, showCc, showBcc, selectedIdentityId, subAddressTag, draftId });
|
const stateRef = useRef({ to, cc, bcc, subject, body, showCc, showBcc, selectedIdentityId, subAddressTag, draftId });
|
||||||
@@ -486,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
|
||||||
@@ -608,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)
|
||||||
@@ -619,19 +661,43 @@ 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
|
||||||
|
if (replyTo && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
||||||
|
const originalText = replyTo.body || '';
|
||||||
|
if (originalText) {
|
||||||
|
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : '';
|
||||||
|
const fromAddr = replyTo.from?.[0];
|
||||||
|
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
|
||||||
|
|
||||||
|
if (mode === 'forward') {
|
||||||
|
finalBody += `\n\n---------- ${t('prefix.forward')} ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ''}\n\n${originalText}`;
|
||||||
|
} else {
|
||||||
|
finalBody += `\n\nOn ${date}, ${fromStr} wrote:\n> ${originalText.split('\n').join('\n> ')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build HTML body when replying/forwarding with original HTML content
|
// Build HTML signature block (prefer htmlSignature, fall back to escaped textSignature)
|
||||||
|
const buildSignatureHtml = (): string => {
|
||||||
|
if (currentIdentity?.htmlSignature) {
|
||||||
|
return `<br><br>-- <br>${sanitizeEmailHtml(currentIdentity.htmlSignature)}`;
|
||||||
|
}
|
||||||
|
if (currentIdentity?.textSignature) {
|
||||||
|
return `<br><br>-- <br>${currentIdentity.textSignature.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')}`;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
// Build HTML body
|
||||||
let finalHtmlBody: string | undefined;
|
let finalHtmlBody: string | undefined;
|
||||||
|
const signatureHtml = buildSignatureHtml();
|
||||||
|
|
||||||
if (replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
if (replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
||||||
|
// Reply/forward with original HTML content
|
||||||
const escapedBody = body.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>');
|
const escapedBody = body.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>');
|
||||||
const signatureHtml = currentIdentity?.textSignature
|
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : '';
|
||||||
? `<br><br>-- <br>${currentIdentity.textSignature.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')}`
|
|
||||||
: '';
|
|
||||||
const date = replyTo.receivedAt ? new Date(replyTo.receivedAt).toLocaleString() : '';
|
|
||||||
const fromAddr = replyTo.from?.[0];
|
const fromAddr = replyTo.from?.[0];
|
||||||
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
|
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
|
||||||
const quoteHeader = mode === 'forward'
|
const quoteHeader = mode === 'forward'
|
||||||
@@ -639,21 +705,129 @@ export function EmailComposer({
|
|||||||
: `On ${date}, ${fromStr} wrote:<br>`;
|
: `On ${date}, ${fromStr} wrote:<br>`;
|
||||||
|
|
||||||
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}<br><div><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote></div>`;
|
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}<br><div><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote></div>`;
|
||||||
|
} else if (signatureHtml) {
|
||||||
|
// New compose or plain-text reply — include HTML body with signature
|
||||||
|
const escapedBody = body.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>');
|
||||||
|
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await onSend?.({
|
// S/MIME send pipeline: build raw MIME → sign → encrypt → sendRawEmail
|
||||||
to: toAddresses,
|
if ((smimeSign_ || smimeEncrypt_) && client && currentIdentity?.id) {
|
||||||
cc: ccAddresses,
|
// 1. Resolve S/MIME key
|
||||||
bcc: bccAddresses,
|
if (smimeSign_ && !smimeKeyRecord) {
|
||||||
subject,
|
throw new Error('No S/MIME key bound to this identity');
|
||||||
body: finalBody,
|
}
|
||||||
htmlBody: finalHtmlBody,
|
|
||||||
draftId: finalDraftId || undefined,
|
// 2. Ensure key is unlocked for signing
|
||||||
fromEmail,
|
if (smimeSign_ && smimeKeyRecord && !smimeStore.isKeyUnlocked(smimeKeyRecord.id)) {
|
||||||
fromName: currentIdentity?.name || undefined,
|
const passphrase = await new Promise<string>((resolve, reject) => {
|
||||||
identityId: currentIdentity?.id,
|
setSmimePassphrasePrompt({ keyId: smimeKeyRecord.id, resolve, reject });
|
||||||
});
|
});
|
||||||
|
try {
|
||||||
|
await smimeStore.unlockKey(smimeKeyRecord.id, passphrase);
|
||||||
|
} finally {
|
||||||
|
setSmimePassphrasePrompt(null);
|
||||||
|
setSmimePassphraseInput('');
|
||||||
|
setSmimePassphraseError('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Resolve attachments as ArrayBuffers
|
||||||
|
const mimeAttachments: MimeAttachment[] = [];
|
||||||
|
for (const att of attachments) {
|
||||||
|
if (att.error || att.uploading) continue;
|
||||||
|
let content: ArrayBuffer;
|
||||||
|
if (att.file.size > 0) {
|
||||||
|
content = await att.file.arrayBuffer();
|
||||||
|
} else if (att.blobId && client) {
|
||||||
|
content = await client.fetchBlobArrayBuffer(att.blobId, att.file.name, att.file.type);
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
mimeAttachments.push({
|
||||||
|
filename: att.file.name,
|
||||||
|
contentType: att.file.type || 'application/octet-stream',
|
||||||
|
content,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Build canonical MIME
|
||||||
|
const mimeBytes = buildMimeMessage({
|
||||||
|
from: { name: currentIdentity.name || undefined, email: fromEmail || currentIdentity.email },
|
||||||
|
to: toAddresses.map(e => ({ email: e })),
|
||||||
|
cc: ccAddresses.length > 0 ? ccAddresses.map(e => ({ email: e })) : undefined,
|
||||||
|
bcc: bccAddresses.length > 0 ? bccAddresses.map(e => ({ email: e })) : undefined,
|
||||||
|
subject,
|
||||||
|
textBody: finalBody,
|
||||||
|
htmlBody: finalHtmlBody,
|
||||||
|
attachments: mimeAttachments.length > 0 ? mimeAttachments : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
let payload: Blob = new Blob([mimeBytes.buffer as ArrayBuffer], { type: 'message/rfc822' });
|
||||||
|
|
||||||
|
const smimeHeaders = {
|
||||||
|
from: { name: currentIdentity.name || undefined, email: fromEmail || currentIdentity.email },
|
||||||
|
to: toAddresses.map(e => ({ email: e })),
|
||||||
|
cc: ccAddresses.length > 0 ? ccAddresses.map(e => ({ email: e })) : undefined,
|
||||||
|
subject,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 5. Sign if enabled
|
||||||
|
if (smimeSign_ && smimeKeyRecord) {
|
||||||
|
const privateKey = smimeStore.getUnlockedKey(smimeKeyRecord.id);
|
||||||
|
if (!privateKey) throw new Error('S/MIME key is not unlocked');
|
||||||
|
const cmsBlob = await smimeSign(
|
||||||
|
mimeBytes,
|
||||||
|
privateKey,
|
||||||
|
smimeKeyRecord.certificate,
|
||||||
|
smimeKeyRecord.certificateChain || [],
|
||||||
|
);
|
||||||
|
const cmsBytes = new Uint8Array(await cmsBlob.arrayBuffer());
|
||||||
|
payload = wrapCmsAsSmimeMessage(cmsBytes, { ...smimeHeaders, smimeType: 'signed-data' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Encrypt if enabled
|
||||||
|
if (smimeEncrypt_ && smimeKeyRecord) {
|
||||||
|
const allRecipients = [...toAddresses, ...ccAddresses, ...bccAddresses];
|
||||||
|
const { found, missing } = smimeStore.getRecipientCerts(allRecipients);
|
||||||
|
if (missing.length > 0) {
|
||||||
|
throw new Error(`Missing certificates for: ${missing.join(', ')}`);
|
||||||
|
}
|
||||||
|
const recipientCertsDer = found.map(c => c.certificate instanceof ArrayBuffer ? c.certificate : new Uint8Array(c.certificate as ArrayBuffer).buffer);
|
||||||
|
const payloadBytes = new Uint8Array(await payload.arrayBuffer());
|
||||||
|
const cmsBlob = await smimeEncrypt(
|
||||||
|
payloadBytes,
|
||||||
|
recipientCertsDer,
|
||||||
|
smimeKeyRecord.certificate,
|
||||||
|
);
|
||||||
|
const cmsBytes = new Uint8Array(await cmsBlob.arrayBuffer());
|
||||||
|
payload = wrapCmsAsSmimeMessage(cmsBytes, { ...smimeHeaders, smimeType: 'enveloped-data' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. Send via raw email path
|
||||||
|
await sendRawEmail(client, payload, currentIdentity.id);
|
||||||
|
} else {
|
||||||
|
// Standard JMAP send path
|
||||||
|
// Collect uploaded attachment blobIds for the send request
|
||||||
|
const uploadedAttachments = attachments
|
||||||
|
.filter(att => att.blobId && !att.uploading && !att.error)
|
||||||
|
.map(att => ({ blobId: att.blobId!, name: att.file.name, type: att.file.type || 'application/octet-stream', size: att.file.size }));
|
||||||
|
|
||||||
|
await onSend?.({
|
||||||
|
to: toAddresses,
|
||||||
|
cc: ccAddresses,
|
||||||
|
bcc: bccAddresses,
|
||||||
|
subject,
|
||||||
|
body: finalBody,
|
||||||
|
htmlBody: finalHtmlBody,
|
||||||
|
draftId: finalDraftId || undefined,
|
||||||
|
fromEmail,
|
||||||
|
fromName: currentIdentity?.name || undefined,
|
||||||
|
identityId: currentIdentity?.id,
|
||||||
|
attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
setTo("");
|
setTo("");
|
||||||
setCc("");
|
setCc("");
|
||||||
@@ -950,13 +1124,20 @@ 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">
|
||||||
<div className="px-4 py-2 text-xs text-muted-foreground">
|
<div className="px-4 py-2 text-xs text-muted-foreground">
|
||||||
{mode === 'forward'
|
{mode === 'forward'
|
||||||
? `---------- ${t('prefix.forward')} ----------`
|
? `---------- ${t('prefix.forward')} ----------`
|
||||||
: `${replyTo.receivedAt ? new Date(replyTo.receivedAt).toLocaleString() : ''}, ${replyTo.from?.[0]?.name || replyTo.from?.[0]?.email || tCommon('unknown')}:`
|
: `${replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : ''}, ${replyTo.from?.[0]?.name || replyTo.from?.[0]?.email || tCommon('unknown')}:`
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -1059,6 +1240,32 @@ export function EmailComposer({
|
|||||||
>
|
>
|
||||||
<BookmarkPlus className="w-4 h-4" />
|
<BookmarkPlus className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* S/MIME toggles */}
|
||||||
|
{canSmimeSign && (
|
||||||
|
<>
|
||||||
|
<div className="w-px h-5 bg-border mx-1" />
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setSmimeSign(v => !v)}
|
||||||
|
className={cn("h-9 w-9", smimeSign_ && "bg-primary/10 text-primary")}
|
||||||
|
title={smimeSign_ ? t('smime_sign_on') : t('smime_sign_off')}
|
||||||
|
>
|
||||||
|
<ShieldCheck className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setSmimeEncrypt(v => !v)}
|
||||||
|
disabled={!canSmimeEncrypt}
|
||||||
|
className={cn("h-9 w-9", smimeEncrypt_ && "bg-primary/10 text-primary")}
|
||||||
|
title={smimeEncrypt_ ? t('smime_encrypt_on') : canSmimeEncrypt ? t('smime_encrypt_off') : t('smime_encrypt_unavailable')}
|
||||||
|
>
|
||||||
|
<Lock className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right side - Discard + Send (desktop) */}
|
{/* Right side - Discard + Send (desktop) */}
|
||||||
@@ -1117,6 +1324,60 @@ export function EmailComposer({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* S/MIME passphrase prompt */}
|
||||||
|
{smimePassphrasePrompt && (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-sm animate-in zoom-in-95 duration-200"
|
||||||
|
>
|
||||||
|
<div className="p-6">
|
||||||
|
<h2 className="text-lg font-semibold text-foreground">{t('smime_unlock_title')}</h2>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">{t('smime_unlock_message')}</p>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
autoFocus
|
||||||
|
value={smimePassphraseInput}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSmimePassphraseInput(e.target.value);
|
||||||
|
setSmimePassphraseError('');
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' && smimePassphraseInput) {
|
||||||
|
smimePassphrasePrompt.resolve(smimePassphraseInput);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder={t('smime_passphrase_placeholder')}
|
||||||
|
className="mt-3 w-full px-3 py-2 border border-border rounded-md text-sm bg-background text-foreground outline-none focus:ring-2 focus:ring-primary"
|
||||||
|
/>
|
||||||
|
{smimePassphraseError && (
|
||||||
|
<p className="mt-1 text-xs text-red-500">{smimePassphraseError}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-end gap-3 px-6 pb-6">
|
||||||
|
<Button variant="outline" onClick={() => {
|
||||||
|
smimePassphrasePrompt.reject();
|
||||||
|
setSmimePassphrasePrompt(null);
|
||||||
|
setSmimePassphraseInput('');
|
||||||
|
setSmimePassphraseError('');
|
||||||
|
}}>
|
||||||
|
{t('cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
disabled={!smimePassphraseInput}
|
||||||
|
onClick={() => smimePassphrasePrompt.resolve(smimePassphraseInput)}
|
||||||
|
>
|
||||||
|
{t('smime_unlock_button')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{showCloseDialog && (
|
{showCloseDialog && (
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150"
|
className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150"
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import {
|
|||||||
Folder,
|
Folder,
|
||||||
ShieldAlert,
|
ShieldAlert,
|
||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
|
EditIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
|
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
|
||||||
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
|
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
|
||||||
@@ -60,6 +61,7 @@ interface EmailContextMenuProps {
|
|||||||
onMoveToMailbox?: (mailboxId: string) => void;
|
onMoveToMailbox?: (mailboxId: string) => void;
|
||||||
onMarkAsSpam?: () => void;
|
onMarkAsSpam?: () => void;
|
||||||
onUndoSpam?: () => void;
|
onUndoSpam?: () => void;
|
||||||
|
onEditDraft?: () => void;
|
||||||
// Batch actions
|
// Batch actions
|
||||||
onBatchMarkAsRead?: (read: boolean) => void;
|
onBatchMarkAsRead?: (read: boolean) => void;
|
||||||
onBatchDelete?: () => void;
|
onBatchDelete?: () => void;
|
||||||
@@ -126,12 +128,14 @@ export function EmailContextMenu({
|
|||||||
onBatchMoveToMailbox,
|
onBatchMoveToMailbox,
|
||||||
onBatchMarkAsSpam,
|
onBatchMarkAsSpam,
|
||||||
onBatchUndoSpam,
|
onBatchUndoSpam,
|
||||||
|
onEditDraft,
|
||||||
}: EmailContextMenuProps) {
|
}: EmailContextMenuProps) {
|
||||||
const t = useTranslations("context_menu");
|
const t = useTranslations("context_menu");
|
||||||
const tColor = useTranslations("email_viewer.color_tag");
|
const tColor = useTranslations("email_viewer.color_tag");
|
||||||
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
|
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
|
||||||
const isUnread = !email.keywords?.$seen;
|
const isUnread = !email.keywords?.$seen;
|
||||||
const isStarred = email.keywords?.$flagged;
|
const isStarred = email.keywords?.$flagged;
|
||||||
|
const isDraft = email.keywords?.['$draft'] === true;
|
||||||
const currentColor = getCurrentColor(email.keywords);
|
const currentColor = getCurrentColor(email.keywords);
|
||||||
const showBatchActions = isMultiSelect && selectedCount > 1;
|
const showBatchActions = isMultiSelect && selectedCount > 1;
|
||||||
const isInJunkFolder = currentMailboxRole === 'junk';
|
const isInJunkFolder = currentMailboxRole === 'junk';
|
||||||
@@ -188,6 +192,18 @@ export function EmailContextMenu({
|
|||||||
</ContextMenuHeader>
|
</ContextMenuHeader>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Edit Draft - only for single draft emails */}
|
||||||
|
{!showBatchActions && isDraft && onEditDraft && (
|
||||||
|
<>
|
||||||
|
<ContextMenuItem
|
||||||
|
icon={EditIcon}
|
||||||
|
label={t("edit_draft")}
|
||||||
|
onClick={() => handleAction(onEditDraft)}
|
||||||
|
/>
|
||||||
|
<ContextMenuSeparator />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Single email actions - Reply, Reply All, Forward */}
|
{/* Single email actions - Reply, Reply All, Forward */}
|
||||||
{!showBatchActions && (
|
{!showBatchActions && (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ interface EmailListProps {
|
|||||||
onMoveToMailbox?: (emailId: string, mailboxId: string) => void;
|
onMoveToMailbox?: (emailId: string, mailboxId: string) => void;
|
||||||
onMarkAsSpam?: (email: Email) => void;
|
onMarkAsSpam?: (email: Email) => void;
|
||||||
onUndoSpam?: (email: Email) => void;
|
onUndoSpam?: (email: Email) => void;
|
||||||
|
onEditDraft?: (email: Email) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function EmailList({
|
export function EmailList({
|
||||||
@@ -57,6 +58,7 @@ export function EmailList({
|
|||||||
onMarkAsSpam,
|
onMarkAsSpam,
|
||||||
onUndoSpam,
|
onUndoSpam,
|
||||||
onMoveToMailbox,
|
onMoveToMailbox,
|
||||||
|
onEditDraft,
|
||||||
}: EmailListProps) {
|
}: EmailListProps) {
|
||||||
const t = useTranslations('email_list');
|
const t = useTranslations('email_list');
|
||||||
const { client } = useAuthStore();
|
const { client } = useAuthStore();
|
||||||
@@ -467,6 +469,7 @@ export function EmailList({
|
|||||||
onMoveToMailbox={(mailboxId) => onMoveToMailbox?.(contextMenu.data!.id, mailboxId)}
|
onMoveToMailbox={(mailboxId) => onMoveToMailbox?.(contextMenu.data!.id, mailboxId)}
|
||||||
onMarkAsSpam={() => onMarkAsSpam?.(contextMenu.data!)}
|
onMarkAsSpam={() => onMarkAsSpam?.(contextMenu.data!)}
|
||||||
onUndoSpam={() => onUndoSpam?.(contextMenu.data!)}
|
onUndoSpam={() => onUndoSpam?.(contextMenu.data!)}
|
||||||
|
onEditDraft={() => onEditDraft?.(contextMenu.data!)}
|
||||||
onBatchMarkAsRead={(read) => client && batchMarkAsRead(client, read)}
|
onBatchMarkAsRead={(read) => client && batchMarkAsRead(client, read)}
|
||||||
onBatchDelete={() => client && batchDelete(client)}
|
onBatchDelete={() => client && batchDelete(client)}
|
||||||
onBatchMoveToMailbox={(mailboxId) => client && batchMoveToMailbox(client, mailboxId)}
|
onBatchMoveToMailbox={(mailboxId) => client && batchMoveToMailbox(client, mailboxId)}
|
||||||
|
|||||||
+2042
-888
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,116 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
import { ShieldCheck, ShieldAlert, ShieldX, Lock, LockOpen, AlertTriangle, Info } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import type { SmimeStatus } from "@/lib/smime/types";
|
||||||
|
|
||||||
|
interface SmimeStatusBannerProps {
|
||||||
|
status: SmimeStatus;
|
||||||
|
onUnlockKey?: () => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SmimeStatusBanner({ status, onUnlockKey, className }: SmimeStatusBannerProps) {
|
||||||
|
const t = useTranslations('smime');
|
||||||
|
|
||||||
|
const items: Array<{
|
||||||
|
icon: React.ReactNode;
|
||||||
|
text: string;
|
||||||
|
variant: 'success' | 'warning' | 'error' | 'info';
|
||||||
|
}> = [];
|
||||||
|
|
||||||
|
// Encryption status
|
||||||
|
if (status.isEncrypted) {
|
||||||
|
if (status.decryptionError) {
|
||||||
|
if (status.decryptionError === 'locked') {
|
||||||
|
items.push({
|
||||||
|
icon: <Lock className="w-4 h-4" />,
|
||||||
|
text: t('unlock_key_desc'),
|
||||||
|
variant: 'warning',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
items.push({
|
||||||
|
icon: <ShieldX className="w-4 h-4" />,
|
||||||
|
text: t('status_encrypted_failed'),
|
||||||
|
variant: 'error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
items.push({
|
||||||
|
icon: <LockOpen className="w-4 h-4" />,
|
||||||
|
text: t('status_encrypted_ok'),
|
||||||
|
variant: 'success',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Signature status
|
||||||
|
if (status.isSigned) {
|
||||||
|
if (status.signatureValid === true) {
|
||||||
|
if (status.signerEmailMatch === false) {
|
||||||
|
items.push({
|
||||||
|
icon: <AlertTriangle className="w-4 h-4" />,
|
||||||
|
text: t('status_signed_mismatch'),
|
||||||
|
variant: 'warning',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
items.push({
|
||||||
|
icon: <ShieldCheck className="w-4 h-4" />,
|
||||||
|
text: t('status_signed_valid'),
|
||||||
|
variant: 'success',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if (status.signatureValid === false) {
|
||||||
|
items.push({
|
||||||
|
icon: <ShieldAlert className="w-4 h-4" />,
|
||||||
|
text: status.signatureError || t('status_signed_invalid'),
|
||||||
|
variant: 'error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unsupported S/MIME
|
||||||
|
if (status.unsupportedReason) {
|
||||||
|
items.push({
|
||||||
|
icon: <Info className="w-4 h-4" />,
|
||||||
|
text: t('status_unsupported'),
|
||||||
|
variant: 'info',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (items.length === 0) return null;
|
||||||
|
|
||||||
|
const variantStyles = {
|
||||||
|
success: 'bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800',
|
||||||
|
warning: 'bg-yellow-50 dark:bg-yellow-950/30 text-yellow-700 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800',
|
||||||
|
error: 'bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800',
|
||||||
|
info: 'bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("flex flex-col gap-1.5 py-1", className)}>
|
||||||
|
{items.map((item, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 px-3 py-1.5 rounded-md text-sm border",
|
||||||
|
variantStyles[item.variant],
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{item.icon}
|
||||||
|
<span className="flex-1">{item.text}</span>
|
||||||
|
{item.variant === 'warning' && status.decryptionError === 'locked' && onUnlockKey && (
|
||||||
|
<button
|
||||||
|
onClick={onUnlockKey}
|
||||||
|
className="text-xs font-medium underline hover:no-underline"
|
||||||
|
>
|
||||||
|
{t('unlock_key')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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";
|
||||||
@@ -225,6 +226,7 @@ function EmailCard({
|
|||||||
const resolvedTheme = useThemeStore((state) => state.resolvedTheme);
|
const resolvedTheme = useThemeStore((state) => state.resolvedTheme);
|
||||||
const density = useSettingsStore((state) => state.density);
|
const density = useSettingsStore((state) => state.density);
|
||||||
const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction);
|
const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction);
|
||||||
|
const emailAlwaysLightMode = useSettingsStore((state) => state.emailAlwaysLightMode);
|
||||||
const sender = email.from?.[0];
|
const sender = email.from?.[0];
|
||||||
const isUnread = !email.keywords?.$seen;
|
const isUnread = !email.keywords?.$seen;
|
||||||
const isStarred = email.keywords?.$flagged;
|
const isStarred = email.keywords?.$flagged;
|
||||||
@@ -315,7 +317,14 @@ function EmailCard({
|
|||||||
|
|
||||||
if (email.htmlBody?.[0]?.partId && email.bodyValues[email.htmlBody[0].partId]) {
|
if (email.htmlBody?.[0]?.partId && email.bodyValues[email.htmlBody[0].partId]) {
|
||||||
htmlContent = email.bodyValues[email.htmlBody[0].partId].value;
|
htmlContent = email.bodyValues[email.htmlBody[0].partId].value;
|
||||||
useHtmlVersion = !!htmlContent;
|
// Prefer textBody when HTML is auto-generated minimal wrapper (no rich formatting).
|
||||||
|
// 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];
|
||||||
|
if (hasTextBody && htmlContent) {
|
||||||
|
useHtmlVersion = hasMeaningfulHtmlBody(htmlContent);
|
||||||
|
} else {
|
||||||
|
useHtmlVersion = !!htmlContent;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (useHtmlVersion && htmlContent) {
|
if (useHtmlVersion && htmlContent) {
|
||||||
@@ -363,7 +372,7 @@ function EmailCard({
|
|||||||
node.setAttribute('rel', 'noopener noreferrer');
|
node.setAttribute('rel', 'noopener noreferrer');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (resolvedTheme === 'dark') {
|
if (resolvedTheme === 'dark' && !emailAlwaysLightMode) {
|
||||||
if (htmlNode.style) {
|
if (htmlNode.style) {
|
||||||
const originalStyles = htmlNode.style.cssText;
|
const originalStyles = htmlNode.style.cssText;
|
||||||
const transformedStyles = transformInlineStyles(originalStyles, 'dark');
|
const transformedStyles = transformInlineStyles(originalStyles, 'dark');
|
||||||
@@ -403,7 +412,6 @@ function EmailCard({
|
|||||||
.replace(/&/g, '&')
|
.replace(/&/g, '&')
|
||||||
.replace(/</g, '<')
|
.replace(/</g, '<')
|
||||||
.replace(/>/g, '>')
|
.replace(/>/g, '>')
|
||||||
.replace(/\n/g, '<br>')
|
|
||||||
.replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">$1</a>');
|
.replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">$1</a>');
|
||||||
return { html: htmlEscaped, isHtml: false };
|
return { html: htmlEscaped, isHtml: false };
|
||||||
}
|
}
|
||||||
@@ -411,11 +419,15 @@ function EmailCard({
|
|||||||
|
|
||||||
// Fallback to preview
|
// Fallback to preview
|
||||||
if (email.preview) {
|
if (email.preview) {
|
||||||
return { html: email.preview.replace(/\n/g, '<br>'), isHtml: false };
|
const previewHtml = email.preview
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>');
|
||||||
|
return { html: previewHtml, isHtml: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { html: "", isHtml: false };
|
return { html: "", isHtml: false };
|
||||||
}, [email, allowExternal, resolvedTheme, cidBlobUrls]);
|
}, [email, allowExternal, resolvedTheme, emailAlwaysLightMode, cidBlobUrls]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn(
|
<div className={cn(
|
||||||
@@ -513,12 +525,14 @@ function EmailCard({
|
|||||||
<div style={{ padding: 'var(--density-card-p)' }}>
|
<div style={{ padding: 'var(--density-card-p)' }}>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"prose prose-sm max-w-none dark:prose-invert",
|
"prose prose-sm max-w-none",
|
||||||
|
!emailAlwaysLightMode && "dark:prose-invert",
|
||||||
"prose-p:my-2 prose-headings:my-3",
|
"prose-p:my-2 prose-headings:my-3",
|
||||||
"prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
|
"prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
|
||||||
"[&_table]:border-collapse [&_td]:p-2 [&_th]:p-2",
|
"[&_table]:border-collapse [&_td]:p-2 [&_th]:p-2",
|
||||||
"[&_img]:max-w-full [&_img]:h-auto"
|
"[&_img]:max-w-full [&_img]:h-auto"
|
||||||
)}
|
)}
|
||||||
|
style={!emailContent.isHtml ? { whiteSpace: 'pre-wrap', fontFamily: 'ui-monospace, "SF Mono", Consolas, monospace', fontSize: '13px' } : undefined}
|
||||||
dangerouslySetInnerHTML={{ __html: emailContent.html }}
|
dangerouslySetInnerHTML={{ __html: emailContent.html }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react';
|
import { useEffect, useState, useCallback } from 'react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { X, Mail, Pencil, Trash2, Plus, AlertTriangle } from 'lucide-react';
|
import { X, Mail, Pencil, Trash2, Plus, AlertTriangle, Star } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
|
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
|
||||||
@@ -19,6 +19,12 @@ import { toast } from '@/stores/toast-store';
|
|||||||
import { useFocusTrap } from '@/hooks/use-focus-trap';
|
import { useFocusTrap } from '@/hooks/use-focus-trap';
|
||||||
import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
|
import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
|
||||||
|
|
||||||
|
function emailMatchesUsername(email: string, username: string): boolean {
|
||||||
|
if (email === username) return true;
|
||||||
|
if (!username.includes('@') && email.split('@')[0] === username) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
interface IdentityFormData {
|
interface IdentityFormData {
|
||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
@@ -38,7 +44,9 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
const tNotif = useTranslations('notifications');
|
const tNotif = useTranslations('notifications');
|
||||||
|
|
||||||
const client = useAuthStore((state) => state.client);
|
const client = useAuthStore((state) => state.client);
|
||||||
const { identities, addIdentity, updateIdentityLocal, removeIdentity } = useIdentityStore();
|
const identities = useIdentityStore((state) => state.identities);
|
||||||
|
const preferredPrimaryId = useIdentityStore((state) => state.preferredPrimaryId);
|
||||||
|
const setPreferredPrimary = useIdentityStore((state) => state.setPreferredPrimary);
|
||||||
const syncIdentities = useSyncIdentities();
|
const syncIdentities = useSyncIdentities();
|
||||||
|
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
@@ -46,6 +54,40 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
||||||
|
|
||||||
|
// Re-fetch all identities from server and update stores
|
||||||
|
const refreshIdentities = useCallback(async () => {
|
||||||
|
if (!client) return;
|
||||||
|
try {
|
||||||
|
const serverIdentities = await client.getIdentities();
|
||||||
|
const username = useAuthStore.getState().username;
|
||||||
|
const preferredPrimaryId = useIdentityStore.getState().preferredPrimaryId;
|
||||||
|
const sorted = [...serverIdentities].sort((a, b) => {
|
||||||
|
const aMatch = emailMatchesUsername(a.email, username || '');
|
||||||
|
const bMatch = emailMatchesUsername(b.email, username || '');
|
||||||
|
if (aMatch && !bMatch) return -1;
|
||||||
|
if (!aMatch && bMatch) return 1;
|
||||||
|
if (aMatch && bMatch) {
|
||||||
|
if (!a.mayDelete && b.mayDelete) return -1;
|
||||||
|
if (a.mayDelete && !b.mayDelete) return 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
// Move preferred primary to front if set
|
||||||
|
if (preferredPrimaryId) {
|
||||||
|
const idx = sorted.findIndex((id) => id.id === preferredPrimaryId);
|
||||||
|
if (idx > 0) {
|
||||||
|
const [preferred] = sorted.splice(idx, 1);
|
||||||
|
sorted.unshift(preferred);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
useIdentityStore.getState().setIdentities(sorted);
|
||||||
|
syncIdentities();
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : 'Failed to refresh identities';
|
||||||
|
toast.error(message);
|
||||||
|
}
|
||||||
|
}, [client, syncIdentities]);
|
||||||
|
|
||||||
// Focus trap with Escape handling
|
// Focus trap with Escape handling
|
||||||
const modalRef = useFocusTrap({
|
const modalRef = useFocusTrap({
|
||||||
isActive: isOpen,
|
isActive: isOpen,
|
||||||
@@ -60,9 +102,10 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
restoreFocus: true,
|
restoreFocus: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Close on click outside
|
// Close on click outside (but not when ConfirmDialog is open)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleClickOutside = (e: MouseEvent) => {
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (confirmDialogProps.isOpen) return;
|
||||||
if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
|
if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
|
||||||
onClose();
|
onClose();
|
||||||
}
|
}
|
||||||
@@ -72,13 +115,13 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
document.addEventListener('mousedown', handleClickOutside);
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||||
}
|
}
|
||||||
}, [isOpen, onClose, modalRef]);
|
}, [isOpen, onClose, modalRef, confirmDialogProps.isOpen]);
|
||||||
|
|
||||||
const handleCreate = useCallback(async (data: IdentityFormData) => {
|
const handleCreate = useCallback(async (data: IdentityFormData) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const newIdentity = await client.createIdentity(
|
await client.createIdentity(
|
||||||
data.name,
|
data.name,
|
||||||
data.email,
|
data.email,
|
||||||
data.replyTo,
|
data.replyTo,
|
||||||
@@ -87,8 +130,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
data.htmlSignature
|
data.htmlSignature
|
||||||
);
|
);
|
||||||
|
|
||||||
addIdentity(newIdentity);
|
await refreshIdentities();
|
||||||
syncIdentities();
|
|
||||||
setIsCreating(false);
|
setIsCreating(false);
|
||||||
toast.success(tNotif('identity_created'));
|
toast.success(tNotif('identity_created'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -96,7 +138,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
toast.error(tNotif('identity_create_failed', { error: message }));
|
toast.error(tNotif('identity_create_failed', { error: message }));
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}, [client, addIdentity, t, tNotif]);
|
}, [client, refreshIdentities, t, tNotif]);
|
||||||
|
|
||||||
const handleUpdate = useCallback(async (identity: Identity, data: IdentityFormData) => {
|
const handleUpdate = useCallback(async (identity: Identity, data: IdentityFormData) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
@@ -110,8 +152,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
htmlSignature: data.htmlSignature,
|
htmlSignature: data.htmlSignature,
|
||||||
});
|
});
|
||||||
|
|
||||||
updateIdentityLocal(identity.id, data);
|
await refreshIdentities();
|
||||||
syncIdentities();
|
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
toast.success(tNotif('identity_updated'));
|
toast.success(tNotif('identity_updated'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -119,7 +160,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
toast.error(tNotif('identity_update_failed', { error: message }));
|
toast.error(tNotif('identity_update_failed', { error: message }));
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}, [client, updateIdentityLocal, t, tNotif]);
|
}, [client, refreshIdentities, t, tNotif]);
|
||||||
|
|
||||||
const handleDelete = useCallback(async (identity: Identity) => {
|
const handleDelete = useCallback(async (identity: Identity) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
@@ -140,8 +181,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await client.deleteIdentity(identity.id);
|
await client.deleteIdentity(identity.id);
|
||||||
removeIdentity(identity.id);
|
await refreshIdentities();
|
||||||
syncIdentities();
|
|
||||||
toast.success(tNotif('identity_deleted'));
|
toast.success(tNotif('identity_deleted'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : t('validation_errors.unknown_error');
|
const message = error instanceof Error ? error.message : t('validation_errors.unknown_error');
|
||||||
@@ -149,7 +189,16 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
} finally {
|
} finally {
|
||||||
setDeletingId(null);
|
setDeletingId(null);
|
||||||
}
|
}
|
||||||
}, [client, removeIdentity, t, tNotif, confirmDialog]);
|
}, [client, refreshIdentities, t, tNotif, confirmDialog]);
|
||||||
|
|
||||||
|
const handleSetPrimary = useCallback((identity: Identity) => {
|
||||||
|
setPreferredPrimary(identity.id);
|
||||||
|
// Re-sort: move the preferred identity to the front
|
||||||
|
const reordered = [identity, ...identities.filter((id) => id.id !== identity.id)];
|
||||||
|
useIdentityStore.getState().setIdentities(reordered);
|
||||||
|
syncIdentities();
|
||||||
|
toast.success(tNotif('identity_set_primary'));
|
||||||
|
}, [identities, setPreferredPrimary, syncIdentities, tNotif]);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
@@ -264,6 +313,17 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
|
|||||||
|
|
||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
{identities[0]?.id !== identity.id && identities.length > 1 && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleSetPrimary(identity)}
|
||||||
|
disabled={!!editingId || isCreating}
|
||||||
|
title={t('set_as_primary')}
|
||||||
|
>
|
||||||
|
<Star className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ export function SubAddressHelper({
|
|||||||
<div
|
<div
|
||||||
ref={popoverRef}
|
ref={popoverRef}
|
||||||
className={cn(
|
className={cn(
|
||||||
'absolute top-full left-0 mt-1 z-50',
|
'absolute top-full right-0 mt-1 z-50',
|
||||||
'bg-background border border-border rounded-lg shadow-lg',
|
'bg-background border border-border rounded-lg shadow-lg',
|
||||||
'w-80 p-4 animate-in fade-in zoom-in-95 duration-150'
|
'w-80 p-4 animate-in fade-in zoom-in-95 duration-150'
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,273 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useRef, useEffect, useCallback } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { Check, Plus, LogOut, Star, ChevronDown, AlertCircle } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useAccountStore, type AccountEntry } from "@/stores/account-store";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { getInitials, MAX_ACCOUNTS } from "@/lib/account-utils";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useRouter } from "@/i18n/navigation";
|
||||||
|
|
||||||
|
interface AccountSwitcherProps {
|
||||||
|
/** "rail" = small avatar only (NavigationRail), "expanded" = avatar + name + email (Sidebar) */
|
||||||
|
variant?: "rail" | "expanded";
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccountAvatar({ account, size = "sm" }: { account: AccountEntry; size?: "sm" | "md" }) {
|
||||||
|
const initials = getInitials(account.displayName || account.label, account.email || account.username);
|
||||||
|
const sizeClasses = size === "sm" ? "w-8 h-8 text-xs" : "w-9 h-9 text-sm";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn("rounded-full flex items-center justify-center text-white font-medium flex-shrink-0", sizeClasses)}
|
||||||
|
style={{ backgroundColor: account.avatarColor }}
|
||||||
|
title={account.label}
|
||||||
|
>
|
||||||
|
{initials}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AccountSwitcher({ variant = "rail", className }: AccountSwitcherProps) {
|
||||||
|
const t = useTranslations("sidebar");
|
||||||
|
const router = useRouter();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||||
|
const popoverRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [popoverStyle, setPopoverStyle] = useState<React.CSSProperties>({});
|
||||||
|
|
||||||
|
const accounts = useAccountStore((s) => s.accounts);
|
||||||
|
const activeAccountId = useAccountStore((s) => s.activeAccountId);
|
||||||
|
const setDefaultAccount = useAccountStore((s) => s.setDefaultAccount);
|
||||||
|
const activeAccount = accounts.find((a) => a.id === activeAccountId);
|
||||||
|
const switchAccount = useAuthStore((s) => s.switchAccount);
|
||||||
|
const logout = useAuthStore((s) => s.logout);
|
||||||
|
const logoutAll = useAuthStore((s) => s.logoutAll);
|
||||||
|
const primaryIdentity = useAuthStore((s) => s.primaryIdentity);
|
||||||
|
|
||||||
|
const updatePosition = useCallback(() => {
|
||||||
|
if (!buttonRef.current) return;
|
||||||
|
const rect = buttonRef.current.getBoundingClientRect();
|
||||||
|
if (variant === "rail") {
|
||||||
|
setPopoverStyle({
|
||||||
|
position: "fixed",
|
||||||
|
left: rect.right + 8,
|
||||||
|
bottom: Math.max(8, window.innerHeight - rect.bottom),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setPopoverStyle({
|
||||||
|
position: "fixed",
|
||||||
|
left: rect.left,
|
||||||
|
top: rect.bottom + 4,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [variant]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
updatePosition();
|
||||||
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (
|
||||||
|
buttonRef.current?.contains(e.target as Node) ||
|
||||||
|
popoverRef.current?.contains(e.target as Node)
|
||||||
|
) return;
|
||||||
|
setOpen(false);
|
||||||
|
};
|
||||||
|
const handleEscape = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === "Escape") setOpen(false);
|
||||||
|
};
|
||||||
|
document.addEventListener("mousedown", handleClickOutside);
|
||||||
|
document.addEventListener("keydown", handleEscape);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousedown", handleClickOutside);
|
||||||
|
document.removeEventListener("keydown", handleEscape);
|
||||||
|
};
|
||||||
|
}, [open, updatePosition]);
|
||||||
|
|
||||||
|
const handleSwitch = async (accountId: string) => {
|
||||||
|
if (accountId === activeAccountId) return;
|
||||||
|
setOpen(false);
|
||||||
|
await switchAccount(accountId);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddAccount = () => {
|
||||||
|
setOpen(false);
|
||||||
|
router.push(`/login?mode=add-account` as never);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
setOpen(false);
|
||||||
|
logout();
|
||||||
|
if (useAccountStore.getState().accounts.length === 0) {
|
||||||
|
router.push("/login" as never);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogoutAll = () => {
|
||||||
|
setOpen(false);
|
||||||
|
logoutAll();
|
||||||
|
router.push("/login" as never);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSetDefault = (accountId: string) => {
|
||||||
|
setDefaultAccount(accountId);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Display name for the active account
|
||||||
|
const displayName = primaryIdentity?.name || activeAccount?.displayName || activeAccount?.label || "";
|
||||||
|
const displayEmail = primaryIdentity?.email || activeAccount?.email || activeAccount?.username || "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
ref={buttonRef}
|
||||||
|
onClick={() => setOpen(!open)}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 rounded-md transition-colors",
|
||||||
|
variant === "rail"
|
||||||
|
? "justify-center w-10 h-10 hover:bg-muted"
|
||||||
|
: "w-full px-2 py-1.5 hover:bg-muted text-left min-w-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
title={variant === "rail" ? (displayName || displayEmail) : undefined}
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-haspopup="true"
|
||||||
|
>
|
||||||
|
{activeAccount ? (
|
||||||
|
<>
|
||||||
|
<AccountAvatar account={activeAccount} size={variant === "rail" ? "sm" : "md"} />
|
||||||
|
{variant === "expanded" && (
|
||||||
|
<>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-medium text-foreground truncate">{displayName}</p>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{displayEmail}</p>
|
||||||
|
</div>
|
||||||
|
<ChevronDown className={cn("w-3.5 h-3.5 text-muted-foreground flex-shrink-0 transition-transform", open && "rotate-180")} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className={cn(
|
||||||
|
"rounded-full bg-muted flex items-center justify-center text-muted-foreground",
|
||||||
|
variant === "rail" ? "w-8 h-8 text-xs" : "w-9 h-9 text-sm"
|
||||||
|
)}>
|
||||||
|
?
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && createPortal(
|
||||||
|
<div
|
||||||
|
ref={popoverRef}
|
||||||
|
style={popoverStyle}
|
||||||
|
className="w-72 rounded-lg border border-border bg-background text-foreground shadow-lg z-50 overflow-hidden"
|
||||||
|
role="menu"
|
||||||
|
>
|
||||||
|
{/* Account List */}
|
||||||
|
<div className="py-1 max-h-64 overflow-y-auto">
|
||||||
|
{accounts.map((account) => {
|
||||||
|
const isActive = account.id === activeAccountId;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={account.id}
|
||||||
|
onClick={() => handleSwitch(account.id)}
|
||||||
|
className={cn(
|
||||||
|
"w-full flex items-start gap-3 px-3 py-2.5 text-left transition-colors",
|
||||||
|
isActive ? "bg-accent/50" : "hover:bg-muted"
|
||||||
|
)}
|
||||||
|
role="menuitem"
|
||||||
|
disabled={isActive}
|
||||||
|
>
|
||||||
|
<div className="relative flex-shrink-0">
|
||||||
|
<AccountAvatar account={account} size="md" />
|
||||||
|
{isActive && (
|
||||||
|
<div className="absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full bg-primary flex items-center justify-center">
|
||||||
|
<Check className="w-2.5 h-2.5 text-primary-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<span className="text-sm font-medium truncate">
|
||||||
|
{account.displayName || account.label}
|
||||||
|
</span>
|
||||||
|
{account.isDefault && (
|
||||||
|
<Star className="w-3 h-3 text-amber-500 flex-shrink-0 fill-amber-500" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">
|
||||||
|
{account.email || account.username}
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-1 mt-0.5">
|
||||||
|
{account.hasError ? (
|
||||||
|
<AlertCircle className="w-3 h-3 text-destructive" />
|
||||||
|
) : (
|
||||||
|
<span className={cn(
|
||||||
|
"w-1.5 h-1.5 rounded-full",
|
||||||
|
account.isConnected ? "bg-green-500" : "bg-muted-foreground/40"
|
||||||
|
)} />
|
||||||
|
)}
|
||||||
|
<span className="text-[10px] text-muted-foreground truncate">
|
||||||
|
{new URL(account.serverUrl).hostname}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Separator + Add Account */}
|
||||||
|
{accounts.length < MAX_ACCOUNTS && (
|
||||||
|
<div className="border-t border-border">
|
||||||
|
<button
|
||||||
|
onClick={handleAddAccount}
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-muted transition-colors"
|
||||||
|
role="menuitem"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
{t("add_account")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Separator + Actions */}
|
||||||
|
<div className="border-t border-border">
|
||||||
|
{activeAccount && !activeAccount.isDefault && accounts.length > 1 && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleSetDefault(activeAccount.id)}
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-muted transition-colors"
|
||||||
|
role="menuitem"
|
||||||
|
>
|
||||||
|
<Star className="w-4 h-4" />
|
||||||
|
{t("set_as_default")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-muted transition-colors"
|
||||||
|
role="menuitem"
|
||||||
|
>
|
||||||
|
<LogOut className="w-4 h-4" />
|
||||||
|
{t("sign_out_of", { account: displayEmail })}
|
||||||
|
</button>
|
||||||
|
{accounts.length > 1 && (
|
||||||
|
<button
|
||||||
|
onClick={handleLogoutAll}
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-destructive hover:bg-muted transition-colors"
|
||||||
|
role="menuitem"
|
||||||
|
>
|
||||||
|
<LogOut className="w-4 h-4" />
|
||||||
|
{t("sign_out_all")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useMemo, useRef, useEffect, useCallback } from 'react';
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { icons as lucideIcons, type LucideIcon } from 'lucide-react';
|
||||||
|
import { Search, X } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
|
||||||
|
// Curated list of commonly useful icons, organized by category
|
||||||
|
const POPULAR_ICONS = [
|
||||||
|
// Communication
|
||||||
|
'Globe', 'Rss', 'Radio', 'Podcast', 'MessageCircle', 'MessageSquare', 'MessagesSquare',
|
||||||
|
'Phone', 'Video', 'Webcam', 'Headphones', 'Mic',
|
||||||
|
// Productivity
|
||||||
|
'FileText', 'FileSpreadsheet', 'Notebook', 'BookOpen', 'ClipboardList',
|
||||||
|
'ListTodo', 'CheckSquare', 'SquareKanban', 'Kanban', 'Trello',
|
||||||
|
'PenLine', 'Pencil', 'Edit', 'NotebookPen',
|
||||||
|
// Dev / Tech
|
||||||
|
'Code', 'Terminal', 'Braces', 'Bug', 'Database', 'Server', 'Cpu',
|
||||||
|
'HardDrive', 'Monitor', 'Laptop', 'Smartphone', 'Tablet',
|
||||||
|
'Wifi', 'Cloud', 'CloudDownload', 'CloudUpload',
|
||||||
|
// Social / People
|
||||||
|
'Users', 'UserPlus', 'UserCircle', 'Contact', 'PersonStanding',
|
||||||
|
'Heart', 'ThumbsUp', 'Star', 'Award', 'Trophy', 'Crown',
|
||||||
|
// Media
|
||||||
|
'Image', 'Camera', 'Film', 'Music', 'Play', 'Tv', 'Youtube', 'Clapperboard',
|
||||||
|
'Palette', 'Paintbrush', 'Brush',
|
||||||
|
// Navigation / Location
|
||||||
|
'Map', 'MapPin', 'Navigation', 'Compass', 'Home', 'Building', 'Building2',
|
||||||
|
'Landmark', 'Store', 'Warehouse',
|
||||||
|
// Finance
|
||||||
|
'DollarSign', 'Euro', 'CreditCard', 'Wallet', 'Receipt', 'PiggyBank',
|
||||||
|
'TrendingUp', 'BarChart', 'BarChart3', 'LineChart', 'PieChart',
|
||||||
|
// Security
|
||||||
|
'Shield', 'ShieldCheck', 'Lock', 'Unlock', 'Key', 'Fingerprint', 'Eye',
|
||||||
|
// Science / Health
|
||||||
|
'Beaker', 'Atom', 'Dna', 'Microscope', 'Stethoscope', 'HeartPulse', 'Pill',
|
||||||
|
'Syringe', 'Thermometer',
|
||||||
|
// Nature
|
||||||
|
'Sun', 'Moon', 'CloudSun', 'Snowflake', 'Zap', 'Flame',
|
||||||
|
'TreePine', 'Flower', 'Leaf', 'Mountain', 'Waves',
|
||||||
|
// Tools
|
||||||
|
'Wrench', 'Hammer', 'Scissors', 'Ruler', 'Magnet',
|
||||||
|
'Package', 'Gift', 'Box', 'Archive',
|
||||||
|
// Transport
|
||||||
|
'Car', 'Bike', 'Bus', 'Train', 'Plane', 'Ship', 'Rocket',
|
||||||
|
// Food
|
||||||
|
'Coffee', 'Wine', 'Beer', 'Pizza', 'Apple', 'Cake', 'CookingPot',
|
||||||
|
// Misc
|
||||||
|
'Gamepad2', 'Dice5', 'Puzzle', 'Sparkles', 'Wand2', 'Bot', 'BrainCircuit',
|
||||||
|
'Lightbulb', 'Bookmark', 'Flag', 'Bell', 'Clock', 'Timer',
|
||||||
|
'Link', 'ExternalLink', 'QrCode', 'Scan', 'LayoutGrid', 'Layers',
|
||||||
|
'Aperture', 'CircleDot', 'Target', 'Crosshair',
|
||||||
|
];
|
||||||
|
|
||||||
|
interface IconPickerProps {
|
||||||
|
value: string;
|
||||||
|
onChange: (iconName: string) => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconPicker({ value, onChange, className }: IconPickerProps) {
|
||||||
|
const t = useTranslations('sidebar_apps');
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const [showAll, setShowAll] = useState(false);
|
||||||
|
const gridRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Get all available icon names
|
||||||
|
const allIconNames = useMemo(() => {
|
||||||
|
return Object.keys(lucideIcons).filter(
|
||||||
|
k => /^[A-Z]/.test(k) && k !== 'createLucideIcon' && k !== 'Icon'
|
||||||
|
).sort();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const filteredIcons = useMemo(() => {
|
||||||
|
const source = showAll ? allIconNames : POPULAR_ICONS.filter(name => name in lucideIcons);
|
||||||
|
if (!search.trim()) return source;
|
||||||
|
const q = search.toLowerCase();
|
||||||
|
return source.filter(name => name.toLowerCase().includes(q));
|
||||||
|
}, [search, showAll, allIconNames]);
|
||||||
|
|
||||||
|
const renderIcon = useCallback((name: string) => {
|
||||||
|
const IconComponent = lucideIcons[name as keyof typeof lucideIcons] as LucideIcon | undefined;
|
||||||
|
if (!IconComponent) return null;
|
||||||
|
return <IconComponent className="w-5 h-5" />;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('space-y-2', className)}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="relative flex-1">
|
||||||
|
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
placeholder={t('search_icons')}
|
||||||
|
className="pl-8 h-8 text-xs"
|
||||||
|
/>
|
||||||
|
{search && (
|
||||||
|
<button
|
||||||
|
onClick={() => setSearch('')}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
<X className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAll(!showAll)}
|
||||||
|
className={cn(
|
||||||
|
'text-xs px-2 py-1 rounded-md border transition-colors whitespace-nowrap',
|
||||||
|
showAll
|
||||||
|
? 'bg-primary/10 text-primary border-primary/30'
|
||||||
|
: 'bg-muted text-muted-foreground border-border hover:text-foreground'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{showAll ? t('show_popular') : t('show_all')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
ref={gridRef}
|
||||||
|
className="grid grid-cols-8 gap-1 max-h-[200px] overflow-y-auto p-1 border rounded-md bg-muted/30"
|
||||||
|
>
|
||||||
|
{filteredIcons.map(name => (
|
||||||
|
<button
|
||||||
|
key={name}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onChange(name)}
|
||||||
|
title={name}
|
||||||
|
className={cn(
|
||||||
|
'flex items-center justify-center w-8 h-8 rounded-md transition-colors',
|
||||||
|
value === name
|
||||||
|
? 'bg-primary text-primary-foreground'
|
||||||
|
: 'hover:bg-muted text-muted-foreground hover:text-foreground'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{renderIcon(name)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{filteredIcons.length === 0 && (
|
||||||
|
<p className="col-span-8 py-4 text-center text-xs text-muted-foreground">
|
||||||
|
{t('no_icons_found')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { X } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import type { InlineAppState } from '@/hooks/use-sidebar-apps';
|
||||||
|
|
||||||
|
interface InlineAppViewProps {
|
||||||
|
apps: InlineAppState[];
|
||||||
|
activeAppId: string;
|
||||||
|
onClose: () => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function InlineAppView({ apps, activeAppId, onClose, className }: InlineAppViewProps) {
|
||||||
|
const activeApp = apps.find((a) => a.id === activeAppId);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('flex flex-col h-full bg-background', className)}>
|
||||||
|
{/* Header bar */}
|
||||||
|
<div className="flex items-center justify-between px-4 py-2 border-b border-border bg-secondary/50 flex-shrink-0">
|
||||||
|
<h3 className="text-sm font-medium truncate">{activeApp?.name}</h3>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="p-1 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
|
||||||
|
aria-label="Close"
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/* Iframes - active one visible, rest hidden but alive */}
|
||||||
|
<div className="flex-1 relative">
|
||||||
|
{apps.map((app) => (
|
||||||
|
<iframe
|
||||||
|
key={app.id}
|
||||||
|
src={app.url}
|
||||||
|
title={app.name}
|
||||||
|
className={cn(
|
||||||
|
'absolute inset-0 w-full h-full border-0',
|
||||||
|
app.id !== activeAppId && 'hidden'
|
||||||
|
)}
|
||||||
|
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
|
||||||
|
referrerPolicy="no-referrer"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,12 +2,15 @@
|
|||||||
|
|
||||||
import { useState, useRef, useEffect, useCallback } from "react";
|
import { useState, useRef, useEffect, useCallback } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { Mail, Calendar, BookUser, HardDrive, Settings, LogOut, Keyboard } from "lucide-react";
|
import { Mail, Calendar, BookUser, HardDrive, Settings, LogOut, Keyboard, Plus } from "lucide-react";
|
||||||
|
import { AccountSwitcher } from "./account-switcher";
|
||||||
|
import { icons as lucideIcons, type LucideIcon } from "lucide-react";
|
||||||
import { usePathname, Link } from "@/i18n/navigation";
|
import { usePathname, Link } from "@/i18n/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { useWebDAVStore } from "@/stores/webdav-store";
|
import { useWebDAVStore } from "@/stores/webdav-store";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { cn, formatFileSize } from "@/lib/utils";
|
import { cn, formatFileSize } from "@/lib/utils";
|
||||||
|
|
||||||
interface NavItem {
|
interface NavItem {
|
||||||
@@ -27,6 +30,10 @@ interface NavigationRailProps {
|
|||||||
isPushConnected?: boolean;
|
isPushConnected?: boolean;
|
||||||
onLogout?: () => void;
|
onLogout?: () => void;
|
||||||
onShowShortcuts?: () => void;
|
onShowShortcuts?: () => void;
|
||||||
|
onManageApps?: () => void;
|
||||||
|
onInlineApp?: (appId: string, url: string, name: string) => void;
|
||||||
|
onCloseInlineApp?: () => void;
|
||||||
|
activeAppId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function StorageQuotaCircle({ quota, usagePercent }: { quota: { used: number; total: number }; usagePercent: number }) {
|
function StorageQuotaCircle({ quota, usagePercent }: { quota: { used: number; total: number }; usagePercent: number }) {
|
||||||
@@ -138,12 +145,17 @@ export function NavigationRail({
|
|||||||
isPushConnected,
|
isPushConnected,
|
||||||
onLogout,
|
onLogout,
|
||||||
onShowShortcuts,
|
onShowShortcuts,
|
||||||
|
onManageApps,
|
||||||
|
onInlineApp,
|
||||||
|
onCloseInlineApp,
|
||||||
|
activeAppId,
|
||||||
}: NavigationRailProps) {
|
}: NavigationRailProps) {
|
||||||
const t = useTranslations("sidebar");
|
const t = useTranslations("sidebar");
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { supportsCalendar } = useCalendarStore();
|
const { supportsCalendar } = useCalendarStore();
|
||||||
const { mailboxes } = useEmailStore();
|
const { mailboxes } = useEmailStore();
|
||||||
const { supportsWebDAV } = useWebDAVStore();
|
const { supportsWebDAV } = useWebDAVStore();
|
||||||
|
const sidebarApps = useSettingsStore((s) => s.sidebarApps);
|
||||||
const inboxUnread = mailboxes.find(m => m.role === "inbox")?.unreadEmails || 0;
|
const inboxUnread = mailboxes.find(m => m.role === "inbox")?.unreadEmails || 0;
|
||||||
|
|
||||||
const navItems: NavItem[] = [
|
const navItems: NavItem[] = [
|
||||||
@@ -151,12 +163,14 @@ export function NavigationRail({
|
|||||||
{ id: "calendar", icon: Calendar, labelKey: "calendar", href: "/calendar", hidden: !supportsCalendar },
|
{ id: "calendar", icon: Calendar, labelKey: "calendar", href: "/calendar", hidden: !supportsCalendar },
|
||||||
{ id: "contacts", icon: BookUser, labelKey: "contacts", href: "/contacts" },
|
{ id: "contacts", icon: BookUser, labelKey: "contacts", href: "/contacts" },
|
||||||
{ id: "files", icon: HardDrive, labelKey: "files", href: "/files", hidden: supportsWebDAV === false },
|
{ id: "files", icon: HardDrive, labelKey: "files", href: "/files", hidden: supportsWebDAV === false },
|
||||||
{ id: "settings", icon: Settings, labelKey: "settings", href: "/settings" },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const isSettingsActive = !activeAppId && pathname.startsWith("/settings");
|
||||||
|
|
||||||
const visibleItems = navItems.filter((item) => !item.hidden);
|
const visibleItems = navItems.filter((item) => !item.hidden);
|
||||||
|
|
||||||
const getIsActive = (href: string) => {
|
const getIsActive = (href: string) => {
|
||||||
|
if (activeAppId) return false;
|
||||||
if (href === "/") {
|
if (href === "/") {
|
||||||
return pathname === "/" || pathname === "";
|
return pathname === "/" || pathname === "";
|
||||||
}
|
}
|
||||||
@@ -177,6 +191,7 @@ export function NavigationRail({
|
|||||||
<Link
|
<Link
|
||||||
key={item.id}
|
key={item.id}
|
||||||
href={item.href}
|
href={item.href}
|
||||||
|
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]",
|
"flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]",
|
||||||
"transition-colors duration-150",
|
"transition-colors duration-150",
|
||||||
@@ -201,6 +216,52 @@ export function NavigationRail({
|
|||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
|
{/* Custom sidebar apps */}
|
||||||
|
{sidebarApps.map((app) => {
|
||||||
|
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
|
||||||
|
const isActive = activeAppId === app.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={app.id}
|
||||||
|
onClick={() => {
|
||||||
|
if (isActive) {
|
||||||
|
onCloseInlineApp?.();
|
||||||
|
} else if (app.openMode === 'tab') {
|
||||||
|
window.open(app.url, '_blank', 'noopener,noreferrer');
|
||||||
|
} else {
|
||||||
|
onInlineApp?.(app.id, app.url, app.name);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]",
|
||||||
|
"transition-colors duration-150",
|
||||||
|
isActive
|
||||||
|
? "text-primary"
|
||||||
|
: "text-muted-foreground hover:text-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="relative">
|
||||||
|
{AppIcon ? <AppIcon className="w-5 h-5" /> : null}
|
||||||
|
{isActive && (
|
||||||
|
<span className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-4 h-0.5 rounded-full bg-primary" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] font-medium leading-tight truncate max-w-[64px]">{app.name}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{/* Manage apps button */}
|
||||||
|
{onManageApps && (
|
||||||
|
<button
|
||||||
|
onClick={onManageApps}
|
||||||
|
className="flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px] transition-colors duration-150 text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
<Plus className="w-5 h-5" />
|
||||||
|
<span className="text-[10px] font-medium leading-tight">{t("add_app")}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -230,6 +291,7 @@ export function NavigationRail({
|
|||||||
<Link
|
<Link
|
||||||
key={item.id}
|
key={item.id}
|
||||||
href={item.href}
|
href={item.href}
|
||||||
|
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
|
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
|
||||||
collapsed
|
collapsed
|
||||||
@@ -257,13 +319,90 @@ export function NavigationRail({
|
|||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
|
{/* Custom sidebar apps */}
|
||||||
|
{sidebarApps.length > 0 && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"border-t",
|
||||||
|
collapsed ? "w-8 mx-auto my-1 pt-1" : "mx-2 my-0.5 pt-0.5"
|
||||||
|
)}
|
||||||
|
style={{ borderColor: 'rgba(128, 128, 128, 0.3)' }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{sidebarApps.map((app) => {
|
||||||
|
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
|
||||||
|
const isActive = activeAppId === app.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={app.id}
|
||||||
|
onClick={() => {
|
||||||
|
if (isActive) {
|
||||||
|
onCloseInlineApp?.();
|
||||||
|
} else if (app.openMode === 'tab') {
|
||||||
|
window.open(app.url, '_blank', 'noopener,noreferrer');
|
||||||
|
} else {
|
||||||
|
onInlineApp?.(app.id, app.url, app.name);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
|
||||||
|
collapsed
|
||||||
|
? "justify-center w-10 h-10"
|
||||||
|
: "px-2.5 text-sm",
|
||||||
|
"max-lg:min-h-[44px]",
|
||||||
|
isActive
|
||||||
|
? "bg-primary/10 text-primary font-medium"
|
||||||
|
: "text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||||
|
)}
|
||||||
|
title={collapsed ? app.name : undefined}
|
||||||
|
style={collapsed ? undefined : { paddingBlock: 'var(--density-sidebar-py)' }}
|
||||||
|
>
|
||||||
|
{AppIcon ? <AppIcon className={cn("w-[18px] h-[18px] flex-shrink-0", isActive && "text-primary")} /> : null}
|
||||||
|
{!collapsed && <span className="truncate">{app.name}</span>}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{/* Manage apps button */}
|
||||||
|
{onManageApps && (
|
||||||
|
<button
|
||||||
|
onClick={onManageApps}
|
||||||
|
className={cn(
|
||||||
|
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
|
||||||
|
collapsed
|
||||||
|
? "justify-center w-10 h-10"
|
||||||
|
: "px-2.5 text-sm",
|
||||||
|
"max-lg:min-h-[44px]",
|
||||||
|
"text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||||
|
)}
|
||||||
|
title={collapsed ? t("add_app") : undefined}
|
||||||
|
style={collapsed ? undefined : { paddingBlock: 'var(--density-sidebar-py)' }}
|
||||||
|
>
|
||||||
|
<Plus className="w-[18px] h-[18px] flex-shrink-0" />
|
||||||
|
{!collapsed && <span className="truncate">{t("add_app")}</span>}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Footer: Storage Quota + Sign Out + Push Status */}
|
{/* Footer: Settings + Help + Storage Quota + Sign Out + Push Status */}
|
||||||
<div className="mt-auto flex flex-col items-center gap-2 pb-3 px-1 border-t border-border pt-2">
|
<div className="mt-auto flex flex-col items-center gap-2 pb-3 px-1">
|
||||||
{quota && quota.total > 0 && (
|
<Link
|
||||||
<StorageQuotaCircle quota={quota} usagePercent={quotaUsagePercent} />
|
href="/settings"
|
||||||
)}
|
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-center w-10 h-10 rounded-md transition-colors",
|
||||||
|
isSettingsActive
|
||||||
|
? "bg-primary/10 text-primary"
|
||||||
|
: "text-muted-foreground hover:text-foreground hover:bg-muted"
|
||||||
|
)}
|
||||||
|
title={t("settings")}
|
||||||
|
aria-current={isSettingsActive ? "page" : undefined}
|
||||||
|
>
|
||||||
|
<Settings className="w-[18px] h-[18px]" />
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="w-8 border-t" style={{ borderColor: 'rgba(128, 128, 128, 0.3)' }} />
|
||||||
|
|
||||||
{onShowShortcuts && (
|
{onShowShortcuts && (
|
||||||
<button
|
<button
|
||||||
@@ -275,6 +414,10 @@ export function NavigationRail({
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{quota && quota.total > 0 && (
|
||||||
|
<StorageQuotaCircle quota={quota} usagePercent={quotaUsagePercent} />
|
||||||
|
)}
|
||||||
|
|
||||||
{isPushConnected != null && (
|
{isPushConnected != null && (
|
||||||
<span
|
<span
|
||||||
className="relative group"
|
className="relative group"
|
||||||
@@ -290,13 +433,7 @@ export function NavigationRail({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{onLogout && (
|
{onLogout && (
|
||||||
<button
|
<AccountSwitcher variant="rail" />
|
||||||
onClick={onLogout}
|
|
||||||
className="flex items-center justify-center w-10 h-10 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
|
|
||||||
title={t("sign_out")}
|
|
||||||
>
|
|
||||||
<LogOut className="w-[18px] h-[18px]" />
|
|
||||||
</button>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,355 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { X, Plus, Pencil, Trash2, GripVertical, ExternalLink, PanelRight } from 'lucide-react';
|
||||||
|
import { icons as lucideIcons, type LucideIcon } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { IconPicker } from './icon-picker';
|
||||||
|
import { useSettingsStore, type SidebarApp } from '@/stores/settings-store';
|
||||||
|
import { useFocusTrap } from '@/hooks/use-focus-trap';
|
||||||
|
import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
|
||||||
|
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
|
||||||
|
|
||||||
|
interface SidebarAppFormData {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
icon: string;
|
||||||
|
openMode: 'tab' | 'inline';
|
||||||
|
}
|
||||||
|
|
||||||
|
function SidebarAppForm({
|
||||||
|
app,
|
||||||
|
onSave,
|
||||||
|
onCancel,
|
||||||
|
}: {
|
||||||
|
app?: SidebarApp;
|
||||||
|
onSave: (data: SidebarAppFormData) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}) {
|
||||||
|
const t = useTranslations('sidebar_apps');
|
||||||
|
const isEditing = !!app;
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<SidebarAppFormData>({
|
||||||
|
name: app?.name || '',
|
||||||
|
url: app?.url || '',
|
||||||
|
icon: app?.icon || 'Globe',
|
||||||
|
openMode: app?.openMode || 'tab',
|
||||||
|
});
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
const validate = (): boolean => {
|
||||||
|
const newErrors: Record<string, string> = {};
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
newErrors.name = t('name_required');
|
||||||
|
}
|
||||||
|
if (!formData.url.trim()) {
|
||||||
|
newErrors.url = t('url_required');
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(formData.url);
|
||||||
|
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
||||||
|
newErrors.url = t('url_invalid');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
newErrors.url = t('url_invalid');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!formData.icon) {
|
||||||
|
newErrors.icon = t('icon_required');
|
||||||
|
}
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!validate()) return;
|
||||||
|
onSave(formData);
|
||||||
|
};
|
||||||
|
|
||||||
|
const SelectedIcon = formData.icon
|
||||||
|
? (lucideIcons[formData.icon as keyof typeof lucideIcons] as LucideIcon | undefined)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{/* Name */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="app-name" className="block text-sm font-medium mb-1">
|
||||||
|
{t('name_label')} <span className="text-destructive">*</span>
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="app-name"
|
||||||
|
type="text"
|
||||||
|
maxLength={50}
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||||
|
placeholder={t('name_placeholder')}
|
||||||
|
className={errors.name ? 'border-destructive' : ''}
|
||||||
|
/>
|
||||||
|
{errors.name && (
|
||||||
|
<p className="text-sm text-destructive mt-1">{errors.name}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* URL */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="app-url" className="block text-sm font-medium mb-1">
|
||||||
|
{t('url_label')} <span className="text-destructive">*</span>
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="app-url"
|
||||||
|
type="url"
|
||||||
|
maxLength={2048}
|
||||||
|
value={formData.url}
|
||||||
|
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
|
||||||
|
placeholder="https://example.com"
|
||||||
|
className={errors.url ? 'border-destructive' : ''}
|
||||||
|
/>
|
||||||
|
{errors.url && (
|
||||||
|
<p className="text-sm text-destructive mt-1">{errors.url}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Open Mode */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">{t('open_mode_label')}</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData({ ...formData, openMode: 'tab' })}
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors flex-1',
|
||||||
|
formData.openMode === 'tab'
|
||||||
|
? 'bg-primary/10 border-primary/30 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<ExternalLink className="w-4 h-4" />
|
||||||
|
{t('open_new_tab')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData({ ...formData, openMode: 'inline' })}
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors flex-1',
|
||||||
|
formData.openMode === 'inline'
|
||||||
|
? 'bg-primary/10 border-primary/30 text-primary'
|
||||||
|
: 'border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<PanelRight className="w-4 h-4" />
|
||||||
|
{t('open_inline')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Icon Picker */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
{t('icon_label')} <span className="text-destructive">*</span>
|
||||||
|
{SelectedIcon && (
|
||||||
|
<span className="inline-flex items-center gap-1.5 ml-2 text-muted-foreground font-normal">
|
||||||
|
— <SelectedIcon className="w-4 h-4" /> {formData.icon}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
<IconPicker
|
||||||
|
value={formData.icon}
|
||||||
|
onChange={(icon) => setFormData({ ...formData, icon })}
|
||||||
|
/>
|
||||||
|
{errors.icon && (
|
||||||
|
<p className="text-sm text-destructive mt-1">{errors.icon}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<Button type="button" variant="outline" onClick={onCancel}>
|
||||||
|
{t('cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit">
|
||||||
|
{isEditing ? t('update') : t('add')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SidebarAppsModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SidebarAppsModal({ isOpen, onClose }: SidebarAppsModalProps) {
|
||||||
|
const t = useTranslations('sidebar_apps');
|
||||||
|
const { sidebarApps, addSidebarApp, updateSidebarApp, removeSidebarApp } = useSettingsStore();
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [isCreating, setIsCreating] = useState(false);
|
||||||
|
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
||||||
|
|
||||||
|
const modalRef = useFocusTrap({
|
||||||
|
isActive: isOpen,
|
||||||
|
onEscape: () => {
|
||||||
|
if (isCreating || editingId) {
|
||||||
|
setIsCreating(false);
|
||||||
|
setEditingId(null);
|
||||||
|
} else {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
restoreFocus: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleCreate = useCallback((data: SidebarAppFormData) => {
|
||||||
|
const id = `app-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||||||
|
addSidebarApp({ id, ...data });
|
||||||
|
setIsCreating(false);
|
||||||
|
}, [addSidebarApp]);
|
||||||
|
|
||||||
|
const handleUpdate = useCallback((id: string, data: SidebarAppFormData) => {
|
||||||
|
updateSidebarApp(id, data);
|
||||||
|
setEditingId(null);
|
||||||
|
}, [updateSidebarApp]);
|
||||||
|
|
||||||
|
const handleDelete = useCallback(async (app: SidebarApp) => {
|
||||||
|
const confirmed = await confirmDialog({
|
||||||
|
title: t('delete_confirm_title'),
|
||||||
|
message: t('delete_confirm', { name: app.name }),
|
||||||
|
confirmText: t('delete'),
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
if (!confirmed) return;
|
||||||
|
removeSidebarApp(app.id);
|
||||||
|
}, [removeSidebarApp, confirmDialog, t]);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-50 p-4 animate-in fade-in duration-150">
|
||||||
|
<div
|
||||||
|
ref={modalRef}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="sidebar-apps-modal-title"
|
||||||
|
className={cn(
|
||||||
|
'bg-background border border-border rounded-lg shadow-xl',
|
||||||
|
'w-full max-w-2xl max-h-[90vh] overflow-hidden',
|
||||||
|
'animate-in zoom-in-95 duration-200'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between px-6 py-4 border-b border-border">
|
||||||
|
<h2 id="sidebar-apps-modal-title" className="text-lg font-semibold text-foreground">
|
||||||
|
{t('modal_title')}
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
<X className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="p-6 overflow-y-auto max-h-[calc(90vh-80px)]">
|
||||||
|
{/* Create form */}
|
||||||
|
{isCreating && (
|
||||||
|
<div className="mb-6 p-4 border border-border rounded-lg bg-muted/30">
|
||||||
|
<h3 className="text-sm font-semibold mb-4">{t('add_new')}</h3>
|
||||||
|
<SidebarAppForm
|
||||||
|
onSave={handleCreate}
|
||||||
|
onCancel={() => setIsCreating(false)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Add button */}
|
||||||
|
{!isCreating && !editingId && (
|
||||||
|
<Button
|
||||||
|
onClick={() => setIsCreating(true)}
|
||||||
|
className="mb-6 w-full sm:w-auto"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
|
{t('add_new')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Apps list */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
{sidebarApps.map((app) => {
|
||||||
|
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
|
||||||
|
|
||||||
|
if (editingId === app.id) {
|
||||||
|
return (
|
||||||
|
<div key={app.id} className="p-4 border border-border rounded-lg bg-muted/30">
|
||||||
|
<h3 className="text-sm font-semibold mb-4">{t('edit_app')}</h3>
|
||||||
|
<SidebarAppForm
|
||||||
|
app={app}
|
||||||
|
onSave={(data) => handleUpdate(app.id, data)}
|
||||||
|
onCancel={() => setEditingId(null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={app.id}
|
||||||
|
className="flex items-center gap-3 p-3 border border-border rounded-lg"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-center w-9 h-9 rounded-md bg-muted">
|
||||||
|
{AppIcon ? <AppIcon className="w-5 h-5 text-muted-foreground" /> : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="font-medium text-sm truncate">{app.name}</p>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{app.url}</p>
|
||||||
|
</div>
|
||||||
|
<span className={cn(
|
||||||
|
'text-[10px] px-1.5 py-0.5 rounded-full font-medium',
|
||||||
|
app.openMode === 'inline'
|
||||||
|
? 'bg-blue-100 text-blue-700 dark:bg-blue-950/40 dark:text-blue-400'
|
||||||
|
: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400'
|
||||||
|
)}>
|
||||||
|
{app.openMode === 'inline' ? t('inline_badge') : t('tab_badge')}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setEditingId(app.id)}
|
||||||
|
disabled={!!editingId || isCreating}
|
||||||
|
>
|
||||||
|
<Pencil className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDelete(app)}
|
||||||
|
disabled={!!editingId || isCreating}
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{sidebarApps.length === 0 && !isCreating && (
|
||||||
|
<div className="text-center py-12 text-muted-foreground">
|
||||||
|
<Plus className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||||
|
<p className="text-sm">{t('no_apps')}</p>
|
||||||
|
<p className="text-xs mt-1">{t('no_apps_hint')}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ConfirmDialog {...confirmDialogProps} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -37,6 +37,9 @@ import { useSettingsStore, KEYWORD_PALETTE, KeywordDefinition } from "@/stores/s
|
|||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import { debug } from "@/lib/debug";
|
import { debug } from "@/lib/debug";
|
||||||
|
import { useConfig } from "@/hooks/use-config";
|
||||||
|
import { useThemeStore } from "@/stores/theme-store";
|
||||||
|
import { AccountSwitcher } from "./account-switcher";
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
mailboxes: Mailbox[];
|
mailboxes: Mailbox[];
|
||||||
@@ -361,6 +364,8 @@ export function Sidebar({
|
|||||||
}: SidebarProps) {
|
}: SidebarProps) {
|
||||||
const { sidebarCollapsed: isCollapsed, toggleSidebarCollapsed } = useUIStore();
|
const { sidebarCollapsed: isCollapsed, toggleSidebarCollapsed } = useUIStore();
|
||||||
const { primaryIdentity } = useAuthStore();
|
const { primaryIdentity } = useAuthStore();
|
||||||
|
const { appLogoLightUrl, appLogoDarkUrl } = useConfig();
|
||||||
|
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
|
||||||
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
|
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
|
||||||
const [tagsExpanded, setTagsExpanded] = useState(() => {
|
const [tagsExpanded, setTagsExpanded] = useState(() => {
|
||||||
try {
|
try {
|
||||||
@@ -460,6 +465,17 @@ export function Sidebar({
|
|||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{(() => {
|
||||||
|
const logoUrl = resolvedTheme === 'dark' ? (appLogoDarkUrl || appLogoLightUrl) : (appLogoLightUrl || appLogoDarkUrl);
|
||||||
|
return logoUrl ? (
|
||||||
|
<img
|
||||||
|
src={logoUrl}
|
||||||
|
alt=""
|
||||||
|
className={cn("object-contain flex-shrink-0", isCollapsed ? "w-6 h-6" : "w-6 h-6")}
|
||||||
|
/>
|
||||||
|
) : null;
|
||||||
|
})()}
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
@@ -470,15 +486,8 @@ export function Sidebar({
|
|||||||
{isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />}
|
{isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{!isCollapsed && primaryIdentity && (
|
{!isCollapsed && (
|
||||||
<div className="min-w-0">
|
<AccountSwitcher variant="expanded" className="flex-1" />
|
||||||
<p className="text-sm font-medium text-foreground truncate" title={primaryIdentity.name}>
|
|
||||||
{primaryIdentity.name}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground truncate" title={primaryIdentity.email}>
|
|
||||||
{primaryIdentity.email}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -7,9 +7,10 @@ import { useAuthStore } from '@/stores/auth-store';
|
|||||||
import { toast } from '@/stores/toast-store';
|
import { toast } from '@/stores/toast-store';
|
||||||
import { SettingsSection } from './settings-section';
|
import { SettingsSection } from './settings-section';
|
||||||
import { Plus, Pencil, Trash2, Check, X, Calendar as CalendarIcon, Copy, Link, Upload, Globe, RefreshCw, Eraser } from 'lucide-react';
|
import { Plus, Pencil, Trash2, Check, X, Calendar as CalendarIcon, Copy, Link, Upload, Globe, RefreshCw, Eraser } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn, formatDateTime } from '@/lib/utils';
|
||||||
import { ICalImportModal } from '@/components/calendar/ical-import-modal';
|
import { ICalImportModal } from '@/components/calendar/ical-import-modal';
|
||||||
import { ICalSubscriptionModal } from '@/components/calendar/ical-subscription-modal';
|
import { ICalSubscriptionModal } from '@/components/calendar/ical-subscription-modal';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
|
||||||
const CALENDAR_COLORS = [
|
const CALENDAR_COLORS = [
|
||||||
"#3b82f6", // blue
|
"#3b82f6", // blue
|
||||||
@@ -152,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);
|
||||||
@@ -164,6 +168,7 @@ export function CalendarManagementSettings() {
|
|||||||
const [refreshingSubId, setRefreshingSubId] = useState<string | null>(null);
|
const [refreshingSubId, setRefreshingSubId] = useState<string | null>(null);
|
||||||
const tImport = useTranslations('calendar.import');
|
const tImport = useTranslations('calendar.import');
|
||||||
const tSub = useTranslations('calendar.subscription');
|
const tSub = useTranslations('calendar.subscription');
|
||||||
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
const colorPickerRef = useRef<HTMLDivElement>(null);
|
const colorPickerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
// Load calendars if not yet loaded
|
// Load calendars if not yet loaded
|
||||||
@@ -173,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);
|
||||||
@@ -293,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/calendars/user/${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) => {
|
||||||
@@ -563,7 +624,7 @@ export function CalendarManagementSettings() {
|
|||||||
</span>
|
</span>
|
||||||
{sub.lastRefreshed && (
|
{sub.lastRefreshed && (
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
{tSub('last_refreshed', { time: new Date(sub.lastRefreshed).toLocaleString() })}
|
{tSub('last_refreshed', { time: formatDateTime(sub.lastRefreshed, timeFormat, { month: 'short', day: 'numeric', year: 'numeric' }) })}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,13 +3,18 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { useSettingsStore } from '@/stores/settings-store';
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import type { ArchiveMode } from '@/stores/settings-store';
|
||||||
|
import { useAuthStore } from '@/stores/auth-store';
|
||||||
|
import { useEmailStore } from '@/stores/email-store';
|
||||||
import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section';
|
import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section';
|
||||||
import { TrustedSendersModal } from '@/components/trusted-senders-modal';
|
import { TrustedSendersModal } from '@/components/trusted-senders-modal';
|
||||||
import { ChevronRight, AlertTriangle } from 'lucide-react';
|
import { ChevronRight, AlertTriangle, FolderSync, Loader2 } from 'lucide-react';
|
||||||
|
|
||||||
export function EmailSettings() {
|
export function EmailSettings() {
|
||||||
const t = useTranslations('settings.email_behavior');
|
const t = useTranslations('settings.email_behavior');
|
||||||
const [showTrustedModal, setShowTrustedModal] = useState(false);
|
const [showTrustedModal, setShowTrustedModal] = useState(false);
|
||||||
|
const [isReorganizing, setIsReorganizing] = useState(false);
|
||||||
|
const [reorganizeResult, setReorganizeResult] = useState<string | null>(null);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
markAsReadDelay,
|
markAsReadDelay,
|
||||||
@@ -19,6 +24,8 @@ export function EmailSettings() {
|
|||||||
emailsPerPage,
|
emailsPerPage,
|
||||||
externalContentPolicy,
|
externalContentPolicy,
|
||||||
mailAttachmentAction,
|
mailAttachmentAction,
|
||||||
|
emailAlwaysLightMode,
|
||||||
|
archiveMode,
|
||||||
trustedSenders,
|
trustedSenders,
|
||||||
updateSetting,
|
updateSetting,
|
||||||
} = useSettingsStore();
|
} = useSettingsStore();
|
||||||
@@ -31,6 +38,69 @@ export function EmailSettings() {
|
|||||||
return t('trusted_senders.count_other', { count });
|
return t('trusted_senders.count_other', { count });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleReorganizeArchive = async () => {
|
||||||
|
const { client } = useAuthStore.getState();
|
||||||
|
const { mailboxes, fetchMailboxes } = useEmailStore.getState();
|
||||||
|
if (!client) return;
|
||||||
|
|
||||||
|
const archiveMailbox = mailboxes.find(m => m.role === 'archive' || m.name.toLowerCase() === 'archive');
|
||||||
|
if (!archiveMailbox) return;
|
||||||
|
|
||||||
|
setIsReorganizing(true);
|
||||||
|
setReorganizeResult(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const archiveId = archiveMailbox.originalId || archiveMailbox.id;
|
||||||
|
|
||||||
|
// Fetch all emails in the root archive mailbox
|
||||||
|
const emails = await client.getEmailsInMailbox(archiveId);
|
||||||
|
let movedCount = 0;
|
||||||
|
|
||||||
|
for (const email of emails) {
|
||||||
|
const emailDate = new Date(email.receivedAt);
|
||||||
|
const year = emailDate.getFullYear().toString();
|
||||||
|
const month = (emailDate.getMonth() + 1).toString().padStart(2, '0');
|
||||||
|
|
||||||
|
// Re-read mailboxes from store each iteration in case new ones were created
|
||||||
|
let currentMailboxes = useEmailStore.getState().mailboxes;
|
||||||
|
|
||||||
|
// Find or create year subfolder
|
||||||
|
let yearMailbox = currentMailboxes.find(
|
||||||
|
m => m.name === year && m.parentId === archiveId
|
||||||
|
);
|
||||||
|
if (!yearMailbox) {
|
||||||
|
yearMailbox = await client.createMailbox(year, archiveId);
|
||||||
|
await fetchMailboxes(client);
|
||||||
|
currentMailboxes = useEmailStore.getState().mailboxes;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (archiveMode === 'year') {
|
||||||
|
await client.moveEmail(email.id, yearMailbox.id);
|
||||||
|
movedCount++;
|
||||||
|
} else {
|
||||||
|
// month mode
|
||||||
|
const yearId = yearMailbox.originalId || yearMailbox.id;
|
||||||
|
let monthMailbox = currentMailboxes.find(
|
||||||
|
m => m.name === month && m.parentId === yearId
|
||||||
|
);
|
||||||
|
if (!monthMailbox) {
|
||||||
|
monthMailbox = await client.createMailbox(month, yearId);
|
||||||
|
await fetchMailboxes(client);
|
||||||
|
}
|
||||||
|
await client.moveEmail(email.id, monthMailbox.id);
|
||||||
|
movedCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setReorganizeResult(t('archive_mode.reorganize_success', { count: movedCount }));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to reorganize archive:', error);
|
||||||
|
setReorganizeResult(t('archive_mode.reorganize_error'));
|
||||||
|
} finally {
|
||||||
|
setIsReorganizing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingsSection title={t('title')} description={t('description')}>
|
<SettingsSection title={t('title')} description={t('description')}>
|
||||||
{/* Mark as Read */}
|
{/* Mark as Read */}
|
||||||
@@ -67,6 +137,40 @@ export function EmailSettings() {
|
|||||||
</div>
|
</div>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{/* Archive Mode */}
|
||||||
|
<SettingItem label={t('archive_mode.label')} description={t('archive_mode.description')}>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Select
|
||||||
|
value={archiveMode}
|
||||||
|
onChange={(value) => updateSetting('archiveMode', value as ArchiveMode)}
|
||||||
|
options={[
|
||||||
|
{ value: 'single', label: t('archive_mode.single') },
|
||||||
|
{ value: 'year', label: t('archive_mode.year') },
|
||||||
|
{ value: 'month', label: t('archive_mode.month') },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
{archiveMode !== 'single' && (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleReorganizeArchive}
|
||||||
|
disabled={isReorganizing}
|
||||||
|
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-accent rounded-md transition-colors text-sm disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isReorganizing ? (
|
||||||
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<FolderSync className="w-4 h-4" />
|
||||||
|
)}
|
||||||
|
<span>{t('archive_mode.reorganize')}</span>
|
||||||
|
</button>
|
||||||
|
{reorganizeResult && (
|
||||||
|
<p className="text-xs text-muted-foreground">{reorganizeResult}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
{/* Permanently Delete Junk */}
|
{/* Permanently Delete Junk */}
|
||||||
<SettingItem label={t('permanently_delete_junk.label')} description={t('permanently_delete_junk.description')}>
|
<SettingItem label={t('permanently_delete_junk.label')} description={t('permanently_delete_junk.description')}>
|
||||||
<ToggleSwitch
|
<ToggleSwitch
|
||||||
@@ -104,6 +208,14 @@ export function EmailSettings() {
|
|||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{/* Always Light Mode for Emails */}
|
||||||
|
<SettingItem label={t('always_light_mode.label')} description={t('always_light_mode.description')}>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={emailAlwaysLightMode}
|
||||||
|
onChange={(checked) => updateSetting('emailAlwaysLightMode', checked)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
{/* External Content */}
|
{/* External Content */}
|
||||||
<SettingItem label={t('external_content.label')} description={t('external_content.description')}>
|
<SettingItem label={t('external_content.label')} description={t('external_content.description')}>
|
||||||
<Select
|
<Select
|
||||||
|
|||||||
@@ -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>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,280 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useCallback } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Plus, Pencil, Trash2, ExternalLink, PanelRight, GripVertical } from "lucide-react";
|
||||||
|
import { icons as lucideIcons, type LucideIcon } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { SettingsSection, SettingItem, ToggleSwitch } from "./settings-section";
|
||||||
|
import { IconPicker } from "@/components/layout/icon-picker";
|
||||||
|
import { useSettingsStore, type SidebarApp } from "@/stores/settings-store";
|
||||||
|
import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
|
||||||
|
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface SidebarAppFormData {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
icon: string;
|
||||||
|
openMode: "tab" | "inline";
|
||||||
|
}
|
||||||
|
|
||||||
|
function AppForm({
|
||||||
|
app,
|
||||||
|
onSave,
|
||||||
|
onCancel,
|
||||||
|
}: {
|
||||||
|
app?: SidebarApp;
|
||||||
|
onSave: (data: SidebarAppFormData) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}) {
|
||||||
|
const t = useTranslations("sidebar_apps");
|
||||||
|
const isEditing = !!app;
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<SidebarAppFormData>({
|
||||||
|
name: app?.name || "",
|
||||||
|
url: app?.url || "",
|
||||||
|
icon: app?.icon || "Globe",
|
||||||
|
openMode: app?.openMode || "tab",
|
||||||
|
});
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
const validate = (): boolean => {
|
||||||
|
const newErrors: Record<string, string> = {};
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
newErrors.name = t("name_required");
|
||||||
|
}
|
||||||
|
if (!formData.url.trim()) {
|
||||||
|
newErrors.url = t("url_required");
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(formData.url);
|
||||||
|
if (!["http:", "https:"].includes(parsed.protocol)) {
|
||||||
|
newErrors.url = t("url_invalid");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
newErrors.url = t("url_invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!formData.icon) {
|
||||||
|
newErrors.icon = t("icon_required");
|
||||||
|
}
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!validate()) return;
|
||||||
|
onSave(formData);
|
||||||
|
};
|
||||||
|
|
||||||
|
const SelectedIcon = formData.icon
|
||||||
|
? (lucideIcons[formData.icon as keyof typeof lucideIcons] as LucideIcon | undefined)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4 p-4 border border-border rounded-lg bg-secondary/30">
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">{t("name_label")}</label>
|
||||||
|
<Input
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||||
|
placeholder={t("name_placeholder")}
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
{errors.name && <p className="text-xs text-destructive mt-1">{errors.name}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium">{t("url_label")}</label>
|
||||||
|
<Input
|
||||||
|
value={formData.url}
|
||||||
|
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
|
||||||
|
placeholder="https://example.com"
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
{errors.url && <p className="text-xs text-destructive mt-1">{errors.url}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium block mb-1">{t("icon_label")}</label>
|
||||||
|
<div className="flex items-center gap-2 mb-2">
|
||||||
|
{SelectedIcon && (
|
||||||
|
<div className="w-8 h-8 rounded-md bg-muted flex items-center justify-center">
|
||||||
|
<SelectedIcon className="w-4 h-4" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<span className="text-sm text-muted-foreground">{formData.icon}</span>
|
||||||
|
</div>
|
||||||
|
<IconPicker value={formData.icon} onChange={(icon) => setFormData({ ...formData, icon })} />
|
||||||
|
{errors.icon && <p className="text-xs text-destructive mt-1">{errors.icon}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium block mb-2">{t("open_mode_label")}</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData({ ...formData, openMode: "tab" })}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 px-3 py-2 rounded-md text-sm border transition-colors",
|
||||||
|
formData.openMode === "tab"
|
||||||
|
? "border-primary bg-primary/10 text-primary"
|
||||||
|
: "border-border hover:bg-muted"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<ExternalLink className="w-4 h-4" />
|
||||||
|
{t("open_new_tab")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData({ ...formData, openMode: "inline" })}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 px-3 py-2 rounded-md text-sm border transition-colors",
|
||||||
|
formData.openMode === "inline"
|
||||||
|
? "border-primary bg-primary/10 text-primary"
|
||||||
|
: "border-border hover:bg-muted"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<PanelRight className="w-4 h-4" />
|
||||||
|
{t("open_inline")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
|
||||||
|
{t("cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" size="sm">
|
||||||
|
{isEditing ? t("update") : t("add")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SidebarAppsSettings() {
|
||||||
|
const t = useTranslations("settings.sidebar_apps");
|
||||||
|
const tApps = useTranslations("sidebar_apps");
|
||||||
|
const { sidebarApps, keepAppsLoaded, addSidebarApp, updateSidebarApp, removeSidebarApp, updateSetting } = useSettingsStore();
|
||||||
|
const [editingApp, setEditingApp] = useState<string | null>(null);
|
||||||
|
const [showAddForm, setShowAddForm] = useState(false);
|
||||||
|
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
|
||||||
|
|
||||||
|
const handleAdd = useCallback((data: SidebarAppFormData) => {
|
||||||
|
const id = `app-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||||||
|
addSidebarApp({ id, ...data });
|
||||||
|
setShowAddForm(false);
|
||||||
|
}, [addSidebarApp]);
|
||||||
|
|
||||||
|
const handleUpdate = useCallback((id: string, data: SidebarAppFormData) => {
|
||||||
|
updateSidebarApp(id, data);
|
||||||
|
setEditingApp(null);
|
||||||
|
}, [updateSidebarApp]);
|
||||||
|
|
||||||
|
const handleDelete = useCallback(async (app: SidebarApp) => {
|
||||||
|
const confirmed = await confirmDialog({
|
||||||
|
title: tApps("delete_confirm_title"),
|
||||||
|
message: tApps("delete_confirm", { name: app.name }),
|
||||||
|
confirmText: tApps("delete"),
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
if (!confirmed) return;
|
||||||
|
removeSidebarApp(app.id);
|
||||||
|
}, [confirmDialog, tApps, removeSidebarApp]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<SettingsSection title={t("title")} description={t("description")}>
|
||||||
|
<SettingItem label={t("keep_loaded")} description={t("keep_loaded_description")}>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={keepAppsLoaded}
|
||||||
|
onChange={(v) => updateSetting("keepAppsLoaded", v)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
<SettingsSection title={t("manage_title")} description={t("manage_description")}>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{sidebarApps.length === 0 && !showAddForm && (
|
||||||
|
<p className="text-sm text-muted-foreground py-4 text-center">{tApps("no_apps_hint")}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{sidebarApps.map((app) => {
|
||||||
|
if (editingApp === app.id) {
|
||||||
|
return (
|
||||||
|
<AppForm
|
||||||
|
key={app.id}
|
||||||
|
app={app}
|
||||||
|
onSave={(data) => handleUpdate(app.id, data)}
|
||||||
|
onCancel={() => setEditingApp(null)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={app.id}
|
||||||
|
className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-muted/50 transition-colors"
|
||||||
|
>
|
||||||
|
<GripVertical className="w-4 h-4 text-muted-foreground/50 flex-shrink-0" />
|
||||||
|
<div className="w-8 h-8 rounded-md bg-muted flex items-center justify-center flex-shrink-0">
|
||||||
|
{AppIcon ? <AppIcon className="w-4 h-4" /> : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-sm font-medium truncate">{app.name}</div>
|
||||||
|
<div className="text-xs text-muted-foreground truncate">{app.url}</div>
|
||||||
|
</div>
|
||||||
|
<span className={cn(
|
||||||
|
"text-[10px] px-1.5 py-0.5 rounded-full flex-shrink-0",
|
||||||
|
app.openMode === "inline"
|
||||||
|
? "bg-blue-500/10 text-blue-600 dark:text-blue-400"
|
||||||
|
: "bg-muted text-muted-foreground"
|
||||||
|
)}>
|
||||||
|
{app.openMode === "inline" ? tApps("inline_badge") : tApps("tab_badge")}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditingApp(app.id)}
|
||||||
|
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
<Pencil className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(app)}
|
||||||
|
className="p-1.5 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{showAddForm && (
|
||||||
|
<AppForm
|
||||||
|
onSave={handleAdd}
|
||||||
|
onCancel={() => setShowAddForm(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!showAddForm && !editingApp && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setShowAddForm(true)}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
|
{tApps("add_new")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
<ConfirmDialog {...confirmDialogProps} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useId } from "react";
|
||||||
|
import { useFocusTrap } from "@/hooks/use-focus-trap";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { ShieldCheck, X } from "lucide-react";
|
||||||
|
import type { SmimeKeyRecord, SmimePublicCert } from "@/lib/smime/types";
|
||||||
|
|
||||||
|
interface SmimeCertificateModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
record: SmimeKeyRecord | SmimePublicCert | null;
|
||||||
|
type: "private" | "public";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SmimeCertificateModal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
record,
|
||||||
|
type,
|
||||||
|
}: SmimeCertificateModalProps) {
|
||||||
|
const t = useTranslations("smime");
|
||||||
|
const id = useId();
|
||||||
|
|
||||||
|
const dialogRef = useFocusTrap({
|
||||||
|
isActive: isOpen,
|
||||||
|
onEscape: onClose,
|
||||||
|
restoreFocus: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isOpen || !record) return null;
|
||||||
|
|
||||||
|
const isExpired = new Date(record.notAfter) < new Date();
|
||||||
|
const isNotYetValid = new Date(record.notBefore) > new Date();
|
||||||
|
|
||||||
|
const rows: { label: string; value: string }[] = [
|
||||||
|
{ label: t("cert_subject"), value: record.subject ?? "" },
|
||||||
|
{ label: t("cert_issuer"), value: record.issuer ?? "" },
|
||||||
|
{ label: t("cert_email"), value: record.email },
|
||||||
|
{
|
||||||
|
label: t("cert_validity"),
|
||||||
|
value: `${new Date(record.notBefore).toLocaleDateString()} — ${new Date(record.notAfter).toLocaleDateString()}`,
|
||||||
|
},
|
||||||
|
{ label: t("cert_fingerprint"), value: record.fingerprint },
|
||||||
|
];
|
||||||
|
|
||||||
|
if ("serialNumber" in record) {
|
||||||
|
rows.splice(2, 0, { label: t("cert_serial"), value: record.serialNumber });
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("algorithm" in record) {
|
||||||
|
rows.push({ label: t("cert_algorithm"), value: record.algorithm });
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("capabilities" in record) {
|
||||||
|
const caps: string[] = [];
|
||||||
|
if (record.capabilities.canSign) caps.push(t("cap_sign"));
|
||||||
|
if (record.capabilities.canEncrypt) caps.push(t("cap_encrypt"));
|
||||||
|
rows.push({ label: t("cert_capabilities"), value: caps.join(", ") || t("cap_none") });
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("source" in record) {
|
||||||
|
rows.push({ label: t("cert_source"), value: record.source });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150">
|
||||||
|
<div
|
||||||
|
ref={dialogRef}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby={`${id}-title`}
|
||||||
|
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-lg animate-in zoom-in-95 duration-200"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between p-6 pb-4 border-b border-border">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-9 h-9 rounded-full bg-primary/10 flex items-center justify-center">
|
||||||
|
<ShieldCheck className="w-5 h-5 text-primary" />
|
||||||
|
</div>
|
||||||
|
<h2 id={`${id}-title`} className="text-lg font-semibold text-foreground">
|
||||||
|
{t("certificate_details")}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="icon" onClick={onClose}>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-6 space-y-3 max-h-[60vh] overflow-y-auto">
|
||||||
|
{(isExpired || isNotYetValid) && (
|
||||||
|
<div className="px-3 py-2 rounded-md bg-destructive/10 text-destructive text-sm">
|
||||||
|
{isExpired ? t("cert_expired") : t("cert_not_yet_valid")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{rows.map(({ label, value }) => (
|
||||||
|
<div key={label}>
|
||||||
|
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||||
|
{label}
|
||||||
|
</dt>
|
||||||
|
<dd className="text-sm text-foreground mt-0.5 break-all font-mono">
|
||||||
|
{value}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end px-6 pb-6">
|
||||||
|
<Button variant="ghost" onClick={onClose}>
|
||||||
|
{t("close")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useId } from "react";
|
||||||
|
import { useFocusTrap } from "@/hooks/use-focus-trap";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { KeyRound, Eye, EyeOff } from "lucide-react";
|
||||||
|
|
||||||
|
interface SmimePassphraseDialogProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSubmit: (passphrase: string) => void | Promise<void>;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
submitText?: string;
|
||||||
|
error?: string | null;
|
||||||
|
/** Show a second passphrase field for import/export confirmation. */
|
||||||
|
showConfirm?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SmimePassphraseDialog({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
onSubmit,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
submitText,
|
||||||
|
error,
|
||||||
|
showConfirm = false,
|
||||||
|
}: SmimePassphraseDialogProps) {
|
||||||
|
const t = useTranslations("smime");
|
||||||
|
const id = useId();
|
||||||
|
const [passphrase, setPassphrase] = useState("");
|
||||||
|
const [confirm, setConfirm] = useState("");
|
||||||
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
|
const dialogRef = useFocusTrap({
|
||||||
|
isActive: isOpen,
|
||||||
|
onEscape: onClose,
|
||||||
|
restoreFocus: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const mismatch = showConfirm && passphrase !== confirm && confirm.length > 0;
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!passphrase || (showConfirm && passphrase !== confirm)) return;
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
await onSubmit(passphrase);
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setPassphrase("");
|
||||||
|
setConfirm("");
|
||||||
|
setShowPassword(false);
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150">
|
||||||
|
<div
|
||||||
|
ref={dialogRef}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby={`${id}-title`}
|
||||||
|
aria-describedby={description ? `${id}-desc` : undefined}
|
||||||
|
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-md animate-in zoom-in-95 duration-200"
|
||||||
|
>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<div className="p-6">
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
|
||||||
|
<KeyRound className="w-5 h-5 text-primary" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h2
|
||||||
|
id={`${id}-title`}
|
||||||
|
className="text-lg font-semibold text-foreground"
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
{description && (
|
||||||
|
<p
|
||||||
|
id={`${id}-desc`}
|
||||||
|
className="text-sm text-muted-foreground mt-1"
|
||||||
|
>
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-3">
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={passphrase}
|
||||||
|
onChange={(e) => setPassphrase(e.target.value)}
|
||||||
|
placeholder={t("passphrase_placeholder")}
|
||||||
|
autoFocus
|
||||||
|
className="pr-10"
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground"
|
||||||
|
aria-label={showPassword ? t("hide_passphrase") : t("show_passphrase")}
|
||||||
|
>
|
||||||
|
{showPassword ? (
|
||||||
|
<EyeOff className="w-4 h-4" />
|
||||||
|
) : (
|
||||||
|
<Eye className="w-4 h-4" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showConfirm && (
|
||||||
|
<div>
|
||||||
|
<Input
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={confirm}
|
||||||
|
onChange={(e) => setConfirm(e.target.value)}
|
||||||
|
placeholder={t("confirm_passphrase_placeholder")}
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
{mismatch && (
|
||||||
|
<p className="text-xs text-destructive mt-1">
|
||||||
|
{t("passphrase_mismatch")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p className="text-sm text-destructive">{error}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 px-6 pb-6">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={handleClose}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
>
|
||||||
|
{t("cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={!passphrase || isSubmitting || (showConfirm && passphrase !== confirm)}
|
||||||
|
>
|
||||||
|
{isSubmitting ? t("processing") : (submitText ?? t("unlock"))}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,559 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useRef } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import {
|
||||||
|
Upload,
|
||||||
|
Trash2,
|
||||||
|
Eye,
|
||||||
|
Lock,
|
||||||
|
Unlock,
|
||||||
|
Download,
|
||||||
|
ShieldCheck,
|
||||||
|
ShieldAlert,
|
||||||
|
Users,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { SettingsSection, SettingItem, ToggleSwitch } from "@/components/settings/settings-section";
|
||||||
|
import { SmimePassphraseDialog } from "@/components/settings/smime-passphrase-dialog";
|
||||||
|
import { SmimeCertificateModal } from "@/components/settings/smime-certificate-modal";
|
||||||
|
import { useSmimeStore } from "@/stores/smime-store";
|
||||||
|
import { useIdentityStore } from "@/stores/identity-store";
|
||||||
|
import { exportPkcs12, downloadPkcs12 } from "@/lib/smime/pkcs12-export";
|
||||||
|
import type { SmimeKeyRecord, SmimePublicCert } from "@/lib/smime/types";
|
||||||
|
|
||||||
|
export function SmimeSettings() {
|
||||||
|
const t = useTranslations("smime");
|
||||||
|
const {
|
||||||
|
keyRecords,
|
||||||
|
publicCerts,
|
||||||
|
identityKeyBindings,
|
||||||
|
defaultSignIdentity,
|
||||||
|
defaultEncrypt,
|
||||||
|
rememberUnlockedKeys,
|
||||||
|
autoImportSignerCerts,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
load,
|
||||||
|
importPKCS12,
|
||||||
|
removeKeyRecord,
|
||||||
|
removePublicCert,
|
||||||
|
bindIdentityToKey,
|
||||||
|
unlockKey,
|
||||||
|
lockKey,
|
||||||
|
setSignDefault,
|
||||||
|
setEncryptDefault,
|
||||||
|
setRememberUnlockedKeys,
|
||||||
|
setAutoImportSignerCerts,
|
||||||
|
isKeyUnlocked,
|
||||||
|
setError,
|
||||||
|
} = useSmimeStore();
|
||||||
|
|
||||||
|
const { identities } = useIdentityStore();
|
||||||
|
|
||||||
|
// Local UI state
|
||||||
|
const [importDialogOpen, setImportDialogOpen] = useState(false);
|
||||||
|
const [unlockDialogOpen, setUnlockDialogOpen] = useState(false);
|
||||||
|
const [unlockTargetId, setUnlockTargetId] = useState<string | null>(null);
|
||||||
|
const [certModalRecord, setCertModalRecord] = useState<SmimeKeyRecord | SmimePublicCert | null>(null);
|
||||||
|
const [certModalType, setCertModalType] = useState<"private" | "public">("private");
|
||||||
|
const [importError, setImportError] = useState<string | null>(null);
|
||||||
|
const [unlockError, setUnlockError] = useState<string | null>(null);
|
||||||
|
const [pendingFile, setPendingFile] = useState<ArrayBuffer | null>(null);
|
||||||
|
const [pendingP12Pass, setPendingP12Pass] = useState("");
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const pubCertInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
// State for the two-step PKCS#12 flow
|
||||||
|
const [importStep, setImportStep] = useState<"p12" | "storage">("p12");
|
||||||
|
|
||||||
|
// Export flow state
|
||||||
|
const [exportDialogOpen, setExportDialogOpen] = useState(false);
|
||||||
|
const [exportTargetRecord, setExportTargetRecord] = useState<SmimeKeyRecord | null>(null);
|
||||||
|
const [exportStep, setExportStep] = useState<"storage" | "export">("storage");
|
||||||
|
const [exportStoragePass, setExportStoragePass] = useState("");
|
||||||
|
const [exportError, setExportError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
// ── PKCS#12 import flow ────────────────────────────────────────
|
||||||
|
|
||||||
|
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
setPendingFile(reader.result as ArrayBuffer);
|
||||||
|
setImportStep("p12");
|
||||||
|
setImportError(null);
|
||||||
|
setImportDialogOpen(true);
|
||||||
|
};
|
||||||
|
reader.readAsArrayBuffer(file);
|
||||||
|
// Reset so same file can be re-selected
|
||||||
|
e.target.value = "";
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImportSubmit = async (passphrase: string) => {
|
||||||
|
if (importStep === "p12") {
|
||||||
|
setPendingP12Pass(passphrase);
|
||||||
|
setImportStep("storage");
|
||||||
|
setImportError(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Storage passphrase step
|
||||||
|
if (!pendingFile) return;
|
||||||
|
try {
|
||||||
|
await importPKCS12(pendingFile, pendingP12Pass, passphrase);
|
||||||
|
setImportDialogOpen(false);
|
||||||
|
setPendingFile(null);
|
||||||
|
setPendingP12Pass("");
|
||||||
|
setImportError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setImportError(err instanceof Error ? err.message : "Import failed");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Public cert import ─────────────────────────────────────────
|
||||||
|
|
||||||
|
const handlePublicCertFile = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async () => {
|
||||||
|
try {
|
||||||
|
const store = useSmimeStore.getState();
|
||||||
|
await store.importPublicCert(reader.result as ArrayBuffer, "manual");
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Failed to import certificate");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsArrayBuffer(file);
|
||||||
|
e.target.value = "";
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Unlock ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const handleUnlockRequest = (id: string) => {
|
||||||
|
setUnlockTargetId(id);
|
||||||
|
setUnlockError(null);
|
||||||
|
setUnlockDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUnlockSubmit = async (passphrase: string) => {
|
||||||
|
if (!unlockTargetId) return;
|
||||||
|
try {
|
||||||
|
await unlockKey(unlockTargetId, passphrase);
|
||||||
|
setUnlockDialogOpen(false);
|
||||||
|
setUnlockTargetId(null);
|
||||||
|
setUnlockError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setUnlockError(err instanceof Error ? err.message : "Unlock failed");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Export flow ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const handleExportRequest = (record: SmimeKeyRecord) => {
|
||||||
|
setExportTargetRecord(record);
|
||||||
|
setExportStep("storage");
|
||||||
|
setExportStoragePass("");
|
||||||
|
setExportError(null);
|
||||||
|
setExportDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExportSubmit = async (passphrase: string) => {
|
||||||
|
if (!exportTargetRecord) return;
|
||||||
|
|
||||||
|
if (exportStep === "storage") {
|
||||||
|
// Verify storage passphrase by attempting to decrypt
|
||||||
|
try {
|
||||||
|
const { decryptPrivateKeyBytes } = await import("@/lib/smime/pkcs12-import");
|
||||||
|
await decryptPrivateKeyBytes(exportTargetRecord, passphrase);
|
||||||
|
setExportStoragePass(passphrase);
|
||||||
|
setExportStep("export");
|
||||||
|
setExportError(null);
|
||||||
|
} catch {
|
||||||
|
setExportError(t("incorrect_passphrase"));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export passphrase step
|
||||||
|
try {
|
||||||
|
const p12Bytes = await exportPkcs12(exportTargetRecord, exportStoragePass, passphrase);
|
||||||
|
const filename = `${exportTargetRecord.email.replace(/[^a-zA-Z0-9.-]/g, '_')}.p12`;
|
||||||
|
downloadPkcs12(p12Bytes, filename);
|
||||||
|
setExportDialogOpen(false);
|
||||||
|
setExportTargetRecord(null);
|
||||||
|
setExportStoragePass("");
|
||||||
|
setExportError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setExportError(err instanceof Error ? err.message : "Export failed");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Helpers ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const isExpired = (dateStr: string) => new Date(dateStr) < new Date();
|
||||||
|
|
||||||
|
const formatDate = (dateStr: string) => {
|
||||||
|
try {
|
||||||
|
return new Date(dateStr).toLocaleDateString();
|
||||||
|
} catch {
|
||||||
|
return dateStr;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getBoundIdentityNames = (keyId: string): string[] => {
|
||||||
|
return Object.entries(identityKeyBindings)
|
||||||
|
.filter(([, kId]) => kId === keyId)
|
||||||
|
.map(([identityId]) => {
|
||||||
|
const identity = identities.find((i) => i.id === identityId);
|
||||||
|
return identity?.email ?? identityId;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
{error && (
|
||||||
|
<div className="px-4 py-3 rounded-md bg-destructive/10 text-destructive text-sm">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Your Certificates ──────────────────────────────────── */}
|
||||||
|
<SettingsSection
|
||||||
|
title={t("your_certificates")}
|
||||||
|
description={t("your_certificates_desc")}
|
||||||
|
>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{keyRecords.map((record) => {
|
||||||
|
const expired = isExpired(record.notAfter);
|
||||||
|
const unlocked = isKeyUnlocked(record.id);
|
||||||
|
const boundIdentities = getBoundIdentityNames(record.id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={record.id}
|
||||||
|
className="flex items-center justify-between p-3 rounded-lg border border-border"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||||
|
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${expired ? "bg-destructive/10" : "bg-primary/10"}`}>
|
||||||
|
{expired ? (
|
||||||
|
<ShieldAlert className="w-4 h-4 text-destructive" />
|
||||||
|
) : (
|
||||||
|
<ShieldCheck className="w-4 h-4 text-primary" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-sm font-medium text-foreground truncate">
|
||||||
|
{record.email || record.subject}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{record.issuer} · {t("expires")} {formatDate(record.notAfter)}
|
||||||
|
{expired && <span className="text-destructive ml-1">({t("expired")})</span>}
|
||||||
|
</p>
|
||||||
|
{boundIdentities.length > 0 && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{t("bound_to")}: {boundIdentities.join(", ")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{unlocked ? (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => lockKey(record.id)}
|
||||||
|
title={t("lock")}
|
||||||
|
>
|
||||||
|
<Unlock className="w-4 h-4 text-green-600" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleUnlockRequest(record.id)}
|
||||||
|
title={t("unlock")}
|
||||||
|
>
|
||||||
|
<Lock className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => {
|
||||||
|
setCertModalRecord(record);
|
||||||
|
setCertModalType("private");
|
||||||
|
}}
|
||||||
|
title={t("details")}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleExportRequest(record)}
|
||||||
|
title={t("export")}
|
||||||
|
>
|
||||||
|
<Download className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => removeKeyRecord(record.id)}
|
||||||
|
title={t("delete")}
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{keyRecords.length === 0 && !isLoading && (
|
||||||
|
<p className="text-sm text-muted-foreground py-4 text-center">
|
||||||
|
{t("no_certificates")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".p12,.pfx"
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleFileSelect}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="mt-2"
|
||||||
|
>
|
||||||
|
<Upload className="w-4 h-4 mr-2" />
|
||||||
|
{t("import_pkcs12")}
|
||||||
|
</Button>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
{/* ── Recipient Certificates ─────────────────────────────── */}
|
||||||
|
<SettingsSection
|
||||||
|
title={t("recipient_certificates")}
|
||||||
|
description={t("recipient_certificates_desc")}
|
||||||
|
>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{publicCerts.map((cert) => {
|
||||||
|
const expired = isExpired(cert.notAfter);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={cert.id}
|
||||||
|
className="flex items-center justify-between p-3 rounded-lg border border-border"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||||
|
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center">
|
||||||
|
<Users className="w-4 h-4 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-sm font-medium text-foreground truncate">
|
||||||
|
{cert.email || cert.subject}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{cert.issuer} · {cert.source}
|
||||||
|
{expired && <span className="text-destructive ml-1">({t("expired")})</span>}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => {
|
||||||
|
setCertModalRecord(cert);
|
||||||
|
setCertModalType("public");
|
||||||
|
}}
|
||||||
|
title={t("details")}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => removePublicCert(cert.id)}
|
||||||
|
title={t("delete")}
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{publicCerts.length === 0 && !isLoading && (
|
||||||
|
<p className="text-sm text-muted-foreground py-4 text-center">
|
||||||
|
{t("no_recipient_certs")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={pubCertInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".pem,.cer,.crt,.der"
|
||||||
|
className="hidden"
|
||||||
|
onChange={handlePublicCertFile}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => pubCertInputRef.current?.click()}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="mt-2"
|
||||||
|
>
|
||||||
|
<Upload className="w-4 h-4 mr-2" />
|
||||||
|
{t("import_public_cert")}
|
||||||
|
</Button>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
{/* ── Identity Bindings ──────────────────────────────────── */}
|
||||||
|
{identities.length > 0 && keyRecords.length > 0 && (
|
||||||
|
<SettingsSection
|
||||||
|
title={t("identity_bindings")}
|
||||||
|
description={t("identity_bindings_desc")}
|
||||||
|
>
|
||||||
|
{identities.map((identity) => {
|
||||||
|
const boundKeyId = identityKeyBindings[identity.id];
|
||||||
|
return (
|
||||||
|
<SettingItem key={identity.id} label={identity.email}>
|
||||||
|
<select
|
||||||
|
value={boundKeyId ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
bindIdentityToKey(identity.id, e.target.value || null)
|
||||||
|
}
|
||||||
|
className="text-sm bg-background border border-border rounded-md px-2 py-1"
|
||||||
|
>
|
||||||
|
<option value="">{t("no_key_bound")}</option>
|
||||||
|
{keyRecords.map((kr) => (
|
||||||
|
<option key={kr.id} value={kr.id}>
|
||||||
|
{kr.email} ({kr.algorithm})
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</SettingItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</SettingsSection>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── Defaults ───────────────────────────────────────────── */}
|
||||||
|
<SettingsSection
|
||||||
|
title={t("defaults_title")}
|
||||||
|
description={t("defaults_desc")}
|
||||||
|
>
|
||||||
|
<SettingItem
|
||||||
|
label={t("encrypt_by_default")}
|
||||||
|
description={t("encrypt_by_default_desc")}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={defaultEncrypt}
|
||||||
|
onChange={setEncryptDefault}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem
|
||||||
|
label={t("remember_unlocked")}
|
||||||
|
description={t("remember_unlocked_desc")}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={rememberUnlockedKeys}
|
||||||
|
onChange={setRememberUnlockedKeys}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem
|
||||||
|
label={t("auto_import_signer_certs")}
|
||||||
|
description={t("auto_import_signer_certs_desc")}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={autoImportSignerCerts}
|
||||||
|
onChange={setAutoImportSignerCerts}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
{identities.map((identity) => {
|
||||||
|
const bound = identityKeyBindings[identity.id];
|
||||||
|
if (!bound) return null;
|
||||||
|
return (
|
||||||
|
<SettingItem
|
||||||
|
key={identity.id}
|
||||||
|
label={`${t("sign_default_for")} ${identity.email}`}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={defaultSignIdentity[identity.id] ?? false}
|
||||||
|
onChange={(v) => setSignDefault(identity.id, v)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
{/* ── Dialogs ────────────────────────────────────────────── */}
|
||||||
|
<SmimePassphraseDialog
|
||||||
|
isOpen={importDialogOpen}
|
||||||
|
onClose={() => {
|
||||||
|
setImportDialogOpen(false);
|
||||||
|
setPendingFile(null);
|
||||||
|
setPendingP12Pass("");
|
||||||
|
setImportError(null);
|
||||||
|
setImportStep("p12");
|
||||||
|
}}
|
||||||
|
onSubmit={handleImportSubmit}
|
||||||
|
title={importStep === "p12" ? t("enter_p12_passphrase") : t("enter_storage_passphrase")}
|
||||||
|
description={importStep === "p12" ? t("p12_passphrase_desc") : t("storage_passphrase_desc")}
|
||||||
|
submitText={importStep === "p12" ? t("next") : t("import")}
|
||||||
|
error={importError}
|
||||||
|
showConfirm={importStep === "storage"}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SmimePassphraseDialog
|
||||||
|
isOpen={unlockDialogOpen}
|
||||||
|
onClose={() => {
|
||||||
|
setUnlockDialogOpen(false);
|
||||||
|
setUnlockTargetId(null);
|
||||||
|
setUnlockError(null);
|
||||||
|
}}
|
||||||
|
onSubmit={handleUnlockSubmit}
|
||||||
|
title={t("unlock_key")}
|
||||||
|
description={t("unlock_key_desc")}
|
||||||
|
error={unlockError}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SmimeCertificateModal
|
||||||
|
isOpen={!!certModalRecord}
|
||||||
|
onClose={() => setCertModalRecord(null)}
|
||||||
|
record={certModalRecord}
|
||||||
|
type={certModalType}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SmimePassphraseDialog
|
||||||
|
isOpen={exportDialogOpen}
|
||||||
|
onClose={() => {
|
||||||
|
setExportDialogOpen(false);
|
||||||
|
setExportTargetRecord(null);
|
||||||
|
setExportStoragePass("");
|
||||||
|
setExportError(null);
|
||||||
|
setExportStep("storage");
|
||||||
|
}}
|
||||||
|
onSubmit={handleExportSubmit}
|
||||||
|
title={exportStep === "storage" ? t("enter_storage_passphrase") : t("enter_export_passphrase")}
|
||||||
|
description={exportStep === "storage" ? t("export_storage_desc") : t("export_passphrase_desc")}
|
||||||
|
submitText={exportStep === "storage" ? t("next") : t("export")}
|
||||||
|
error={exportError}
|
||||||
|
showConfirm={exportStep === "export"}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,9 @@ services:
|
|||||||
image: ghcr.io/bulwarkmail/webmail:latest
|
image: ghcr.io/bulwarkmail/webmail:latest
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000"
|
- "3000:3000"
|
||||||
|
environment:
|
||||||
|
- HOSTNAME=0.0.0.0 # Use "::" for IPv6
|
||||||
|
- PORT=3000
|
||||||
env_file:
|
env_file:
|
||||||
- .env.local
|
- .env.local
|
||||||
healthcheck:
|
healthcheck:
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export default [
|
|||||||
"*.config.js",
|
"*.config.js",
|
||||||
"*.config.mjs",
|
"*.config.mjs",
|
||||||
"e2e/**",
|
"e2e/**",
|
||||||
|
"local-data/**/*.mjs",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ interface ConfigData {
|
|||||||
settingsSyncEnabled: boolean;
|
settingsSyncEnabled: boolean;
|
||||||
stalwartFeaturesEnabled: boolean;
|
stalwartFeaturesEnabled: boolean;
|
||||||
devMode: boolean;
|
devMode: boolean;
|
||||||
|
faviconUrl: string;
|
||||||
|
appLogoLightUrl: string;
|
||||||
|
appLogoDarkUrl: string;
|
||||||
loginLogoLightUrl: string;
|
loginLogoLightUrl: string;
|
||||||
loginLogoDarkUrl: string;
|
loginLogoDarkUrl: string;
|
||||||
loginCompanyName: string;
|
loginCompanyName: string;
|
||||||
@@ -79,6 +82,9 @@ export function useConfig(): AppConfig {
|
|||||||
settingsSyncEnabled: configCache?.settingsSyncEnabled || false,
|
settingsSyncEnabled: configCache?.settingsSyncEnabled || false,
|
||||||
stalwartFeaturesEnabled: configCache?.stalwartFeaturesEnabled ?? true,
|
stalwartFeaturesEnabled: configCache?.stalwartFeaturesEnabled ?? true,
|
||||||
devMode: configCache?.devMode || false,
|
devMode: configCache?.devMode || false,
|
||||||
|
faviconUrl: configCache?.faviconUrl || '/branding/Bulwark_Favicon.svg',
|
||||||
|
appLogoLightUrl: configCache?.appLogoLightUrl || '',
|
||||||
|
appLogoDarkUrl: configCache?.appLogoDarkUrl || '',
|
||||||
loginLogoLightUrl: configCache?.loginLogoLightUrl || '/branding/Bulwark_Logo_Color.svg',
|
loginLogoLightUrl: configCache?.loginLogoLightUrl || '/branding/Bulwark_Logo_Color.svg',
|
||||||
loginLogoDarkUrl: configCache?.loginLogoDarkUrl || '/branding/Bulwark_Logo_White.svg',
|
loginLogoDarkUrl: configCache?.loginLogoDarkUrl || '/branding/Bulwark_Logo_White.svg',
|
||||||
loginCompanyName: configCache?.loginCompanyName || '',
|
loginCompanyName: configCache?.loginCompanyName || '',
|
||||||
@@ -103,6 +109,9 @@ export function useConfig(): AppConfig {
|
|||||||
settingsSyncEnabled: configCache.settingsSyncEnabled,
|
settingsSyncEnabled: configCache.settingsSyncEnabled,
|
||||||
stalwartFeaturesEnabled: configCache.stalwartFeaturesEnabled,
|
stalwartFeaturesEnabled: configCache.stalwartFeaturesEnabled,
|
||||||
devMode: configCache.devMode,
|
devMode: configCache.devMode,
|
||||||
|
faviconUrl: configCache.faviconUrl,
|
||||||
|
appLogoLightUrl: configCache.appLogoLightUrl,
|
||||||
|
appLogoDarkUrl: configCache.appLogoDarkUrl,
|
||||||
loginLogoLightUrl: configCache.loginLogoLightUrl,
|
loginLogoLightUrl: configCache.loginLogoLightUrl,
|
||||||
loginLogoDarkUrl: configCache.loginLogoDarkUrl,
|
loginLogoDarkUrl: configCache.loginLogoDarkUrl,
|
||||||
loginCompanyName: configCache.loginCompanyName,
|
loginCompanyName: configCache.loginCompanyName,
|
||||||
@@ -128,6 +137,9 @@ export function useConfig(): AppConfig {
|
|||||||
settingsSyncEnabled: data.settingsSyncEnabled,
|
settingsSyncEnabled: data.settingsSyncEnabled,
|
||||||
stalwartFeaturesEnabled: data.stalwartFeaturesEnabled,
|
stalwartFeaturesEnabled: data.stalwartFeaturesEnabled,
|
||||||
devMode: data.devMode,
|
devMode: data.devMode,
|
||||||
|
faviconUrl: data.faviconUrl,
|
||||||
|
appLogoLightUrl: data.appLogoLightUrl,
|
||||||
|
appLogoDarkUrl: data.appLogoDarkUrl,
|
||||||
loginLogoLightUrl: data.loginLogoLightUrl,
|
loginLogoLightUrl: data.loginLogoLightUrl,
|
||||||
loginLogoDarkUrl: data.loginLogoDarkUrl,
|
loginLogoDarkUrl: data.loginLogoDarkUrl,
|
||||||
loginCompanyName: data.loginCompanyName,
|
loginCompanyName: data.loginCompanyName,
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
|
||||||
|
export interface InlineAppState {
|
||||||
|
id: string;
|
||||||
|
url: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSidebarApps() {
|
||||||
|
const [showAppsModal, setShowAppsModal] = useState(false);
|
||||||
|
const [inlineApp, setInlineApp] = useState<InlineAppState | null>(null);
|
||||||
|
const [loadedApps, setLoadedApps] = useState<InlineAppState[]>([]);
|
||||||
|
const keepAppsLoaded = useSettingsStore((s) => s.keepAppsLoaded);
|
||||||
|
|
||||||
|
const handleManageApps = useCallback(() => {
|
||||||
|
setShowAppsModal(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleInlineApp = useCallback((appId: string, url: string, name: string) => {
|
||||||
|
const app = { id: appId, url, name };
|
||||||
|
setInlineApp(app);
|
||||||
|
setLoadedApps((prev) => {
|
||||||
|
if (prev.some((a) => a.id === appId)) return prev;
|
||||||
|
return [...prev, app];
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const closeInlineApp = useCallback(() => {
|
||||||
|
if (!keepAppsLoaded) {
|
||||||
|
setLoadedApps((prev) => prev.filter((a) => a.id !== inlineApp?.id));
|
||||||
|
}
|
||||||
|
setInlineApp(null);
|
||||||
|
}, [keepAppsLoaded, inlineApp]);
|
||||||
|
|
||||||
|
const closeAppsModal = useCallback(() => {
|
||||||
|
setShowAppsModal(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
showAppsModal,
|
||||||
|
inlineApp,
|
||||||
|
loadedApps: keepAppsLoaded ? loadedApps : (inlineApp ? [inlineApp] : []),
|
||||||
|
handleManageApps,
|
||||||
|
handleInlineApp,
|
||||||
|
closeInlineApp,
|
||||||
|
closeAppsModal,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -239,9 +239,10 @@ export function useTimeGridInteractions({
|
|||||||
clearTimeout(clickTimerRef.current);
|
clearTimeout(clickTimerRef.current);
|
||||||
clickTimerRef.current = null;
|
clickTimerRef.current = null;
|
||||||
}
|
}
|
||||||
const key = format(day, "yyyy-MM-dd");
|
const d = new Date(day);
|
||||||
setQuickCreate({ dayKey: key, day, hour, top: hour * hourHeight });
|
d.setHours(hour, 0, 0, 0);
|
||||||
}, [hourHeight]);
|
onCreateRange(d);
|
||||||
|
}, [onCreateRange]);
|
||||||
|
|
||||||
const handleQuickCreateSubmit = useCallback(async (title: string) => {
|
const handleQuickCreateSubmit = useCallback(async (title: string) => {
|
||||||
if (!quickCreate) return;
|
if (!quickCreate) return;
|
||||||
|
|||||||
@@ -335,10 +335,7 @@ describe('formatEventSummary', () => {
|
|||||||
duration: 'PT1H30M',
|
duration: 'PT1H30M',
|
||||||
});
|
});
|
||||||
expect(summary.start).toBe('2026-02-17T10:00:00');
|
expect(summary.start).toBe('2026-02-17T10:00:00');
|
||||||
expect(summary.end).toBeTruthy();
|
expect(summary.end).toBe('2026-02-17T11:30:00');
|
||||||
const endDate = new Date(summary.end!);
|
|
||||||
expect(endDate.getHours()).toBe(new Date('2026-02-17T10:00:00').getHours() + 1);
|
|
||||||
expect(endDate.getMinutes()).toBe(new Date('2026-02-17T10:00:00').getMinutes() + 30);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses utcStart and utcEnd when available', () => {
|
it('uses utcStart and utcEnd when available', () => {
|
||||||
@@ -349,6 +346,38 @@ describe('formatEventSummary', () => {
|
|||||||
});
|
});
|
||||||
expect(summary.start).toBe('2026-02-17T15:00:00Z');
|
expect(summary.start).toBe('2026-02-17T15:00:00Z');
|
||||||
expect(summary.end).toBe('2026-02-17T16:00:00Z');
|
expect(summary.end).toBe('2026-02-17T16:00:00Z');
|
||||||
|
expect(summary.isAllDay).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prefers local start over utcStart for all-day events', () => {
|
||||||
|
const summary = formatEventSummary({
|
||||||
|
utcStart: '2026-03-16T00:00:00Z',
|
||||||
|
utcEnd: '2026-03-17T00:00:00Z',
|
||||||
|
start: '2026-03-16T00:00:00',
|
||||||
|
showWithoutTime: true,
|
||||||
|
});
|
||||||
|
expect(summary.start).toBe('2026-03-16T00:00:00');
|
||||||
|
expect(summary.end).toBe('2026-03-17T00:00:00Z');
|
||||||
|
expect(summary.isAllDay).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('computes all-day end in local format when utcEnd is missing', () => {
|
||||||
|
const summary = formatEventSummary({
|
||||||
|
start: '2026-03-16T00:00:00',
|
||||||
|
duration: 'P1D',
|
||||||
|
showWithoutTime: true,
|
||||||
|
});
|
||||||
|
expect(summary.start).toBe('2026-03-16T00:00:00');
|
||||||
|
expect(summary.end).toBe('2026-03-17T00:00:00');
|
||||||
|
expect(summary.isAllDay).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns local format end for timed events with local start', () => {
|
||||||
|
const summary = formatEventSummary({
|
||||||
|
start: '2026-02-17T10:00:00',
|
||||||
|
duration: 'PT1H30M',
|
||||||
|
});
|
||||||
|
expect(summary.end).toBe('2026-02-17T11:30:00');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ describe('config API route', () => {
|
|||||||
delete process.env.SETTINGS_SYNC_ENABLED;
|
delete process.env.SETTINGS_SYNC_ENABLED;
|
||||||
delete process.env.STALWART_FEATURES;
|
delete process.env.STALWART_FEATURES;
|
||||||
delete process.env.DEV_MOCK_JMAP;
|
delete process.env.DEV_MOCK_JMAP;
|
||||||
|
delete process.env.FAVICON_URL;
|
||||||
|
delete process.env.APP_LOGO_LIGHT_URL;
|
||||||
|
delete process.env.APP_LOGO_DARK_URL;
|
||||||
delete process.env.LOGIN_COMPANY_NAME;
|
delete process.env.LOGIN_COMPANY_NAME;
|
||||||
delete process.env.LOGIN_IMPRINT_URL;
|
delete process.env.LOGIN_IMPRINT_URL;
|
||||||
delete process.env.LOGIN_PRIVACY_POLICY_URL;
|
delete process.env.LOGIN_PRIVACY_POLICY_URL;
|
||||||
@@ -60,6 +63,9 @@ describe('config API route', () => {
|
|||||||
expect(config.loginImprintUrl).toBe('');
|
expect(config.loginImprintUrl).toBe('');
|
||||||
expect(config.loginPrivacyPolicyUrl).toBe('');
|
expect(config.loginPrivacyPolicyUrl).toBe('');
|
||||||
expect(config.loginWebsiteUrl).toBe('');
|
expect(config.loginWebsiteUrl).toBe('');
|
||||||
|
expect(config.faviconUrl).toBe('/branding/Bulwark_Favicon.svg');
|
||||||
|
expect(config.appLogoLightUrl).toBe('');
|
||||||
|
expect(config.appLogoDarkUrl).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should use runtime env vars over defaults', async () => {
|
it('should use runtime env vars over defaults', async () => {
|
||||||
@@ -142,4 +148,16 @@ describe('config API route', () => {
|
|||||||
|
|
||||||
expect(config.stalwartFeaturesEnabled).toBe(false);
|
expect(config.stalwartFeaturesEnabled).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should return custom favicon and app logo URLs', async () => {
|
||||||
|
process.env.FAVICON_URL = '/branding/custom-favicon.svg';
|
||||||
|
process.env.APP_LOGO_LIGHT_URL = '/branding/my-logo.svg';
|
||||||
|
process.env.APP_LOGO_DARK_URL = '/branding/my-logo-white.svg';
|
||||||
|
|
||||||
|
const config = await getConfig();
|
||||||
|
|
||||||
|
expect(config.faviconUrl).toBe('/branding/custom-favicon.svg');
|
||||||
|
expect(config.appLogoLightUrl).toBe('/branding/my-logo.svg');
|
||||||
|
expect(config.appLogoDarkUrl).toBe('/branding/my-logo-white.svg');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// @vitest-environment node
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
@@ -87,6 +88,22 @@ function extractUsedKeys(filePath: string): string[] {
|
|||||||
return [...new Set(keys)];
|
return [...new Set(keys)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function collectUsedKeysByFile(files: string[]): Map<string, string[]> {
|
||||||
|
const keyToFiles = new Map<string, string[]>();
|
||||||
|
|
||||||
|
for (const filePath of files) {
|
||||||
|
for (const key of extractUsedKeys(filePath)) {
|
||||||
|
const existing = keyToFiles.get(key) ?? [];
|
||||||
|
if (!existing.includes(filePath)) {
|
||||||
|
existing.push(filePath);
|
||||||
|
keyToFiles.set(key, existing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return keyToFiles;
|
||||||
|
}
|
||||||
|
|
||||||
const locales = fs
|
const locales = fs
|
||||||
.readdirSync(localesDir)
|
.readdirSync(localesDir)
|
||||||
.filter((entry) => fs.statSync(path.join(localesDir, entry)).isDirectory());
|
.filter((entry) => fs.statSync(path.join(localesDir, entry)).isDirectory());
|
||||||
@@ -120,19 +137,22 @@ describe('translations completeness', () => {
|
|||||||
describe('translations used in source code exist in en locale', () => {
|
describe('translations used in source code exist in en locale', () => {
|
||||||
const srcDirs = ['components', 'app', 'hooks', 'lib', 'stores', 'contexts'].map((d) => path.join(rootDir, d));
|
const srcDirs = ['components', 'app', 'hooks', 'lib', 'stores', 'contexts'].map((d) => path.join(rootDir, d));
|
||||||
const allFiles = srcDirs.flatMap((d) => getSourceFiles(d));
|
const allFiles = srcDirs.flatMap((d) => getSourceFiles(d));
|
||||||
const usedKeys = new Set<string>();
|
const usedKeysByFile = collectUsedKeysByFile(allFiles);
|
||||||
for (const f of allFiles) {
|
const usedKeys = [...usedKeysByFile.keys()].sort();
|
||||||
for (const k of extractUsedKeys(f)) {
|
|
||||||
usedKeys.add(k);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
it('all translation keys referenced in source should exist in en locale', () => {
|
it('all translation keys referenced in source should exist in en locale', () => {
|
||||||
const missing = [...usedKeys].sort().filter((key) => resolveKey(referenceData, key) === undefined);
|
const missing = usedKeys.filter((key) => resolveKey(referenceData, key) === undefined);
|
||||||
|
const details = missing.map((key) => {
|
||||||
|
const relativeFiles = (usedKeysByFile.get(key) ?? [])
|
||||||
|
.map((filePath) => path.relative(rootDir, filePath))
|
||||||
|
.sort();
|
||||||
|
|
||||||
|
return `${key}\n used in:\n - ${relativeFiles.join('\n - ')}`;
|
||||||
|
});
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
missing,
|
missing,
|
||||||
`${missing.length} translation key(s) used in source code but missing from en locale:\n${missing.join('\n')}`,
|
`${missing.length} translation key(s) used in source code but missing from en locale:\n${details.join('\n')}`,
|
||||||
).toEqual([]);
|
).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ describe("parseVCard", () => {
|
|||||||
expect(result).toHaveLength(1);
|
expect(result).toHaveLength(1);
|
||||||
const card = result[0];
|
const card = result[0];
|
||||||
|
|
||||||
expect(card.gender).toEqual({ sex: "F", identity: "Female" });
|
expect(card.speakToAs).toEqual({ grammaticalGender: "feminine", pronouns: { p0: { pronouns: "Female" } } });
|
||||||
expect(card.media?.m0).toEqual({
|
expect(card.media?.m0).toEqual({
|
||||||
kind: "logo",
|
kind: "logo",
|
||||||
uri: "https://example.com/logo.png",
|
uri: "https://example.com/logo.png",
|
||||||
@@ -331,7 +331,7 @@ describe("generateVCard", () => {
|
|||||||
components: [{ kind: "given", value: "Jane" }],
|
components: [{ kind: "given", value: "Jane" }],
|
||||||
isOrdered: true,
|
isOrdered: true,
|
||||||
},
|
},
|
||||||
gender: { sex: "F", identity: "Female" },
|
speakToAs: { grammaticalGender: "feminine", pronouns: { p0: { pronouns: "Female" } } },
|
||||||
media: {
|
media: {
|
||||||
m0: { kind: "logo", uri: "https://example.com/logo.png", mediaType: "image/png" },
|
m0: { kind: "logo", uri: "https://example.com/logo.png", mediaType: "image/png" },
|
||||||
m1: { kind: "sound", uri: "https://example.com/sound.ogg", mediaType: "audio/ogg" },
|
m1: { kind: "sound", uri: "https://example.com/sound.ogg", mediaType: "audio/ogg" },
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
/**
|
||||||
|
* Manages per-account state snapshots for fast switching.
|
||||||
|
* When user switches from Account A → B, we snapshot A's store state
|
||||||
|
* into memory, clear stores, then restore B's cached state.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useEmailStore } from '@/stores/email-store';
|
||||||
|
import { useContactStore } from '@/stores/contact-store';
|
||||||
|
import { useCalendarStore } from '@/stores/calendar-store';
|
||||||
|
import { useFilterStore } from '@/stores/filter-store';
|
||||||
|
import { useIdentityStore } from '@/stores/identity-store';
|
||||||
|
import { useVacationStore } from '@/stores/vacation-store';
|
||||||
|
|
||||||
|
// Minimal snapshot shapes — we only capture what we need
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
type StoreSnapshot = Record<string, any>;
|
||||||
|
|
||||||
|
interface AccountSnapshot {
|
||||||
|
email: StoreSnapshot;
|
||||||
|
contact: StoreSnapshot;
|
||||||
|
calendar: StoreSnapshot;
|
||||||
|
filter: StoreSnapshot;
|
||||||
|
identity: StoreSnapshot;
|
||||||
|
vacation: StoreSnapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = new Map<string, AccountSnapshot>();
|
||||||
|
|
||||||
|
/** Capture current store states for the given account */
|
||||||
|
export function snapshotAccount(accountId: string): void {
|
||||||
|
const emailState = useEmailStore.getState();
|
||||||
|
const contactState = useContactStore.getState();
|
||||||
|
const calendarState = useCalendarStore.getState();
|
||||||
|
const filterState = useFilterStore.getState();
|
||||||
|
const identityState = useIdentityStore.getState();
|
||||||
|
const vacationState = useVacationStore.getState();
|
||||||
|
|
||||||
|
cache.set(accountId, {
|
||||||
|
email: {
|
||||||
|
emails: emailState.emails,
|
||||||
|
mailboxes: emailState.mailboxes,
|
||||||
|
selectedEmail: emailState.selectedEmail,
|
||||||
|
selectedMailbox: emailState.selectedMailbox,
|
||||||
|
searchQuery: emailState.searchQuery,
|
||||||
|
quota: emailState.quota,
|
||||||
|
},
|
||||||
|
contact: {
|
||||||
|
contacts: contactState.contacts,
|
||||||
|
addressBooks: contactState.addressBooks,
|
||||||
|
supportsSync: contactState.supportsSync,
|
||||||
|
},
|
||||||
|
calendar: {
|
||||||
|
calendars: calendarState.calendars,
|
||||||
|
events: calendarState.events,
|
||||||
|
selectedCalendarIds: calendarState.selectedCalendarIds,
|
||||||
|
viewMode: calendarState.viewMode,
|
||||||
|
supportsCalendar: calendarState.supportsCalendar,
|
||||||
|
},
|
||||||
|
filter: {
|
||||||
|
rules: filterState.rules,
|
||||||
|
isSupported: filterState.isSupported,
|
||||||
|
},
|
||||||
|
identity: {
|
||||||
|
identities: identityState.identities,
|
||||||
|
preferredPrimaryId: identityState.preferredPrimaryId,
|
||||||
|
},
|
||||||
|
vacation: {
|
||||||
|
isEnabled: vacationState.isEnabled,
|
||||||
|
isSupported: vacationState.isSupported,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Restore cached store states for the given account. Returns false if no cache exists. */
|
||||||
|
export function restoreAccount(accountId: string): boolean {
|
||||||
|
const snapshot = cache.get(accountId);
|
||||||
|
if (!snapshot) return false;
|
||||||
|
|
||||||
|
useEmailStore.setState(snapshot.email);
|
||||||
|
useContactStore.setState(snapshot.contact);
|
||||||
|
useCalendarStore.setState(snapshot.calendar);
|
||||||
|
useFilterStore.setState(snapshot.filter);
|
||||||
|
useIdentityStore.setState(snapshot.identity);
|
||||||
|
useVacationStore.setState(snapshot.vacation);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clear all stores (used before restoring a different account) */
|
||||||
|
export function clearAllStores(): void {
|
||||||
|
useEmailStore.setState({
|
||||||
|
emails: [],
|
||||||
|
mailboxes: [],
|
||||||
|
selectedEmail: null,
|
||||||
|
selectedMailbox: '',
|
||||||
|
isLoading: false,
|
||||||
|
error: null,
|
||||||
|
searchQuery: '',
|
||||||
|
quota: null,
|
||||||
|
});
|
||||||
|
useIdentityStore.getState().clearIdentities();
|
||||||
|
useContactStore.getState().clearContacts();
|
||||||
|
useVacationStore.getState().clearState();
|
||||||
|
useCalendarStore.getState().clearState();
|
||||||
|
useFilterStore.getState().clearState();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Evict cached state for one account */
|
||||||
|
export function evictAccount(accountId: string): void {
|
||||||
|
cache.delete(accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Evict all cached states */
|
||||||
|
export function evictAll(): void {
|
||||||
|
cache.clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
/**
|
||||||
|
* Utilities for multi-account support:
|
||||||
|
* - Account ID generation
|
||||||
|
* - Deterministic avatar colors
|
||||||
|
* - Account-scoped localStorage keys
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Generate a unique, deterministic account ID from username and server URL */
|
||||||
|
export function generateAccountId(username: string, serverUrl: string): string {
|
||||||
|
const host = new URL(serverUrl).hostname;
|
||||||
|
return `${username}@${host}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deterministic avatar/accent color from an email string */
|
||||||
|
export function generateAvatarColor(email: string): string {
|
||||||
|
let hash = 0;
|
||||||
|
for (let i = 0; i < email.length; i++) {
|
||||||
|
hash = ((hash << 5) - hash + email.charCodeAt(i)) | 0;
|
||||||
|
}
|
||||||
|
// 12 distinct, accessible hues
|
||||||
|
const colors = [
|
||||||
|
'#2563eb', // blue
|
||||||
|
'#7c3aed', // violet
|
||||||
|
'#db2777', // pink
|
||||||
|
'#dc2626', // red
|
||||||
|
'#ea580c', // orange
|
||||||
|
'#d97706', // amber
|
||||||
|
'#65a30d', // lime
|
||||||
|
'#16a34a', // green
|
||||||
|
'#0d9488', // teal
|
||||||
|
'#0891b2', // cyan
|
||||||
|
'#6366f1', // indigo
|
||||||
|
'#9333ea', // purple
|
||||||
|
];
|
||||||
|
return colors[Math.abs(hash) % colors.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get initials for an avatar from a display name or email */
|
||||||
|
export function getInitials(name: string, email?: string): string {
|
||||||
|
if (name) {
|
||||||
|
const parts = name.trim().split(/\s+/);
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
|
||||||
|
}
|
||||||
|
return parts[0][0]?.toUpperCase() ?? '?';
|
||||||
|
}
|
||||||
|
if (email) {
|
||||||
|
return email[0]?.toUpperCase() ?? '?';
|
||||||
|
}
|
||||||
|
return '?';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build an account-scoped localStorage key */
|
||||||
|
export function getAccountScopedKey(baseKey: string, accountId: string): string {
|
||||||
|
return `${baseKey}::${accountId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Maximum number of accounts allowed */
|
||||||
|
export const MAX_ACCOUNTS = 5;
|
||||||
@@ -1,2 +1,7 @@
|
|||||||
export const SESSION_COOKIE = 'jmap_session';
|
export const SESSION_COOKIE = 'jmap_session';
|
||||||
export const SESSION_COOKIE_MAX_AGE = 30 * 24 * 60 * 60;
|
export const SESSION_COOKIE_MAX_AGE = 30 * 24 * 60 * 60;
|
||||||
|
|
||||||
|
/** Get the cookie name for a given account slot (0-4). Slot 0 uses the legacy name. */
|
||||||
|
export function sessionCookieName(slot: number): string {
|
||||||
|
return slot === 0 ? SESSION_COOKIE : `${SESSION_COOKIE}_${slot}`;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export function replaceWindowLocation(url: string): void {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.location.replace(url);
|
||||||
|
}
|
||||||
@@ -449,6 +449,7 @@ export interface EventSummary {
|
|||||||
title: string;
|
title: string;
|
||||||
start: string | null;
|
start: string | null;
|
||||||
end: string | null;
|
end: string | null;
|
||||||
|
isAllDay: boolean;
|
||||||
location: string | null;
|
location: string | null;
|
||||||
organizer: string | null;
|
organizer: string | null;
|
||||||
organizerEmail: string | null;
|
organizerEmail: string | null;
|
||||||
@@ -495,6 +496,8 @@ export function formatEventSummary(event: Partial<CalendarEvent>): EventSummary
|
|||||||
if (!organizer) organizer = organizerEmail;
|
if (!organizer) organizer = organizerEmail;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isAllDay = event.showWithoutTime ?? false;
|
||||||
|
|
||||||
let end: string | null = null;
|
let end: string | null = null;
|
||||||
if (event.utcEnd) {
|
if (event.utcEnd) {
|
||||||
end = event.utcEnd;
|
end = event.utcEnd;
|
||||||
@@ -502,10 +505,17 @@ export function formatEventSummary(event: Partial<CalendarEvent>): EventSummary
|
|||||||
end = addDurationToDate(event.start, event.duration, event.timeZone);
|
end = addDurationToDate(event.start, event.duration, event.timeZone);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// For all-day events, prefer the local start (no timezone) to avoid
|
||||||
|
// UTC conversion shifting the displayed date in non-UTC timezones.
|
||||||
|
const start = isAllDay
|
||||||
|
? (event.start || null)
|
||||||
|
: (event.utcStart || event.start || null);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title: event.title || '',
|
title: event.title || '',
|
||||||
start: event.utcStart || event.start || null,
|
start,
|
||||||
end,
|
end,
|
||||||
|
isAllDay,
|
||||||
location,
|
location,
|
||||||
organizer,
|
organizer,
|
||||||
organizerEmail,
|
organizerEmail,
|
||||||
@@ -530,6 +540,19 @@ function addDurationToDate(start: string, duration: string, _timeZone?: string |
|
|||||||
date.setMinutes(date.getMinutes() + minutes);
|
date.setMinutes(date.getMinutes() + minutes);
|
||||||
date.setSeconds(date.getSeconds() + seconds);
|
date.setSeconds(date.getSeconds() + seconds);
|
||||||
|
|
||||||
|
// If the input is a local datetime (no UTC 'Z' suffix), return a local
|
||||||
|
// format string so that all-day date arithmetic isn't shifted by the
|
||||||
|
// browser's UTC offset (toISOString converts to UTC).
|
||||||
|
if (!start.endsWith('Z') && !start.includes('+')) {
|
||||||
|
const y = date.getFullYear();
|
||||||
|
const m = String(date.getMonth() + 1).padStart(2, '0');
|
||||||
|
const d = String(date.getDate()).padStart(2, '0');
|
||||||
|
const h = String(date.getHours()).padStart(2, '0');
|
||||||
|
const min = String(date.getMinutes()).padStart(2, '0');
|
||||||
|
const s = String(date.getSeconds()).padStart(2, '0');
|
||||||
|
return `${y}-${m}-${d}T${h}:${min}:${s}`;
|
||||||
|
}
|
||||||
|
|
||||||
return date.toISOString();
|
return date.toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -79,6 +79,8 @@ export function buildWeekSegments(events: CalendarEvent[], weekDays: Date[]): Ca
|
|||||||
if (left.event.showWithoutTime !== right.event.showWithoutTime) {
|
if (left.event.showWithoutTime !== right.event.showWithoutTime) {
|
||||||
return left.event.showWithoutTime ? -1 : 1;
|
return left.event.showWithoutTime ? -1 : 1;
|
||||||
}
|
}
|
||||||
|
const timeDiff = new Date(left.event.start).getTime() - new Date(right.event.start).getTime();
|
||||||
|
if (timeDiff !== 0) return timeDiff;
|
||||||
return (left.event.title || "").localeCompare(right.event.title || "");
|
return (left.event.title || "").localeCompare(right.event.title || "");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -140,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];
|
||||||
|
}
|
||||||
|
|||||||
+788
-102
File diff suppressed because it is too large
Load Diff
+82
-2
@@ -36,6 +36,9 @@ export interface Email {
|
|||||||
verdict: string;
|
verdict: string;
|
||||||
explanation: string;
|
explanation: string;
|
||||||
};
|
};
|
||||||
|
// S/MIME support
|
||||||
|
blobId?: string;
|
||||||
|
bodyStructure?: EmailBodyPart;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthenticationResults {
|
export interface AuthenticationResults {
|
||||||
@@ -157,9 +160,13 @@ export interface Identity {
|
|||||||
|
|
||||||
export interface ContactCard {
|
export interface ContactCard {
|
||||||
id: string;
|
id: string;
|
||||||
|
originalId?: string;
|
||||||
uid?: string;
|
uid?: string;
|
||||||
addressBookIds: Record<string, boolean>;
|
addressBookIds: Record<string, boolean>;
|
||||||
kind?: 'individual' | 'group' | 'org' | 'location' | 'device' | 'application';
|
kind?: 'individual' | 'group' | 'org' | 'location' | 'device' | 'application';
|
||||||
|
accountId?: string;
|
||||||
|
accountName?: string;
|
||||||
|
isShared?: boolean;
|
||||||
language?: string;
|
language?: string;
|
||||||
name?: ContactName;
|
name?: ContactName;
|
||||||
nicknames?: Record<string, ContactNickname>;
|
nicknames?: Record<string, ContactNickname>;
|
||||||
@@ -180,7 +187,10 @@ export interface ContactCard {
|
|||||||
relatedTo?: Record<string, ContactRelation>;
|
relatedTo?: Record<string, ContactRelation>;
|
||||||
keywords?: Record<string, boolean>;
|
keywords?: Record<string, boolean>;
|
||||||
members?: Record<string, boolean>;
|
members?: Record<string, boolean>;
|
||||||
gender?: { sex?: string; identity?: string };
|
speakToAs?: {
|
||||||
|
grammaticalGender?: string;
|
||||||
|
pronouns?: Record<string, { pronouns: string; pref?: number; contexts?: Record<string, boolean> }>;
|
||||||
|
};
|
||||||
calendarUri?: string;
|
calendarUri?: string;
|
||||||
schedulingUri?: string;
|
schedulingUri?: string;
|
||||||
freeBusyUri?: string;
|
freeBusyUri?: string;
|
||||||
@@ -242,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;
|
||||||
@@ -274,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -313,12 +354,16 @@ export interface ContactRelation {
|
|||||||
|
|
||||||
export interface AddressBook {
|
export interface AddressBook {
|
||||||
id: string;
|
id: string;
|
||||||
|
originalId?: string;
|
||||||
name: string;
|
name: string;
|
||||||
description?: string | null;
|
description?: string | null;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
isDefault?: boolean;
|
isDefault?: boolean;
|
||||||
isSubscribed?: boolean;
|
isSubscribed?: boolean;
|
||||||
myRights?: AddressBookRights;
|
myRights?: AddressBookRights;
|
||||||
|
accountId?: string;
|
||||||
|
accountName?: string;
|
||||||
|
isShared?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AddressBookRights {
|
export interface AddressBookRights {
|
||||||
@@ -364,6 +409,7 @@ export interface DeliveryStatus {
|
|||||||
|
|
||||||
export interface Calendar {
|
export interface Calendar {
|
||||||
id: string;
|
id: string;
|
||||||
|
originalId?: string;
|
||||||
name: string;
|
name: string;
|
||||||
description: string | null;
|
description: string | null;
|
||||||
color: string | null;
|
color: string | null;
|
||||||
@@ -377,6 +423,9 @@ export interface Calendar {
|
|||||||
timeZone: string | null;
|
timeZone: string | null;
|
||||||
shareWith: Record<string, CalendarRights> | null;
|
shareWith: Record<string, CalendarRights> | null;
|
||||||
myRights: CalendarRights;
|
myRights: CalendarRights;
|
||||||
|
accountId?: string;
|
||||||
|
accountName?: string;
|
||||||
|
isShared?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CalendarRights {
|
export interface CalendarRights {
|
||||||
@@ -392,7 +441,12 @@ export interface CalendarRights {
|
|||||||
|
|
||||||
export interface CalendarEvent {
|
export interface CalendarEvent {
|
||||||
id: string;
|
id: string;
|
||||||
|
originalId?: string;
|
||||||
calendarIds: Record<string, boolean>;
|
calendarIds: Record<string, boolean>;
|
||||||
|
originalCalendarIds?: Record<string, boolean>;
|
||||||
|
accountId?: string;
|
||||||
|
accountName?: string;
|
||||||
|
isShared?: boolean;
|
||||||
isDraft: boolean;
|
isDraft: boolean;
|
||||||
isOrigin: boolean;
|
isOrigin: boolean;
|
||||||
utcStart: string | null;
|
utcStart: string | null;
|
||||||
@@ -541,6 +595,32 @@ export interface CalendarRelation {
|
|||||||
relation: Record<string, boolean> | null;
|
relation: Record<string, boolean> | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CalendarTask {
|
||||||
|
id: string;
|
||||||
|
calendarIds: Record<string, boolean>;
|
||||||
|
'@type': 'Task';
|
||||||
|
uid: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
due: string | null;
|
||||||
|
start: string | null;
|
||||||
|
duration: string | null;
|
||||||
|
timeZone: string | null;
|
||||||
|
showWithoutTime: boolean;
|
||||||
|
progress: 'needs-action' | 'in-process' | 'completed' | 'cancelled';
|
||||||
|
progressUpdated: string | null;
|
||||||
|
priority: number;
|
||||||
|
privacy: 'public' | 'private' | 'secret';
|
||||||
|
keywords: Record<string, boolean> | null;
|
||||||
|
categories: Record<string, boolean> | null;
|
||||||
|
color: string | null;
|
||||||
|
created: string | null;
|
||||||
|
updated: string;
|
||||||
|
recurrenceRules: CalendarRecurrenceRule[] | null;
|
||||||
|
alerts: Record<string, CalendarEventAlert> | null;
|
||||||
|
relatedTo: Record<string, CalendarRelation> | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CalendarParticipantIdentity {
|
export interface CalendarParticipantIdentity {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -1,2 +1,7 @@
|
|||||||
export const OAUTH_SCOPES = 'openid email profile';
|
export const OAUTH_SCOPES = 'openid email profile';
|
||||||
export const REFRESH_TOKEN_COOKIE = 'jmap_rt';
|
export const REFRESH_TOKEN_COOKIE = 'jmap_rt';
|
||||||
|
|
||||||
|
/** Get the cookie name for a given account slot (0-4). Slot 0 uses the legacy name. */
|
||||||
|
export function refreshTokenCookieName(slot: number): string {
|
||||||
|
return slot === 0 ? REFRESH_TOKEN_COOKIE : `${REFRESH_TOKEN_COOKIE}_${slot}`;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
||||||
import { readFile, writeFile, unlink, mkdir } from 'node:fs/promises';
|
import { readFile, writeFile, unlink, mkdir, rename } from 'node:fs/promises';
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
@@ -45,7 +45,10 @@ export async function saveUserSettings(username: string, serverUrl: string, sett
|
|||||||
const tag = cipher.getAuthTag();
|
const tag = cipher.getAuthTag();
|
||||||
|
|
||||||
const data = Buffer.concat([iv, tag, encrypted]);
|
const data = Buffer.concat([iv, tag, encrypted]);
|
||||||
await writeFile(getSettingsPath(username, serverUrl), data);
|
const targetPath = getSettingsPath(username, serverUrl);
|
||||||
|
const tmpPath = targetPath + '.tmp';
|
||||||
|
await writeFile(tmpPath, data);
|
||||||
|
await rename(tmpPath, targetPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadUserSettings(username: string, serverUrl: string): Promise<Record<string, unknown> | null> {
|
export async function loadUserSettings(username: string, serverUrl: string): Promise<Record<string, unknown> | null> {
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { describe, it, expect, vi, beforeAll } from 'vitest';
|
||||||
|
import {
|
||||||
|
pemToDer,
|
||||||
|
derToPem,
|
||||||
|
isPem,
|
||||||
|
parseCertificateDer,
|
||||||
|
parseCertificatePemOrDer,
|
||||||
|
computeFingerprint,
|
||||||
|
classifyCapabilities,
|
||||||
|
extractCertificateInfo,
|
||||||
|
} from '../certificate-utils';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
|
||||||
|
// Generate a self-signed test certificate using Web Crypto + pkijs
|
||||||
|
let testCertDer: ArrayBuffer;
|
||||||
|
let testCert: pkijs.Certificate;
|
||||||
|
let testKeyPair: globalThis.CryptoKeyPair;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const cryptoEngine = new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
});
|
||||||
|
pkijs.setEngine('test', crypto, cryptoEngine);
|
||||||
|
|
||||||
|
// Generate RSA key pair
|
||||||
|
testKeyPair = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['sign', 'verify'],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Build a minimal self-signed X.509 certificate
|
||||||
|
testCert = new pkijs.Certificate();
|
||||||
|
testCert.version = 2; // v3
|
||||||
|
testCert.serialNumber = new asn1js.Integer({ value: 1 });
|
||||||
|
|
||||||
|
testCert.issuer.typesAndValues.push(new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '2.5.4.3', // CN
|
||||||
|
value: new asn1js.Utf8String({ value: 'Test CA' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
testCert.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '2.5.4.3', // CN
|
||||||
|
value: new asn1js.Utf8String({ value: 'Test User' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
testCert.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '1.2.840.113549.1.9.1', // emailAddress
|
||||||
|
value: new asn1js.IA5String({ value: 'test@example.com' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
testCert.notBefore.value = new Date('2024-01-01T00:00:00Z');
|
||||||
|
testCert.notAfter.value = new Date('2030-12-31T23:59:59Z');
|
||||||
|
|
||||||
|
await testCert.subjectPublicKeyInfo.importKey(testKeyPair.publicKey, cryptoEngine);
|
||||||
|
|
||||||
|
// Add KeyUsage extension: digitalSignature + keyEncipherment
|
||||||
|
const bitArray = new ArrayBuffer(1);
|
||||||
|
const bitView = new Uint8Array(bitArray);
|
||||||
|
bitView[0] = 0b10100000; // digitalSignature (bit 0) + keyEncipherment (bit 2)
|
||||||
|
|
||||||
|
testCert.extensions = [
|
||||||
|
new pkijs.Extension({
|
||||||
|
extnID: '2.5.29.15', // keyUsage
|
||||||
|
critical: true,
|
||||||
|
extnValue: new asn1js.OctetString({
|
||||||
|
valueHex: new Uint8Array(new asn1js.BitString({
|
||||||
|
valueHex: bitArray,
|
||||||
|
unusedBits: 3,
|
||||||
|
}).toBER(false)),
|
||||||
|
}).toBER(false) as ArrayBuffer,
|
||||||
|
parsedValue: {
|
||||||
|
digitalSignature: true,
|
||||||
|
contentCommitment: false,
|
||||||
|
keyEncipherment: true,
|
||||||
|
dataEncipherment: false,
|
||||||
|
keyAgreement: false,
|
||||||
|
keyCertSign: false,
|
||||||
|
cRLSign: false,
|
||||||
|
encipherOnly: false,
|
||||||
|
decipherOnly: false,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
|
await testCert.sign(testKeyPair.privateKey, 'SHA-256', cryptoEngine);
|
||||||
|
|
||||||
|
// toBER may return a non-standard ArrayBuffer in jsdom; normalize it
|
||||||
|
const rawDer = testCert.toSchema(true).toBER(false);
|
||||||
|
testCertDer = new Uint8Array(rawDer).buffer;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('certificate-utils', () => {
|
||||||
|
describe('pemToDer / derToPem roundtrip', () => {
|
||||||
|
it('converts PEM to DER and back', () => {
|
||||||
|
const pem = derToPem(testCertDer, 'CERTIFICATE');
|
||||||
|
expect(pem).toContain('-----BEGIN CERTIFICATE-----');
|
||||||
|
expect(pem).toContain('-----END CERTIFICATE-----');
|
||||||
|
|
||||||
|
const der2 = pemToDer(pem);
|
||||||
|
expect(new Uint8Array(der2)).toEqual(new Uint8Array(testCertDer));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('derToPem wraps lines at 64 chars', () => {
|
||||||
|
const pem = derToPem(testCertDer, 'CERTIFICATE');
|
||||||
|
const lines = pem.split('\n');
|
||||||
|
// All content lines (not headers) should be <= 64 chars
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line.startsWith('-----')) {
|
||||||
|
expect(line.length).toBeLessThanOrEqual(64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isPem', () => {
|
||||||
|
it('returns true for certificate PEM', () => {
|
||||||
|
expect(isPem('-----BEGIN CERTIFICATE-----\nMIIB...\n-----END CERTIFICATE-----')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true for PKCS12 PEM', () => {
|
||||||
|
expect(isPem('-----BEGIN PKCS12-----\ndata\n-----END PKCS12-----')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true for private key PEM', () => {
|
||||||
|
expect(isPem('-----BEGIN PRIVATE KEY-----\ndata\n-----END PRIVATE KEY-----')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true for encrypted private key PEM', () => {
|
||||||
|
expect(isPem('-----BEGIN ENCRYPTED PRIVATE KEY-----\ndata\n-----END ENCRYPTED PRIVATE KEY-----')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false for non-PEM data', () => {
|
||||||
|
expect(isPem('hello world')).toBe(false);
|
||||||
|
expect(isPem('')).toBe(false);
|
||||||
|
expect(isPem('MIIB...')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parseCertificateDer', () => {
|
||||||
|
it('parses a valid DER certificate', () => {
|
||||||
|
const cert = parseCertificateDer(testCertDer);
|
||||||
|
expect(cert).toBeInstanceOf(pkijs.Certificate);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on invalid DER data', () => {
|
||||||
|
const garbage = new Uint8Array([0, 1, 2, 3]).buffer;
|
||||||
|
expect(() => parseCertificateDer(garbage)).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parseCertificatePemOrDer', () => {
|
||||||
|
it('parses DER ArrayBuffer', () => {
|
||||||
|
const cert = parseCertificatePemOrDer(testCertDer);
|
||||||
|
expect(cert).toBeInstanceOf(pkijs.Certificate);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses PEM string', () => {
|
||||||
|
const pem = derToPem(testCertDer, 'CERTIFICATE');
|
||||||
|
const cert = parseCertificatePemOrDer(pem);
|
||||||
|
expect(cert).toBeInstanceOf(pkijs.Certificate);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on non-PEM string', () => {
|
||||||
|
expect(() => parseCertificatePemOrDer('not a pem')).toThrow('String input is not PEM-encoded');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('computeFingerprint', () => {
|
||||||
|
it('returns hex fingerprint with colons', async () => {
|
||||||
|
const fp = await computeFingerprint(testCertDer);
|
||||||
|
expect(fp).toMatch(/^[0-9a-f]{2}(:[0-9a-f]{2}){31}$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is deterministic', async () => {
|
||||||
|
const fp1 = await computeFingerprint(testCertDer);
|
||||||
|
const fp2 = await computeFingerprint(testCertDer);
|
||||||
|
expect(fp1).toBe(fp2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('classifyCapabilities', () => {
|
||||||
|
it('detects sign + encrypt from KeyUsage', () => {
|
||||||
|
const caps = classifyCapabilities(testCert);
|
||||||
|
expect(caps.canSign).toBe(true);
|
||||||
|
expect(caps.canEncrypt).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('extractCertificateInfo', () => {
|
||||||
|
it('extracts full certificate metadata', async () => {
|
||||||
|
const info = await extractCertificateInfo(testCert, testCertDer);
|
||||||
|
|
||||||
|
expect(info.subject).toContain('CN=Test User');
|
||||||
|
expect(info.issuer).toContain('CN=Test CA');
|
||||||
|
expect(info.notBefore).toBe('2024-01-01T00:00:00.000Z');
|
||||||
|
expect(info.notAfter).toBe('2030-12-31T23:59:59.000Z');
|
||||||
|
expect(info.fingerprint).toMatch(/^[0-9a-f]{2}(:[0-9a-f]{2}){31}$/);
|
||||||
|
expect(info.algorithm).toMatch(/^RSA/);
|
||||||
|
expect(info.emailAddresses).toContain('test@example.com');
|
||||||
|
expect(info.capabilities.canSign).toBe(true);
|
||||||
|
expect(info.capabilities.canEncrypt).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns serialNumber as hex', async () => {
|
||||||
|
const info = await extractCertificateInfo(testCert, testCertDer);
|
||||||
|
// Serial number 1 → should be hex string
|
||||||
|
expect(info.serialNumber).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
|
import 'fake-indexeddb/auto';
|
||||||
|
|
||||||
|
// Each test file gets a fresh global indexedDB via fake-indexeddb/auto.
|
||||||
|
// Since openDB() caches connections implicitly, we re-import the module for each test.
|
||||||
|
// However, to keep it simple, we'll just test in order and accept cumulative state,
|
||||||
|
// or we can test with unique IDs.
|
||||||
|
|
||||||
|
import {
|
||||||
|
saveKeyRecord,
|
||||||
|
getKeyRecord,
|
||||||
|
getKeyRecordForEmail,
|
||||||
|
listKeyRecords,
|
||||||
|
deleteKeyRecord,
|
||||||
|
savePublicCert,
|
||||||
|
getPublicCertForEmail,
|
||||||
|
listPublicCerts,
|
||||||
|
deletePublicCert,
|
||||||
|
} from '../key-storage';
|
||||||
|
import type { SmimeKeyRecord, SmimePublicCert } from '../types';
|
||||||
|
|
||||||
|
function makeKeyRecord(overrides: Partial<SmimeKeyRecord> = {}): SmimeKeyRecord {
|
||||||
|
return {
|
||||||
|
id: 'key-1',
|
||||||
|
email: 'user@example.com',
|
||||||
|
certificate: new ArrayBuffer(10),
|
||||||
|
certificateChain: [],
|
||||||
|
encryptedPrivateKey: new ArrayBuffer(32),
|
||||||
|
salt: new ArrayBuffer(16),
|
||||||
|
iv: new ArrayBuffer(12),
|
||||||
|
kdfIterations: 600000,
|
||||||
|
issuer: 'CN=Test CA',
|
||||||
|
subject: 'CN=Test User',
|
||||||
|
serialNumber: '01',
|
||||||
|
notBefore: '2024-01-01T00:00:00Z',
|
||||||
|
notAfter: '2030-12-31T23:59:59Z',
|
||||||
|
fingerprint: 'aa:bb:cc',
|
||||||
|
algorithm: 'RSA-2048',
|
||||||
|
capabilities: { canSign: true, canEncrypt: true },
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makePublicCert(overrides: Partial<SmimePublicCert> = {}): SmimePublicCert {
|
||||||
|
return {
|
||||||
|
id: 'cert-1',
|
||||||
|
email: 'recipient@example.com',
|
||||||
|
certificate: new ArrayBuffer(10),
|
||||||
|
issuer: 'CN=Test CA',
|
||||||
|
subject: 'CN=Recipient',
|
||||||
|
notBefore: '2024-01-01T00:00:00Z',
|
||||||
|
notAfter: '2030-12-31T23:59:59Z',
|
||||||
|
fingerprint: 'dd:ee:ff',
|
||||||
|
source: 'manual',
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use unique IDs for each test to avoid state leakage
|
||||||
|
let testCounter = 0;
|
||||||
|
function uid() { return `test-${++testCounter}-${Date.now()}`; }
|
||||||
|
|
||||||
|
describe('key-storage', () => {
|
||||||
|
describe('key records', () => {
|
||||||
|
it('saves and retrieves a key record by id', async () => {
|
||||||
|
const id = uid();
|
||||||
|
const record = makeKeyRecord({ id });
|
||||||
|
await saveKeyRecord(record);
|
||||||
|
const retrieved = await getKeyRecord(id);
|
||||||
|
expect(retrieved).toBeDefined();
|
||||||
|
expect(retrieved!.id).toBe(id);
|
||||||
|
expect(retrieved!.email).toBe('user@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined for non-existent key record', async () => {
|
||||||
|
const result = await getKeyRecord('absolutely-non-existent-' + uid());
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retrieves key record by email', async () => {
|
||||||
|
const id = uid();
|
||||||
|
const email = `alice-${id}@example.com`;
|
||||||
|
const record = makeKeyRecord({ id, email });
|
||||||
|
await saveKeyRecord(record);
|
||||||
|
const result = await getKeyRecordForEmail(email);
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result!.email).toBe(email);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists key records (includes previously saved)', async () => {
|
||||||
|
const id1 = uid();
|
||||||
|
const id2 = uid();
|
||||||
|
await saveKeyRecord(makeKeyRecord({ id: id1, email: `${id1}@example.com` }));
|
||||||
|
await saveKeyRecord(makeKeyRecord({ id: id2, email: `${id2}@example.com` }));
|
||||||
|
const records = await listKeyRecords();
|
||||||
|
expect(records.length).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(records.find(r => r.id === id1)).toBeDefined();
|
||||||
|
expect(records.find(r => r.id === id2)).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes a key record', async () => {
|
||||||
|
const id = uid();
|
||||||
|
const record = makeKeyRecord({ id });
|
||||||
|
await saveKeyRecord(record);
|
||||||
|
await deleteKeyRecord(id);
|
||||||
|
const result = await getKeyRecord(id);
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates existing record with same id', async () => {
|
||||||
|
const id = uid();
|
||||||
|
const record1 = makeKeyRecord({ id, email: 'old@example.com' });
|
||||||
|
await saveKeyRecord(record1);
|
||||||
|
const record2 = makeKeyRecord({ id, email: 'new@example.com' });
|
||||||
|
await saveKeyRecord(record2);
|
||||||
|
const retrieved = await getKeyRecord(id);
|
||||||
|
expect(retrieved!.email).toBe('new@example.com');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('public certs', () => {
|
||||||
|
it('saves and retrieves by email', async () => {
|
||||||
|
const id = uid();
|
||||||
|
const email = `recipient-${id}@example.com`;
|
||||||
|
const cert = makePublicCert({ id, email });
|
||||||
|
await savePublicCert(cert);
|
||||||
|
const result = await getPublicCertForEmail(email);
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result!.email).toBe(email);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists public certs (includes previously saved)', async () => {
|
||||||
|
const id1 = uid();
|
||||||
|
const id2 = uid();
|
||||||
|
await savePublicCert(makePublicCert({ id: id1, email: `${id1}@test.com` }));
|
||||||
|
await savePublicCert(makePublicCert({ id: id2, email: `${id2}@test.com` }));
|
||||||
|
const certs = await listPublicCerts();
|
||||||
|
expect(certs.find(c => c.id === id1)).toBeDefined();
|
||||||
|
expect(certs.find(c => c.id === id2)).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes a public cert', async () => {
|
||||||
|
const id = uid();
|
||||||
|
const cert = makePublicCert({ id });
|
||||||
|
await savePublicCert(cert);
|
||||||
|
await deletePublicCert(id);
|
||||||
|
const certs = await listPublicCerts();
|
||||||
|
expect(certs.find(c => c.id === id)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { buildMimeMessage, quotedPrintableEncode, base64Encode } from '../mime-builder';
|
||||||
|
|
||||||
|
// Mock crypto.randomUUID and crypto.getRandomValues for deterministic tests
|
||||||
|
beforeEach(() => {
|
||||||
|
let uuidCounter = 0;
|
||||||
|
vi.spyOn(crypto, 'randomUUID').mockImplementation(
|
||||||
|
() => `00000000-0000-0000-0000-${String(++uuidCounter).padStart(12, '0')}` as `${string}-${string}-${string}-${string}-${string}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.spyOn(crypto, 'getRandomValues').mockImplementation(<T extends ArrayBufferView | null>(array: T): T => {
|
||||||
|
if (array) {
|
||||||
|
const u8 = new Uint8Array((array as unknown as Uint8Array).buffer);
|
||||||
|
for (let i = 0; i < u8.length; i++) u8[i] = i;
|
||||||
|
}
|
||||||
|
return array;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mime-builder', () => {
|
||||||
|
describe('buildMimeMessage', () => {
|
||||||
|
it('builds a text-only message', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { name: 'Alice', email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'Hello',
|
||||||
|
textBody: 'Hi Bob!',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('From: "Alice" <alice@example.com>');
|
||||||
|
expect(text).toContain('To: bob@example.com');
|
||||||
|
expect(text).toContain('Subject: Hello');
|
||||||
|
expect(text).toContain('Content-Type: text/plain; charset=utf-8');
|
||||||
|
expect(text).toContain('MIME-Version: 1.0');
|
||||||
|
expect(text).toContain('Hi Bob!');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds a text + HTML multipart/alternative', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'Test',
|
||||||
|
textBody: 'Plain text',
|
||||||
|
htmlBody: '<p>HTML body</p>',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('Content-Type: multipart/alternative');
|
||||||
|
expect(text).toContain('Content-Type: text/plain; charset=utf-8');
|
||||||
|
expect(text).toContain('Content-Type: text/html; charset=utf-8');
|
||||||
|
expect(text).toContain('Plain text');
|
||||||
|
expect(text).toContain('<p>HTML body</p>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds HTML-only message', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'HTML only',
|
||||||
|
htmlBody: '<h1>Hello</h1>',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('Content-Type: text/html; charset=utf-8');
|
||||||
|
expect(text).toContain('<h1>Hello</h1>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds message with attachments', () => {
|
||||||
|
const attachment = {
|
||||||
|
filename: 'test.txt',
|
||||||
|
contentType: 'text/plain',
|
||||||
|
content: new TextEncoder().encode('file content').buffer,
|
||||||
|
};
|
||||||
|
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'With attachment',
|
||||||
|
textBody: 'See attached',
|
||||||
|
attachments: [attachment],
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('Content-Type: multipart/mixed');
|
||||||
|
expect(text).toContain('Content-Disposition: attachment; filename="test.txt"');
|
||||||
|
expect(text).toContain('Content-Transfer-Encoding: base64');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds message with inline attachment (cid)', () => {
|
||||||
|
const inline = {
|
||||||
|
filename: 'image.png',
|
||||||
|
contentType: 'image/png',
|
||||||
|
content: new Uint8Array([0x89, 0x50, 0x4E, 0x47]).buffer,
|
||||||
|
cid: 'img1',
|
||||||
|
};
|
||||||
|
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'Inline',
|
||||||
|
htmlBody: '<img src="cid:img1">',
|
||||||
|
attachments: [inline],
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('Content-Disposition: inline; filename="image.png"');
|
||||||
|
expect(text).toContain('Content-ID: <img1>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes CC header when provided', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
cc: [{ name: 'Charlie', email: 'charlie@example.com' }],
|
||||||
|
subject: 'CC test',
|
||||||
|
textBody: 'Hello',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('Cc: "Charlie" <charlie@example.com>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits BCC from MIME headers', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
bcc: [{ email: 'secret@example.com' }],
|
||||||
|
subject: 'BCC test',
|
||||||
|
textBody: 'Hello',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).not.toContain('Bcc');
|
||||||
|
expect(text).not.toContain('secret@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes In-Reply-To and References', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'Re: Thread',
|
||||||
|
textBody: 'reply',
|
||||||
|
inReplyTo: '<msg1@example.com>',
|
||||||
|
references: ['<msg0@example.com>', '<msg1@example.com>'],
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('In-Reply-To: <msg1@example.com>');
|
||||||
|
expect(text).toContain('References: <msg0@example.com> <msg1@example.com>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes non-ASCII subject with RFC 2047', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'Ünïcödé',
|
||||||
|
textBody: 'test',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('=?UTF-8?Q?');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses CRLF line endings', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'CRLF',
|
||||||
|
textBody: 'test',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
// Should contain CRLF before the body
|
||||||
|
expect(text).toContain('\r\n');
|
||||||
|
// Should not contain bare LF without preceding CR (except within QP encoding)
|
||||||
|
const lines = text.split('\r\n');
|
||||||
|
expect(lines.length).toBeGreaterThan(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds empty body message', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { email: 'alice@example.com' },
|
||||||
|
to: [{ email: 'bob@example.com' }],
|
||||||
|
subject: 'Empty',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('Content-Type: text/plain; charset=utf-8');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('escapes display name in From header', () => {
|
||||||
|
const msg = buildMimeMessage({
|
||||||
|
from: { name: 'O\'Brien, "Bob"', email: 'bob@example.com' },
|
||||||
|
to: [{ email: 'alice@example.com' }],
|
||||||
|
subject: 'Name test',
|
||||||
|
textBody: 'test',
|
||||||
|
date: new Date('2024-06-15T12:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = new TextDecoder().decode(msg);
|
||||||
|
expect(text).toContain('From: "O\'Brien, \\"Bob\\"" <bob@example.com>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('quotedPrintableEncode', () => {
|
||||||
|
it('passes through ASCII text unchanged', () => {
|
||||||
|
const result = quotedPrintableEncode('Hello World');
|
||||||
|
expect(result).toBe('Hello World');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes non-ASCII characters', () => {
|
||||||
|
const result = quotedPrintableEncode('Héllo');
|
||||||
|
expect(result).toContain('=');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes equals sign', () => {
|
||||||
|
const result = quotedPrintableEncode('a=b');
|
||||||
|
expect(result).toContain('=3D');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('wraps long lines with soft line break', () => {
|
||||||
|
const longLine = 'a'.repeat(100);
|
||||||
|
const result = quotedPrintableEncode(longLine);
|
||||||
|
const lines = result.split('\r\n');
|
||||||
|
for (const line of lines) {
|
||||||
|
expect(line.length).toBeLessThanOrEqual(76);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('base64Encode', () => {
|
||||||
|
it('encodes binary data to base64', () => {
|
||||||
|
const data = new Uint8Array([72, 101, 108, 108, 111]).buffer; // "Hello"
|
||||||
|
const result = base64Encode(data);
|
||||||
|
expect(result).toBe('SGVsbG8=');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('wraps long lines at 76 chars', () => {
|
||||||
|
const data = new Uint8Array(200).buffer;
|
||||||
|
const result = base64Encode(data);
|
||||||
|
const lines = result.split('\r\n');
|
||||||
|
for (const line of lines) {
|
||||||
|
expect(line.length).toBeLessThanOrEqual(76);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
// @vitest-environment node
|
||||||
|
import { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import { importPkcs12, unlockPrivateKey, decryptPrivateKeyBytes } from '../pkcs12-import';
|
||||||
|
import { exportPkcs12 } from '../pkcs12-export';
|
||||||
|
|
||||||
|
const cryptoEngine = new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
});
|
||||||
|
|
||||||
|
function stringToAB(str: string): ArrayBuffer {
|
||||||
|
const buf = new ArrayBuffer(str.length);
|
||||||
|
const view = new Uint8Array(buf);
|
||||||
|
for (let i = 0; i < str.length; i++) {
|
||||||
|
view[i] = str.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a minimal real PKCS#12 (.p12) blob for testing.
|
||||||
|
*/
|
||||||
|
async function buildTestP12(
|
||||||
|
email: string,
|
||||||
|
cn: string,
|
||||||
|
p12Password: string,
|
||||||
|
): Promise<{ p12Bytes: ArrayBuffer; keyPair: globalThis.CryptoKeyPair; certDer: ArrayBuffer }> {
|
||||||
|
// Generate RSA key pair (signing)
|
||||||
|
const keyPair = await crypto.subtle.generateKey(
|
||||||
|
{
|
||||||
|
name: 'RSASSA-PKCS1-v1_5',
|
||||||
|
modulusLength: 2048,
|
||||||
|
publicExponent: new Uint8Array([1, 0, 1]),
|
||||||
|
hash: 'SHA-256',
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
['sign', 'verify'],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Self-signed certificate
|
||||||
|
const cert = new pkijs.Certificate();
|
||||||
|
cert.version = 2;
|
||||||
|
cert.serialNumber = new asn1js.Integer({ value: 42 });
|
||||||
|
|
||||||
|
cert.issuer.typesAndValues.push(
|
||||||
|
new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '2.5.4.3',
|
||||||
|
value: new asn1js.Utf8String({ value: cn }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cert.subject.typesAndValues.push(
|
||||||
|
new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '2.5.4.3',
|
||||||
|
value: new asn1js.Utf8String({ value: cn }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cert.subject.typesAndValues.push(
|
||||||
|
new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '1.2.840.113549.1.9.1',
|
||||||
|
value: new asn1js.IA5String({ value: email }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cert.notBefore.value = new Date('2024-01-01T00:00:00Z');
|
||||||
|
cert.notAfter.value = new Date('2030-12-31T23:59:59Z');
|
||||||
|
|
||||||
|
await cert.subjectPublicKeyInfo.importKey(keyPair.publicKey, cryptoEngine);
|
||||||
|
await cert.sign(keyPair.privateKey, 'SHA-256', cryptoEngine);
|
||||||
|
|
||||||
|
const certDer = cert.toSchema(true).toBER(false);
|
||||||
|
|
||||||
|
// Export private key as PKCS#8
|
||||||
|
const pkcs8Bytes = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
|
||||||
|
|
||||||
|
// Build PKCS#12 structure
|
||||||
|
const keyBag = new pkijs.PKCS8ShroudedKeyBag({
|
||||||
|
parsedValue: pkijs.PrivateKeyInfo.fromBER(pkcs8Bytes),
|
||||||
|
});
|
||||||
|
|
||||||
|
const passwordBuf = stringToAB(p12Password);
|
||||||
|
|
||||||
|
await keyBag.makeInternalValues({
|
||||||
|
password: passwordBuf,
|
||||||
|
contentEncryptionAlgorithm: {
|
||||||
|
name: 'AES-CBC',
|
||||||
|
length: 256,
|
||||||
|
} as Parameters<typeof keyBag.makeInternalValues>[0]['contentEncryptionAlgorithm'],
|
||||||
|
hmacHashAlgorithm: 'SHA-256',
|
||||||
|
iterationCount: 2048,
|
||||||
|
});
|
||||||
|
|
||||||
|
const keyBagSafe = new pkijs.SafeBag({
|
||||||
|
bagId: '1.2.840.113549.1.12.10.1.2',
|
||||||
|
bagValue: keyBag,
|
||||||
|
});
|
||||||
|
|
||||||
|
const certBagSafe = new pkijs.SafeBag({
|
||||||
|
bagId: '1.2.840.113549.1.12.10.1.3',
|
||||||
|
bagValue: new pkijs.CertBag({ parsedValue: cert }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const authenticatedSafe = new pkijs.AuthenticatedSafe({
|
||||||
|
parsedValue: {
|
||||||
|
safeContents: [
|
||||||
|
{ privacyMode: 0, value: new pkijs.SafeContents({ safeBags: [keyBagSafe] }) },
|
||||||
|
{ privacyMode: 0, value: new pkijs.SafeContents({ safeBags: [certBagSafe] }) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await authenticatedSafe.makeInternalValues({ safeContents: [{}, {}] });
|
||||||
|
|
||||||
|
const pfx = new pkijs.PFX({
|
||||||
|
parsedValue: {
|
||||||
|
integrityMode: 0,
|
||||||
|
authenticatedSafe,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await pfx.makeInternalValues({
|
||||||
|
password: passwordBuf,
|
||||||
|
iterations: 2048,
|
||||||
|
pbkdf2HashAlgorithm: 'SHA-256',
|
||||||
|
hmacHashAlgorithm: 'SHA-256',
|
||||||
|
});
|
||||||
|
|
||||||
|
const p12Bytes = pfx.toSchema().toBER(false);
|
||||||
|
return { p12Bytes, keyPair, certDer };
|
||||||
|
}
|
||||||
|
|
||||||
|
let testP12: Awaited<ReturnType<typeof buildTestP12>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
pkijs.setEngine('test', crypto, cryptoEngine);
|
||||||
|
testP12 = await buildTestP12('alice@example.com', 'Alice Test', 'p12pass');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('importPkcs12', () => {
|
||||||
|
it('imports a valid PKCS#12 file and produces a key record', async () => {
|
||||||
|
const result = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
|
||||||
|
expect(result.keyRecord).toBeDefined();
|
||||||
|
expect(result.keyRecord.email).toBe('alice@example.com');
|
||||||
|
expect(result.keyRecord.subject).toContain('Alice Test');
|
||||||
|
expect(result.keyRecord.certificate).toBeDefined();
|
||||||
|
expect(result.keyRecord.encryptedPrivateKey.byteLength).toBeGreaterThan(0);
|
||||||
|
expect(result.keyRecord.salt.byteLength).toBeGreaterThan(0);
|
||||||
|
expect(result.keyRecord.iv.byteLength).toBeGreaterThan(0);
|
||||||
|
expect(result.keyRecord.kdfIterations).toBe(600_000);
|
||||||
|
expect(result.keyRecord.fingerprint).toBeTruthy();
|
||||||
|
|
||||||
|
expect(result.certInfo).toBeDefined();
|
||||||
|
expect(result.certInfo.emailAddresses).toContain('alice@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on invalid ASN.1 data', async () => {
|
||||||
|
const garbage = new Uint8Array([0, 1, 2, 3]).buffer;
|
||||||
|
await expect(importPkcs12(garbage, 'pass', 'store')).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('unlockPrivateKey', () => {
|
||||||
|
it('unlocks and returns signing and decryption keys', async () => {
|
||||||
|
const result = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
const { signingKey, decryptionKey } = await unlockPrivateKey(result.keyRecord, 'storagepass');
|
||||||
|
|
||||||
|
expect(signingKey).toBeDefined();
|
||||||
|
expect(signingKey.type).toBe('private');
|
||||||
|
expect(signingKey.extractable).toBe(false);
|
||||||
|
|
||||||
|
expect(decryptionKey).toBeDefined();
|
||||||
|
expect(decryptionKey!.type).toBe('private');
|
||||||
|
expect(decryptionKey!.extractable).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on incorrect passphrase', async () => {
|
||||||
|
const result = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
await expect(unlockPrivateKey(result.keyRecord, 'wrongpass')).rejects.toThrow('Incorrect passphrase');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('decryptPrivateKeyBytes', () => {
|
||||||
|
it('returns raw PKCS#8 bytes', async () => {
|
||||||
|
const result = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
const pkcs8 = await decryptPrivateKeyBytes(result.keyRecord, 'storagepass');
|
||||||
|
|
||||||
|
expect(pkcs8).toBeInstanceOf(ArrayBuffer);
|
||||||
|
expect(pkcs8.byteLength).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on incorrect passphrase', async () => {
|
||||||
|
const result = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
await expect(decryptPrivateKeyBytes(result.keyRecord, 'bad')).rejects.toThrow('Incorrect passphrase');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('exportPkcs12', () => {
|
||||||
|
it('produces a valid PKCS#12 that can be re-imported', async () => {
|
||||||
|
const imported = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
|
||||||
|
// Export
|
||||||
|
const p12Out = await exportPkcs12(imported.keyRecord, 'storagepass', 'exportpass');
|
||||||
|
expect(p12Out).toBeInstanceOf(ArrayBuffer);
|
||||||
|
expect(p12Out.byteLength).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// Re-import
|
||||||
|
const reimported = await importPkcs12(p12Out, 'exportpass', 'newstoragepass');
|
||||||
|
expect(reimported.keyRecord.email).toBe('alice@example.com');
|
||||||
|
expect(reimported.keyRecord.subject).toContain('Alice Test');
|
||||||
|
expect(reimported.keyRecord.fingerprint).toBe(imported.keyRecord.fingerprint);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on incorrect storage passphrase', async () => {
|
||||||
|
const imported = await importPkcs12(testP12.p12Bytes, 'p12pass', 'storagepass');
|
||||||
|
await expect(exportPkcs12(imported.keyRecord, 'wrong', 'exportpass')).rejects.toThrow('Incorrect passphrase');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
// @vitest-environment node
|
||||||
|
import { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import { smimeSign } from '../smime-sign';
|
||||||
|
import { smimeEncrypt } from '../smime-encrypt';
|
||||||
|
import { smimeDecrypt, SmimeKeyLockedError, findDecryptionCandidates, normalizeCmsBytes } from '../smime-decrypt';
|
||||||
|
import { smimeVerify } from '../smime-verify';
|
||||||
|
import { extractCertificateInfo } from '../certificate-utils';
|
||||||
|
import type { SmimeKeyRecord } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Integration tests for S/MIME sign→verify and encrypt→decrypt roundtrips.
|
||||||
|
* Uses Node.js crypto (not jsdom) for accurate Web Crypto behavior.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const testMimeBytes = new TextEncoder().encode(
|
||||||
|
'Content-Type: text/plain; charset=utf-8\r\n\r\nHello, World!',
|
||||||
|
);
|
||||||
|
|
||||||
|
const cryptoEngine = new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
});
|
||||||
|
|
||||||
|
async function buildCert(
|
||||||
|
cn: string,
|
||||||
|
email: string,
|
||||||
|
publicKey: CryptoKey,
|
||||||
|
signingPrivateKey: CryptoKey,
|
||||||
|
): Promise<{ cert: pkijs.Certificate; certDer: ArrayBuffer }> {
|
||||||
|
const cert = new pkijs.Certificate();
|
||||||
|
cert.version = 2;
|
||||||
|
cert.serialNumber = new asn1js.Integer({ value: Math.floor(Math.random() * 100000) });
|
||||||
|
|
||||||
|
cert.issuer.typesAndValues.push(
|
||||||
|
new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '2.5.4.3',
|
||||||
|
value: new asn1js.Utf8String({ value: cn }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cert.subject.typesAndValues.push(
|
||||||
|
new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '2.5.4.3',
|
||||||
|
value: new asn1js.Utf8String({ value: cn }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cert.subject.typesAndValues.push(
|
||||||
|
new pkijs.AttributeTypeAndValue({
|
||||||
|
type: '1.2.840.113549.1.9.1',
|
||||||
|
value: new asn1js.IA5String({ value: email }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cert.notBefore.value = new Date('2024-01-01T00:00:00Z');
|
||||||
|
cert.notAfter.value = new Date('2030-12-31T23:59:59Z');
|
||||||
|
|
||||||
|
await cert.subjectPublicKeyInfo.importKey(publicKey, cryptoEngine);
|
||||||
|
|
||||||
|
await cert.sign(signingPrivateKey, 'SHA-256', cryptoEngine);
|
||||||
|
|
||||||
|
const certDer = cert.toSchema(true).toBER(false);
|
||||||
|
return { cert, certDer };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function makeKeyRecord(
|
||||||
|
id: string,
|
||||||
|
email: string,
|
||||||
|
certDer: ArrayBuffer,
|
||||||
|
): Promise<SmimeKeyRecord> {
|
||||||
|
const cert = new pkijs.Certificate({
|
||||||
|
schema: asn1js.fromBER(certDer).result,
|
||||||
|
});
|
||||||
|
const info = await extractCertificateInfo(cert, certDer);
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
email: email.toLowerCase(),
|
||||||
|
certificate: certDer,
|
||||||
|
certificateChain: [],
|
||||||
|
encryptedPrivateKey: new ArrayBuffer(0),
|
||||||
|
salt: new ArrayBuffer(0),
|
||||||
|
iv: new ArrayBuffer(0),
|
||||||
|
kdfIterations: 600000,
|
||||||
|
issuer: info.issuer,
|
||||||
|
subject: info.subject,
|
||||||
|
serialNumber: info.serialNumber,
|
||||||
|
notBefore: info.notBefore,
|
||||||
|
notAfter: info.notAfter,
|
||||||
|
fingerprint: info.fingerprint,
|
||||||
|
algorithm: info.algorithm,
|
||||||
|
capabilities: info.capabilities,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Signing key pair and cert (RSASSA-PKCS1-v1_5 public key embedded in cert)
|
||||||
|
let signKeyPair: globalThis.CryptoKeyPair;
|
||||||
|
let signCertDer: ArrayBuffer;
|
||||||
|
|
||||||
|
// Encryption key pair and cert (RSA-OAEP public key embedded in cert)
|
||||||
|
let encKeyPair: globalThis.CryptoKeyPair;
|
||||||
|
let encCertDer: ArrayBuffer;
|
||||||
|
let encKeyRecord: SmimeKeyRecord;
|
||||||
|
|
||||||
|
// Second encryption identity for cross-recipient tests
|
||||||
|
let bobEncKeyPair: globalThis.CryptoKeyPair;
|
||||||
|
let bobEncCertDer: ArrayBuffer;
|
||||||
|
let bobKeyRecord: SmimeKeyRecord;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
pkijs.setEngine('test', crypto, cryptoEngine);
|
||||||
|
|
||||||
|
// --- Signing identity ---
|
||||||
|
signKeyPair = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['sign', 'verify'],
|
||||||
|
);
|
||||||
|
const signResult = await buildCert('Alice Signer', 'alice@example.com', signKeyPair.publicKey, signKeyPair.privateKey);
|
||||||
|
signCertDer = signResult.certDer;
|
||||||
|
|
||||||
|
// --- Encryption identity (Alice) ---
|
||||||
|
encKeyPair = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'],
|
||||||
|
);
|
||||||
|
// Self-sign with a temporary signing key
|
||||||
|
const tempSignKey = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['sign', 'verify'],
|
||||||
|
);
|
||||||
|
const encResult = await buildCert('Alice', 'alice@example.com', encKeyPair.publicKey, tempSignKey.privateKey);
|
||||||
|
encCertDer = encResult.certDer;
|
||||||
|
encKeyRecord = await makeKeyRecord('key-alice-enc', 'alice@example.com', encCertDer);
|
||||||
|
|
||||||
|
// --- Bob encryption identity ---
|
||||||
|
bobEncKeyPair = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'],
|
||||||
|
);
|
||||||
|
const bobTempSignKey = await crypto.subtle.generateKey(
|
||||||
|
{ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
|
||||||
|
true,
|
||||||
|
['sign', 'verify'],
|
||||||
|
);
|
||||||
|
const bobResult = await buildCert('Bob', 'bob@example.com', bobEncKeyPair.publicKey, bobTempSignKey.privateKey);
|
||||||
|
bobEncCertDer = bobResult.certDer;
|
||||||
|
bobKeyRecord = await makeKeyRecord('key-bob-enc', 'bob@example.com', bobEncCertDer);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('smimeSign + smimeVerify roundtrip', () => {
|
||||||
|
it('signs and verifies a message successfully', async () => {
|
||||||
|
const signedBlob = await smimeSign(testMimeBytes, signKeyPair.privateKey, signCertDer);
|
||||||
|
expect(signedBlob).toBeInstanceOf(Blob);
|
||||||
|
expect(signedBlob.type).toContain('application/pkcs7-mime');
|
||||||
|
|
||||||
|
const cmsBytes = await signedBlob.arrayBuffer();
|
||||||
|
const result = await smimeVerify(cmsBytes, 'alice@example.com');
|
||||||
|
|
||||||
|
expect(result.status.isSigned).toBe(true);
|
||||||
|
expect(result.status.signatureValid).toBe(true);
|
||||||
|
expect(result.status.signerEmailMatch).toBe(true);
|
||||||
|
expect(result.status.signerCert).toBeDefined();
|
||||||
|
expect(result.status.signerCert!.email).toBe('alice@example.com');
|
||||||
|
|
||||||
|
const innerText = new TextDecoder().decode(result.mimeBytes);
|
||||||
|
expect(innerText).toContain('Hello, World!');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports email mismatch when From differs from signer', async () => {
|
||||||
|
const signedBlob = await smimeSign(testMimeBytes, signKeyPair.privateKey, signCertDer);
|
||||||
|
const cmsBytes = await signedBlob.arrayBuffer();
|
||||||
|
const result = await smimeVerify(cmsBytes, 'evil@attacker.com');
|
||||||
|
|
||||||
|
expect(result.status.isSigned).toBe(true);
|
||||||
|
expect(result.status.signerEmailMatch).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('smimeEncrypt + smimeDecrypt roundtrip', () => {
|
||||||
|
it('encrypts and decrypts a message', async () => {
|
||||||
|
const encryptedBlob = await smimeEncrypt(
|
||||||
|
testMimeBytes,
|
||||||
|
[encCertDer],
|
||||||
|
encCertDer,
|
||||||
|
);
|
||||||
|
expect(encryptedBlob).toBeInstanceOf(Blob);
|
||||||
|
expect(encryptedBlob.type).toContain('application/pkcs7-mime');
|
||||||
|
|
||||||
|
const cmsBytes = await encryptedBlob.arrayBuffer();
|
||||||
|
const unlockedKeys = new Map<string, CryptoKey>();
|
||||||
|
unlockedKeys.set(encKeyRecord.id, encKeyPair.privateKey);
|
||||||
|
|
||||||
|
const result = await smimeDecrypt({
|
||||||
|
cmsBytes,
|
||||||
|
keyRecords: [encKeyRecord],
|
||||||
|
unlockedKeys,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.mimeBytes).toBeDefined();
|
||||||
|
const decryptedText = new TextDecoder().decode(result.mimeBytes);
|
||||||
|
expect(decryptedText).toContain('Hello, World!');
|
||||||
|
expect(result.keyRecordId).toBe(encKeyRecord.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws when no matching key is available', async () => {
|
||||||
|
const encryptedBlob = await smimeEncrypt(
|
||||||
|
testMimeBytes,
|
||||||
|
[encCertDer],
|
||||||
|
encCertDer,
|
||||||
|
);
|
||||||
|
const cmsBytes = await encryptedBlob.arrayBuffer();
|
||||||
|
|
||||||
|
// Bob's key record doesn't match Alice's encrypted message
|
||||||
|
await expect(
|
||||||
|
smimeDecrypt({
|
||||||
|
cmsBytes,
|
||||||
|
keyRecords: [bobKeyRecord],
|
||||||
|
unlockedKeys: new Map(),
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('No imported S/MIME key matches');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('SmimeKeyLockedError', () => {
|
||||||
|
it('has correct name and keyRecordId', () => {
|
||||||
|
const err = new SmimeKeyLockedError('test', 'key-1');
|
||||||
|
expect(err.name).toBe('SmimeKeyLockedError');
|
||||||
|
expect(err.keyRecordId).toBe('key-1');
|
||||||
|
expect(err.message).toBe('test');
|
||||||
|
expect(err).toBeInstanceOf(Error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findDecryptionCandidates', () => {
|
||||||
|
it('returns empty array for invalid CMS data', () => {
|
||||||
|
const garbage = new Uint8Array([0, 1, 2, 3]).buffer;
|
||||||
|
const result = findDecryptionCandidates(garbage, [encKeyRecord]);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('smimeVerify edge cases', () => {
|
||||||
|
it('throws on invalid ASN.1 data', async () => {
|
||||||
|
const garbage = new Uint8Array([0, 1, 2, 3]).buffer;
|
||||||
|
await expect(smimeVerify(garbage)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('normalizeCmsBytes', () => {
|
||||||
|
// Helper: a minimal DER-encoded ASN.1 SEQUENCE (0x30 tag)
|
||||||
|
const derBytes = new Uint8Array([0x30, 0x03, 0x02, 0x01, 0x05]);
|
||||||
|
|
||||||
|
it('passes through raw DER unchanged', () => {
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(derBytes.buffer as ArrayBuffer));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes through empty buffer unchanged', () => {
|
||||||
|
const result = normalizeCmsBytes(new ArrayBuffer(0));
|
||||||
|
expect(result.byteLength).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes plain base64 content', () => {
|
||||||
|
const b64 = btoa(String.fromCharCode(...derBytes));
|
||||||
|
const input = new TextEncoder().encode(b64).buffer as ArrayBuffer;
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(input));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes base64 content with MIME headers', () => {
|
||||||
|
const b64 = btoa(String.fromCharCode(...derBytes));
|
||||||
|
const mime =
|
||||||
|
'Content-Type: application/pkcs7-mime\r\n' +
|
||||||
|
'Content-Transfer-Encoding: base64\r\n' +
|
||||||
|
'\r\n' +
|
||||||
|
b64 + '\r\n';
|
||||||
|
const input = new TextEncoder().encode(mime).buffer as ArrayBuffer;
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(input));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes PEM-wrapped content', () => {
|
||||||
|
const b64 = btoa(String.fromCharCode(...derBytes));
|
||||||
|
const pem = '-----BEGIN PKCS7-----\n' + b64 + '\n-----END PKCS7-----\n';
|
||||||
|
const input = new TextEncoder().encode(pem).buffer as ArrayBuffer;
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(input));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes MIME headers with unix line endings', () => {
|
||||||
|
const b64 = btoa(String.fromCharCode(...derBytes));
|
||||||
|
const mime =
|
||||||
|
'Content-Type: application/pkcs7-mime\n' +
|
||||||
|
'Content-Transfer-Encoding: base64\n' +
|
||||||
|
'\n' +
|
||||||
|
b64 + '\n';
|
||||||
|
const input = new TextEncoder().encode(mime).buffer as ArrayBuffer;
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(input));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes base64 when MIME headers are very long', () => {
|
||||||
|
const b64 = btoa(String.fromCharCode(...derBytes));
|
||||||
|
const longHeader = 'X-Long-Header: ' + 'A'.repeat(3000) + '\r\n';
|
||||||
|
const mime =
|
||||||
|
longHeader +
|
||||||
|
'Content-Type: application/pkcs7-mime\r\n' +
|
||||||
|
'Content-Transfer-Encoding: base64\r\n' +
|
||||||
|
'\r\n' +
|
||||||
|
b64 + '\r\n';
|
||||||
|
const input = new TextEncoder().encode(mime).buffer as ArrayBuffer;
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(input));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts largest base64 block from multipart-like text', () => {
|
||||||
|
const b64 = btoa(String.fromCharCode(...derBytes));
|
||||||
|
const multipartLike =
|
||||||
|
'Content-Type: multipart/mixed; boundary="b"\r\n\r\n' +
|
||||||
|
'--b\r\n' +
|
||||||
|
'Content-Type: text/plain\r\n\r\n' +
|
||||||
|
'hello\r\n' +
|
||||||
|
'--b\r\n' +
|
||||||
|
'Content-Type: application/pkcs7-mime\r\n' +
|
||||||
|
'Content-Transfer-Encoding: base64\r\n\r\n' +
|
||||||
|
b64 + '\r\n' +
|
||||||
|
'--b--\r\n';
|
||||||
|
const input = new TextEncoder().encode(multipartLike).buffer as ArrayBuffer;
|
||||||
|
const result = new Uint8Array(normalizeCmsBytes(input));
|
||||||
|
expect(result).toEqual(derBytes);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns original when content is not decodable', () => {
|
||||||
|
const garbage = new Uint8Array([0x01, 0x02, 0xFF, 0xFE]);
|
||||||
|
const result = normalizeCmsBytes(garbage.buffer as ArrayBuffer);
|
||||||
|
// Should return original since it can\'t be decoded
|
||||||
|
expect(result.byteLength).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { detectSmime } from '../smime-detect';
|
||||||
|
|
||||||
|
describe('detectSmime', () => {
|
||||||
|
describe('no S/MIME content', () => {
|
||||||
|
it('returns null type when no arguments provided', () => {
|
||||||
|
const result = detectSmime();
|
||||||
|
expect(result.type).toBeNull();
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null type for plain text content', () => {
|
||||||
|
const result = detectSmime('text/plain');
|
||||||
|
expect(result.type).toBeNull();
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null type for multipart/mixed without S/MIME', () => {
|
||||||
|
const result = detectSmime('multipart/mixed; boundary="abc"');
|
||||||
|
expect(result.type).toBeNull();
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Content-Type header detection', () => {
|
||||||
|
it('detects enveloped-data from Content-Type', () => {
|
||||||
|
const ct = 'application/pkcs7-mime; smime-type=enveloped-data; name="smime.p7m"';
|
||||||
|
const body = { partId: '1', blobId: 'blob1', type: ct };
|
||||||
|
const result = detectSmime(ct, body);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
expect(result.blobId).toBe('blob1');
|
||||||
|
expect(result.partId).toBe('1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects signed-data from Content-Type', () => {
|
||||||
|
const ct = 'application/pkcs7-mime; smime-type=signed-data; name="smime.p7m"';
|
||||||
|
const body = { partId: '2', blobId: 'blob2', type: ct };
|
||||||
|
const result = detectSmime(ct, body);
|
||||||
|
expect(result.type).toBe('signed-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
expect(result.blobId).toBe('blob2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects x-pkcs7-mime variant', () => {
|
||||||
|
const ct = 'application/x-pkcs7-mime; smime-type=enveloped-data';
|
||||||
|
const body = { partId: '1', blobId: 'blob1', type: ct };
|
||||||
|
const result = detectSmime(ct, body);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects detached signature via multipart/signed', () => {
|
||||||
|
const ct = 'multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256';
|
||||||
|
const result = detectSmime(ct);
|
||||||
|
expect(result.type).toBe('detached-sig');
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles generic pkcs7-mime without smime-type', () => {
|
||||||
|
const ct = 'application/pkcs7-mime; name="smime.p7m"';
|
||||||
|
const body = { partId: '1', blobId: 'blob1', type: ct };
|
||||||
|
const result = detectSmime(ct, body);
|
||||||
|
// Should default to enveloped-data for generic pkcs7-mime
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.blobId).toBe('blob1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is case-insensitive for Content-Type', () => {
|
||||||
|
const ct = 'Application/PKCS7-MIME; smime-type=Enveloped-Data';
|
||||||
|
const body = { partId: '1', blobId: 'b1', type: ct };
|
||||||
|
const result = detectSmime(ct, body);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bodyStructure detection', () => {
|
||||||
|
it('finds pkcs7-mime part in bodyStructure tree', () => {
|
||||||
|
const body = {
|
||||||
|
type: 'multipart/mixed',
|
||||||
|
subParts: [
|
||||||
|
{ partId: '1', type: 'text/plain', blobId: 'text-blob' },
|
||||||
|
{
|
||||||
|
partId: '2',
|
||||||
|
type: 'application/pkcs7-mime; smime-type=enveloped-data',
|
||||||
|
blobId: 'cms-blob',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const result = detectSmime(undefined, body);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
expect(result.blobId).toBe('cms-blob');
|
||||||
|
expect(result.partId).toBe('2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects detached sig in multipart/signed bodyStructure', () => {
|
||||||
|
const body = {
|
||||||
|
type: 'multipart/signed',
|
||||||
|
subParts: [
|
||||||
|
{ partId: '1', type: 'text/plain', blobId: 'text-blob' },
|
||||||
|
{ partId: '2', type: 'application/pkcs7-signature', blobId: 'sig-blob' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const result = detectSmime(undefined, body);
|
||||||
|
expect(result.type).toBe('detached-sig');
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('walks nested bodyStructure', () => {
|
||||||
|
const body = {
|
||||||
|
type: 'multipart/mixed',
|
||||||
|
subParts: [
|
||||||
|
{
|
||||||
|
type: 'multipart/alternative',
|
||||||
|
subParts: [
|
||||||
|
{ partId: '1.1', type: 'text/plain', blobId: 'txt' },
|
||||||
|
{ partId: '1.2', type: 'text/html', blobId: 'html' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
partId: '2',
|
||||||
|
type: 'application/pkcs7-mime; smime-type=signed-data',
|
||||||
|
blobId: 'sig-blob',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const result = detectSmime(undefined, body);
|
||||||
|
expect(result.type).toBe('signed-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
expect(result.blobId).toBe('sig-blob');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('attachment detection', () => {
|
||||||
|
it('detects .p7m attachment', () => {
|
||||||
|
const attachments = [
|
||||||
|
{ partId: '3', blobId: 'att-blob', name: 'message.p7m', type: 'application/octet-stream' },
|
||||||
|
];
|
||||||
|
const result = detectSmime(undefined, null, attachments);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
expect(result.blobId).toBe('att-blob');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects .p7s attachment as detached-sig', () => {
|
||||||
|
const attachments = [
|
||||||
|
{ partId: '3', blobId: 'sig-blob', name: 'smime.p7s', type: 'application/octet-stream' },
|
||||||
|
];
|
||||||
|
const result = detectSmime(undefined, null, attachments);
|
||||||
|
expect(result.type).toBe('detached-sig');
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects pkcs7-mime attachment type', () => {
|
||||||
|
const attachments = [
|
||||||
|
{
|
||||||
|
partId: '2',
|
||||||
|
blobId: 'enc-blob',
|
||||||
|
name: 'encrypted.bin',
|
||||||
|
type: 'application/pkcs7-mime; smime-type=enveloped-data',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const result = detectSmime(undefined, null, attachments);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.supported).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips non-S/MIME attachments', () => {
|
||||||
|
const attachments = [
|
||||||
|
{ partId: '2', blobId: 'pdf-blob', name: 'document.pdf', type: 'application/pdf' },
|
||||||
|
];
|
||||||
|
const result = detectSmime(undefined, null, attachments);
|
||||||
|
expect(result.type).toBeNull();
|
||||||
|
expect(result.supported).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('priority order', () => {
|
||||||
|
it('Content-Type takes precedence over bodyStructure', () => {
|
||||||
|
const ct = 'application/pkcs7-mime; smime-type=enveloped-data';
|
||||||
|
const body = {
|
||||||
|
partId: '1',
|
||||||
|
blobId: 'from-ct',
|
||||||
|
type: ct,
|
||||||
|
};
|
||||||
|
const result = detectSmime(ct, body);
|
||||||
|
expect(result.type).toBe('enveloped-data');
|
||||||
|
expect(result.blobId).toBe('from-ct');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
|
||||||
|
// Mock IndexedDB storage functions before importing store
|
||||||
|
vi.mock('@/lib/smime/key-storage', () => ({
|
||||||
|
saveKeyRecord: vi.fn().mockResolvedValue(undefined),
|
||||||
|
listKeyRecords: vi.fn().mockResolvedValue([]),
|
||||||
|
deleteKeyRecord: vi.fn().mockResolvedValue(undefined),
|
||||||
|
savePublicCert: vi.fn().mockResolvedValue(undefined),
|
||||||
|
listPublicCerts: vi.fn().mockResolvedValue([]),
|
||||||
|
deletePublicCert: vi.fn().mockResolvedValue(undefined),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/lib/smime/pkcs12-import', () => ({
|
||||||
|
importPkcs12: vi.fn(),
|
||||||
|
unlockPrivateKey: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/lib/smime/certificate-utils', () => ({
|
||||||
|
parseCertificatePemOrDer: vi.fn(),
|
||||||
|
extractCertificateInfo: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { useSmimeStore } from '@/stores/smime-store';
|
||||||
|
import { listKeyRecords, listPublicCerts, saveKeyRecord, deleteKeyRecord, savePublicCert, deletePublicCert } from '@/lib/smime/key-storage';
|
||||||
|
import { importPkcs12, unlockPrivateKey } from '@/lib/smime/pkcs12-import';
|
||||||
|
import type { SmimeKeyRecord, SmimePublicCert } from '@/lib/smime/types';
|
||||||
|
|
||||||
|
const mockKeyRecord: SmimeKeyRecord = {
|
||||||
|
id: 'key-1',
|
||||||
|
email: 'user@example.com',
|
||||||
|
certificate: new ArrayBuffer(10),
|
||||||
|
certificateChain: [],
|
||||||
|
encryptedPrivateKey: new ArrayBuffer(32),
|
||||||
|
salt: new ArrayBuffer(16),
|
||||||
|
iv: new ArrayBuffer(12),
|
||||||
|
kdfIterations: 600000,
|
||||||
|
issuer: 'CN=Test CA',
|
||||||
|
subject: 'CN=Test User',
|
||||||
|
serialNumber: '01',
|
||||||
|
notBefore: '2024-01-01T00:00:00Z',
|
||||||
|
notAfter: '2030-12-31T23:59:59Z',
|
||||||
|
fingerprint: 'aa:bb:cc',
|
||||||
|
algorithm: 'RSA-2048',
|
||||||
|
capabilities: { canSign: true, canEncrypt: true },
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
sessionStorage.clear();
|
||||||
|
// Reset store state
|
||||||
|
useSmimeStore.setState({
|
||||||
|
keyRecords: [],
|
||||||
|
publicCerts: [],
|
||||||
|
unlockedKeys: new Map(),
|
||||||
|
unlockedDecryptionKeys: new Map(),
|
||||||
|
identityKeyBindings: {},
|
||||||
|
defaultSignIdentity: {},
|
||||||
|
defaultEncrypt: false,
|
||||||
|
rememberUnlockedKeys: false,
|
||||||
|
autoImportSignerCerts: false,
|
||||||
|
isLoading: false,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('smime-store', () => {
|
||||||
|
describe('load', () => {
|
||||||
|
it('loads key records and public certs from IndexedDB', async () => {
|
||||||
|
const records = [mockKeyRecord];
|
||||||
|
const certs: SmimePublicCert[] = [];
|
||||||
|
vi.mocked(listKeyRecords).mockResolvedValue(records);
|
||||||
|
vi.mocked(listPublicCerts).mockResolvedValue(certs);
|
||||||
|
|
||||||
|
await useSmimeStore.getState().load();
|
||||||
|
|
||||||
|
const state = useSmimeStore.getState();
|
||||||
|
expect(state.keyRecords).toEqual(records);
|
||||||
|
expect(state.publicCerts).toEqual(certs);
|
||||||
|
expect(state.isLoading).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('re-unlocks remembered keys during load', async () => {
|
||||||
|
const records = [mockKeyRecord];
|
||||||
|
const mockSigningKey = {} as CryptoKey;
|
||||||
|
const mockDecryptionKey = {} as CryptoKey;
|
||||||
|
sessionStorage.setItem('smime-unlocked-session', JSON.stringify({ 'key-1': 'passphrase' }));
|
||||||
|
useSmimeStore.setState({ rememberUnlockedKeys: true });
|
||||||
|
vi.mocked(listKeyRecords).mockResolvedValue(records);
|
||||||
|
vi.mocked(listPublicCerts).mockResolvedValue([]);
|
||||||
|
vi.mocked(unlockPrivateKey).mockResolvedValue({
|
||||||
|
signingKey: mockSigningKey,
|
||||||
|
decryptionKey: mockDecryptionKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
await useSmimeStore.getState().load();
|
||||||
|
|
||||||
|
expect(unlockPrivateKey).toHaveBeenCalledWith(mockKeyRecord, 'passphrase');
|
||||||
|
expect(useSmimeStore.getState().getUnlockedKey('key-1')).toBe(mockSigningKey);
|
||||||
|
expect(useSmimeStore.getState().unlockedDecryptionKeys.get('key-1')).toBe(mockDecryptionKey);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes stale remembered keys when re-unlock fails', async () => {
|
||||||
|
const records = [mockKeyRecord];
|
||||||
|
sessionStorage.setItem('smime-unlocked-session', JSON.stringify({ 'key-1': 'bad-pass' }));
|
||||||
|
useSmimeStore.setState({ rememberUnlockedKeys: true });
|
||||||
|
vi.mocked(listKeyRecords).mockResolvedValue(records);
|
||||||
|
vi.mocked(listPublicCerts).mockResolvedValue([]);
|
||||||
|
vi.mocked(unlockPrivateKey).mockRejectedValue(new Error('Incorrect passphrase'));
|
||||||
|
|
||||||
|
await useSmimeStore.getState().load();
|
||||||
|
|
||||||
|
expect(sessionStorage.getItem('smime-unlocked-session')).toBeNull();
|
||||||
|
expect(useSmimeStore.getState().isKeyUnlocked('key-1')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets error on failure', async () => {
|
||||||
|
vi.mocked(listKeyRecords).mockRejectedValue(new Error('DB failed'));
|
||||||
|
|
||||||
|
await useSmimeStore.getState().load();
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().error).toBe('DB failed');
|
||||||
|
expect(useSmimeStore.getState().isLoading).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('importPKCS12', () => {
|
||||||
|
it('imports and adds key record', async () => {
|
||||||
|
vi.mocked(importPkcs12).mockResolvedValue({
|
||||||
|
keyRecord: mockKeyRecord,
|
||||||
|
certInfo: {} as any,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await useSmimeStore.getState().importPKCS12(
|
||||||
|
new ArrayBuffer(10),
|
||||||
|
'p12pass',
|
||||||
|
'storagepass',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.id).toBe('key-1');
|
||||||
|
expect(saveKeyRecord).toHaveBeenCalledWith(mockKeyRecord);
|
||||||
|
expect(useSmimeStore.getState().keyRecords).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets error on import failure', async () => {
|
||||||
|
vi.mocked(importPkcs12).mockRejectedValue(new Error('Bad password'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
useSmimeStore.getState().importPKCS12(new ArrayBuffer(10), 'wrong', 'pass'),
|
||||||
|
).rejects.toThrow('Bad password');
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().error).toBe('Bad password');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('removeKeyRecord', () => {
|
||||||
|
it('removes key record and clears bindings', async () => {
|
||||||
|
useSmimeStore.setState({
|
||||||
|
keyRecords: [mockKeyRecord],
|
||||||
|
identityKeyBindings: { 'identity-1': 'key-1' },
|
||||||
|
unlockedKeys: new Map([['key-1', {} as CryptoKey]]),
|
||||||
|
unlockedDecryptionKeys: new Map([['key-1', {} as CryptoKey]]),
|
||||||
|
});
|
||||||
|
|
||||||
|
await useSmimeStore.getState().removeKeyRecord('key-1');
|
||||||
|
|
||||||
|
expect(deleteKeyRecord).toHaveBeenCalledWith('key-1');
|
||||||
|
expect(useSmimeStore.getState().keyRecords).toHaveLength(0);
|
||||||
|
expect(useSmimeStore.getState().identityKeyBindings).toEqual({});
|
||||||
|
expect(useSmimeStore.getState().unlockedKeys.has('key-1')).toBe(false);
|
||||||
|
expect(useSmimeStore.getState().unlockedDecryptionKeys.has('key-1')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('removePublicCert', () => {
|
||||||
|
it('removes public cert', async () => {
|
||||||
|
const cert: SmimePublicCert = {
|
||||||
|
id: 'cert-1',
|
||||||
|
email: 'recipient@example.com',
|
||||||
|
certificate: new ArrayBuffer(10),
|
||||||
|
issuer: 'CN=CA',
|
||||||
|
subject: 'CN=Recipient',
|
||||||
|
notBefore: '2024-01-01T00:00:00Z',
|
||||||
|
notAfter: '2030-12-31T23:59:59Z',
|
||||||
|
fingerprint: 'aa:bb',
|
||||||
|
source: 'manual',
|
||||||
|
};
|
||||||
|
useSmimeStore.setState({ publicCerts: [cert] });
|
||||||
|
|
||||||
|
await useSmimeStore.getState().removePublicCert('cert-1');
|
||||||
|
|
||||||
|
expect(deletePublicCert).toHaveBeenCalledWith('cert-1');
|
||||||
|
expect(useSmimeStore.getState().publicCerts).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('unlockKey + lockKey', () => {
|
||||||
|
it('unlocks a key', async () => {
|
||||||
|
const mockSigningKey = {} as CryptoKey;
|
||||||
|
const mockDecryptionKey = {} as CryptoKey;
|
||||||
|
vi.mocked(unlockPrivateKey).mockResolvedValue({ signingKey: mockSigningKey, decryptionKey: mockDecryptionKey });
|
||||||
|
useSmimeStore.setState({ keyRecords: [mockKeyRecord] });
|
||||||
|
|
||||||
|
await useSmimeStore.getState().unlockKey('key-1', 'passphrase');
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().isKeyUnlocked('key-1')).toBe(true);
|
||||||
|
expect(useSmimeStore.getState().getUnlockedKey('key-1')).toBe(mockSigningKey);
|
||||||
|
expect(useSmimeStore.getState().unlockedDecryptionKeys.get('key-1')).toBe(mockDecryptionKey);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores the passphrase for session rehydration when remember is enabled', async () => {
|
||||||
|
const mockSigningKey = {} as CryptoKey;
|
||||||
|
vi.mocked(unlockPrivateKey).mockResolvedValue({ signingKey: mockSigningKey });
|
||||||
|
useSmimeStore.setState({ keyRecords: [mockKeyRecord], rememberUnlockedKeys: true });
|
||||||
|
|
||||||
|
await useSmimeStore.getState().unlockKey('key-1', 'passphrase');
|
||||||
|
|
||||||
|
expect(sessionStorage.getItem('smime-unlocked-session')).toBe(
|
||||||
|
JSON.stringify({ 'key-1': 'passphrase' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores only the signing key when no decryption key is available', async () => {
|
||||||
|
const mockSigningKey = {} as CryptoKey;
|
||||||
|
vi.mocked(unlockPrivateKey).mockResolvedValue({ signingKey: mockSigningKey });
|
||||||
|
useSmimeStore.setState({ keyRecords: [mockKeyRecord] });
|
||||||
|
|
||||||
|
await useSmimeStore.getState().unlockKey('key-1', 'passphrase');
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().getUnlockedKey('key-1')).toBe(mockSigningKey);
|
||||||
|
expect(useSmimeStore.getState().unlockedDecryptionKeys.has('key-1')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws for non-existent key record', async () => {
|
||||||
|
await expect(
|
||||||
|
useSmimeStore.getState().unlockKey('non-existent', 'pass'),
|
||||||
|
).rejects.toThrow('Key record not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locks a key', () => {
|
||||||
|
sessionStorage.setItem('smime-unlocked-session', JSON.stringify({ 'key-1': 'passphrase' }));
|
||||||
|
useSmimeStore.setState({
|
||||||
|
unlockedKeys: new Map([['key-1', {} as CryptoKey]]),
|
||||||
|
unlockedDecryptionKeys: new Map([['key-1', {} as CryptoKey]]),
|
||||||
|
});
|
||||||
|
|
||||||
|
useSmimeStore.getState().lockKey('key-1');
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().isKeyUnlocked('key-1')).toBe(false);
|
||||||
|
expect(useSmimeStore.getState().unlockedDecryptionKeys.has('key-1')).toBe(false);
|
||||||
|
expect(sessionStorage.getItem('smime-unlocked-session')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locks all keys', () => {
|
||||||
|
sessionStorage.setItem(
|
||||||
|
'smime-unlocked-session',
|
||||||
|
JSON.stringify({ 'key-1': 'one', 'key-2': 'two' }),
|
||||||
|
);
|
||||||
|
useSmimeStore.setState({
|
||||||
|
unlockedKeys: new Map([
|
||||||
|
['key-1', {} as CryptoKey],
|
||||||
|
['key-2', {} as CryptoKey],
|
||||||
|
]),
|
||||||
|
unlockedDecryptionKeys: new Map([
|
||||||
|
['key-1', {} as CryptoKey],
|
||||||
|
['key-2', {} as CryptoKey],
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
|
||||||
|
useSmimeStore.getState().lockAllKeys();
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().unlockedKeys.size).toBe(0);
|
||||||
|
expect(useSmimeStore.getState().unlockedDecryptionKeys.size).toBe(0);
|
||||||
|
expect(sessionStorage.getItem('smime-unlocked-session')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('identity bindings', () => {
|
||||||
|
it('binds an identity to a key', () => {
|
||||||
|
useSmimeStore.getState().bindIdentityToKey('identity-1', 'key-1');
|
||||||
|
expect(useSmimeStore.getState().identityKeyBindings['identity-1']).toBe('key-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unbinds an identity', () => {
|
||||||
|
useSmimeStore.setState({ identityKeyBindings: { 'identity-1': 'key-1' } });
|
||||||
|
useSmimeStore.getState().bindIdentityToKey('identity-1', null);
|
||||||
|
expect(useSmimeStore.getState().identityKeyBindings['identity-1']).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getKeyRecordForIdentity returns the bound record', () => {
|
||||||
|
useSmimeStore.setState({
|
||||||
|
keyRecords: [mockKeyRecord],
|
||||||
|
identityKeyBindings: { 'identity-1': 'key-1' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const record = useSmimeStore.getState().getKeyRecordForIdentity('identity-1');
|
||||||
|
expect(record?.id).toBe('key-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getKeyRecordForIdentity returns undefined for unbound identity', () => {
|
||||||
|
const record = useSmimeStore.getState().getKeyRecordForIdentity('identity-2');
|
||||||
|
expect(record).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getPublicCertForEmail', () => {
|
||||||
|
it('finds cert by email (case-insensitive)', () => {
|
||||||
|
const cert: SmimePublicCert = {
|
||||||
|
id: 'c1',
|
||||||
|
email: 'bob@example.com',
|
||||||
|
certificate: new ArrayBuffer(10),
|
||||||
|
issuer: 'CN=CA',
|
||||||
|
subject: 'CN=Bob',
|
||||||
|
notBefore: '2024-01-01',
|
||||||
|
notAfter: '2030-12-31',
|
||||||
|
fingerprint: 'ff',
|
||||||
|
source: 'manual',
|
||||||
|
};
|
||||||
|
useSmimeStore.setState({ publicCerts: [cert] });
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().getPublicCertForEmail('Bob@Example.COM')?.id).toBe('c1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined when not found', () => {
|
||||||
|
expect(useSmimeStore.getState().getPublicCertForEmail('nobody@test.com')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getRecipientCerts', () => {
|
||||||
|
it('partitions emails into found and missing', () => {
|
||||||
|
const cert: SmimePublicCert = {
|
||||||
|
id: 'c1',
|
||||||
|
email: 'known@example.com',
|
||||||
|
certificate: new ArrayBuffer(10),
|
||||||
|
issuer: '',
|
||||||
|
subject: '',
|
||||||
|
notBefore: '',
|
||||||
|
notAfter: '',
|
||||||
|
fingerprint: '',
|
||||||
|
source: 'manual',
|
||||||
|
};
|
||||||
|
useSmimeStore.setState({ publicCerts: [cert] });
|
||||||
|
|
||||||
|
const { found, missing } = useSmimeStore.getState().getRecipientCerts([
|
||||||
|
'known@example.com',
|
||||||
|
'unknown@example.com',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(found).toHaveLength(1);
|
||||||
|
expect(found[0].id).toBe('c1');
|
||||||
|
expect(missing).toEqual(['unknown@example.com']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('preferences', () => {
|
||||||
|
it('sets sign default for identity', () => {
|
||||||
|
useSmimeStore.getState().setSignDefault('identity-1', true);
|
||||||
|
expect(useSmimeStore.getState().defaultSignIdentity['identity-1']).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets encrypt default', () => {
|
||||||
|
useSmimeStore.getState().setEncryptDefault(true);
|
||||||
|
expect(useSmimeStore.getState().defaultEncrypt).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets remember unlocked keys and clears when disabled', () => {
|
||||||
|
sessionStorage.setItem('smime-unlocked-session', JSON.stringify({ 'key-1': 'passphrase' }));
|
||||||
|
useSmimeStore.setState({
|
||||||
|
unlockedKeys: new Map([['key-1', {} as CryptoKey]]),
|
||||||
|
});
|
||||||
|
|
||||||
|
useSmimeStore.getState().setRememberUnlockedKeys(false);
|
||||||
|
|
||||||
|
expect(useSmimeStore.getState().rememberUnlockedKeys).toBe(false);
|
||||||
|
expect(useSmimeStore.getState().unlockedKeys.size).toBe(0);
|
||||||
|
expect(sessionStorage.getItem('smime-unlocked-session')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets auto import signer certs', () => {
|
||||||
|
useSmimeStore.getState().setAutoImportSignerCerts(true);
|
||||||
|
expect(useSmimeStore.getState().autoImportSignerCerts).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('setError', () => {
|
||||||
|
it('sets and clears error', () => {
|
||||||
|
useSmimeStore.getState().setError('Something went wrong');
|
||||||
|
expect(useSmimeStore.getState().error).toBe('Something went wrong');
|
||||||
|
|
||||||
|
useSmimeStore.getState().setError(null);
|
||||||
|
expect(useSmimeStore.getState().error).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import { Convert } from 'pvtsutils';
|
||||||
|
import type { CertificateInfo, SmimeKeyCapabilities } from './types';
|
||||||
|
|
||||||
|
/** OID for id-kp-emailProtection (S/MIME) */
|
||||||
|
const OID_EMAIL_PROTECTION = '1.3.6.1.5.5.7.3.4';
|
||||||
|
|
||||||
|
/** OID for SubjectAlternativeName */
|
||||||
|
const OID_SAN = '2.5.29.17';
|
||||||
|
|
||||||
|
// ── PEM/DER conversions ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function pemToDer(pem: string): ArrayBuffer {
|
||||||
|
const lines = pem
|
||||||
|
.replace(/-----BEGIN [^-]+-----/, '')
|
||||||
|
.replace(/-----END [^-]+-----/, '')
|
||||||
|
.replace(/\s/g, '');
|
||||||
|
return Convert.FromBase64(lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function derToPem(der: ArrayBuffer, label: string): string {
|
||||||
|
const b64 = Convert.ToBase64(der);
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (let i = 0; i < b64.length; i += 64) {
|
||||||
|
lines.push(b64.slice(i, i + 64));
|
||||||
|
}
|
||||||
|
return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPem(data: string): boolean {
|
||||||
|
return /-----BEGIN (CERTIFICATE|PKCS12|ENCRYPTED PRIVATE KEY|PRIVATE KEY)-----/.test(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Certificate parsing ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function parseCertificateDer(der: ArrayBuffer): pkijs.Certificate {
|
||||||
|
const asn1 = asn1js.fromBER(der);
|
||||||
|
if (asn1.offset === -1) {
|
||||||
|
throw new Error('Invalid DER data: ASN.1 parsing failed');
|
||||||
|
}
|
||||||
|
return new pkijs.Certificate({ schema: asn1.result });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseCertificatePemOrDer(data: ArrayBuffer | string): pkijs.Certificate {
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
if (isPem(data)) {
|
||||||
|
return parseCertificateDer(pemToDer(data));
|
||||||
|
}
|
||||||
|
throw new Error('String input is not PEM-encoded');
|
||||||
|
}
|
||||||
|
// ArrayBuffer might contain PEM text rather than DER binary
|
||||||
|
// PEM files start with "-----BEGIN " (0x2D 0x2D 0x2D 0x2D 0x2D 0x42)
|
||||||
|
const header = new Uint8Array(data, 0, Math.min(20, data.byteLength));
|
||||||
|
const maybePem = String.fromCharCode(...header);
|
||||||
|
if (maybePem.startsWith('-----BEGIN ')) {
|
||||||
|
const text = new TextDecoder().decode(data);
|
||||||
|
return parseCertificateDer(pemToDer(text));
|
||||||
|
}
|
||||||
|
return parseCertificateDer(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Metadata extraction ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
function rdnToString(rdn: pkijs.RelativeDistinguishedNames): string {
|
||||||
|
return rdn.typesAndValues
|
||||||
|
.map((tv) => {
|
||||||
|
const oid = tv.type;
|
||||||
|
const val = tv.value.valueBlock.value;
|
||||||
|
const name = oidToName(oid);
|
||||||
|
return `${name}=${val}`;
|
||||||
|
})
|
||||||
|
.join(', ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function oidToName(oid: string): string {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
'2.5.4.3': 'CN',
|
||||||
|
'2.5.4.6': 'C',
|
||||||
|
'2.5.4.7': 'L',
|
||||||
|
'2.5.4.8': 'ST',
|
||||||
|
'2.5.4.10': 'O',
|
||||||
|
'2.5.4.11': 'OU',
|
||||||
|
'1.2.840.113549.1.9.1': 'E',
|
||||||
|
};
|
||||||
|
return map[oid] ?? oid;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function computeFingerprint(der: ArrayBuffer): Promise<string> {
|
||||||
|
const hash = await crypto.subtle.digest('SHA-256', new Uint8Array(der));
|
||||||
|
return Array.from(new Uint8Array(hash))
|
||||||
|
.map((b) => b.toString(16).padStart(2, '0'))
|
||||||
|
.join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractAlgorithm(cert: pkijs.Certificate): string {
|
||||||
|
const algOid = cert.subjectPublicKeyInfo.algorithm.algorithmId;
|
||||||
|
// RSA
|
||||||
|
if (algOid === '1.2.840.113549.1.1.1') {
|
||||||
|
const pubKey = cert.subjectPublicKeyInfo;
|
||||||
|
try {
|
||||||
|
const asn1Pub = asn1js.fromBER(pubKey.subjectPublicKey.valueBlock.valueHexView);
|
||||||
|
const seq = asn1Pub.result as asn1js.Sequence;
|
||||||
|
const modulus = seq.valueBlock.value[0] as asn1js.Integer;
|
||||||
|
const bitLen = (modulus.valueBlock.valueHexView.byteLength - 1) * 8;
|
||||||
|
return `RSA-${bitLen}`;
|
||||||
|
} catch {
|
||||||
|
return 'RSA';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ECDSA
|
||||||
|
if (algOid === '1.2.840.10045.2.1') {
|
||||||
|
const params = cert.subjectPublicKeyInfo.algorithm.algorithmParams;
|
||||||
|
if (params instanceof asn1js.ObjectIdentifier) {
|
||||||
|
const curveOid = params.valueBlock.toString();
|
||||||
|
const curves: Record<string, string> = {
|
||||||
|
'1.2.840.10045.3.1.7': 'ECDSA-P256',
|
||||||
|
'1.3.132.0.34': 'ECDSA-P384',
|
||||||
|
'1.3.132.0.35': 'ECDSA-P521',
|
||||||
|
};
|
||||||
|
return curves[curveOid] ?? 'ECDSA';
|
||||||
|
}
|
||||||
|
return 'ECDSA';
|
||||||
|
}
|
||||||
|
return algOid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractKeyUsage(cert: pkijs.Certificate): string[] | undefined {
|
||||||
|
const ext = cert.extensions?.find((e) => e.extnID === '2.5.29.15');
|
||||||
|
if (!ext?.parsedValue) return undefined;
|
||||||
|
const ku = ext.parsedValue as {
|
||||||
|
digitalSignature?: boolean;
|
||||||
|
contentCommitment?: boolean;
|
||||||
|
keyEncipherment?: boolean;
|
||||||
|
dataEncipherment?: boolean;
|
||||||
|
keyAgreement?: boolean;
|
||||||
|
keyCertSign?: boolean;
|
||||||
|
cRLSign?: boolean;
|
||||||
|
encipherOnly?: boolean;
|
||||||
|
decipherOnly?: boolean;
|
||||||
|
};
|
||||||
|
const names: string[] = [];
|
||||||
|
if (ku.digitalSignature) names.push('digitalSignature');
|
||||||
|
if (ku.contentCommitment) names.push('contentCommitment');
|
||||||
|
if (ku.keyEncipherment) names.push('keyEncipherment');
|
||||||
|
if (ku.dataEncipherment) names.push('dataEncipherment');
|
||||||
|
if (ku.keyAgreement) names.push('keyAgreement');
|
||||||
|
if (ku.keyCertSign) names.push('keyCertSign');
|
||||||
|
if (ku.cRLSign) names.push('cRLSign');
|
||||||
|
if (ku.encipherOnly) names.push('encipherOnly');
|
||||||
|
if (ku.decipherOnly) names.push('decipherOnly');
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractExtendedKeyUsage(cert: pkijs.Certificate): string[] | undefined {
|
||||||
|
const ext = cert.extensions?.find((e) => e.extnID === '2.5.29.37');
|
||||||
|
if (!ext?.parsedValue) return undefined;
|
||||||
|
const eku = ext.parsedValue as pkijs.ExtKeyUsage;
|
||||||
|
return eku.keyPurposes;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractEmailAddresses(cert: pkijs.Certificate): string[] {
|
||||||
|
const emails: string[] = [];
|
||||||
|
|
||||||
|
// From subject emailAddress attribute
|
||||||
|
for (const tv of cert.subject.typesAndValues) {
|
||||||
|
if (tv.type === '1.2.840.113549.1.9.1') {
|
||||||
|
emails.push(tv.value.valueBlock.value as string);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// From SubjectAlternativeName
|
||||||
|
const sanExt = cert.extensions?.find((e) => e.extnID === OID_SAN);
|
||||||
|
if (sanExt?.parsedValue) {
|
||||||
|
const san = sanExt.parsedValue as pkijs.GeneralNames;
|
||||||
|
for (const name of san.names) {
|
||||||
|
// type 1 = rfc822Name
|
||||||
|
if (name.type === 1 && typeof name.value === 'string') {
|
||||||
|
if (!emails.includes(name.value)) {
|
||||||
|
emails.push(name.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return emails;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Determine signing/encryption capabilities from KU / EKU. Tolerant of absent extensions. */
|
||||||
|
export function classifyCapabilities(cert: pkijs.Certificate): SmimeKeyCapabilities {
|
||||||
|
const ku = extractKeyUsage(cert);
|
||||||
|
const eku = extractExtendedKeyUsage(cert);
|
||||||
|
|
||||||
|
let canSign = true;
|
||||||
|
let canEncrypt = true;
|
||||||
|
|
||||||
|
// If KeyUsage is present, check explicit bits
|
||||||
|
if (ku) {
|
||||||
|
canSign = ku.includes('digitalSignature') || ku.includes('contentCommitment');
|
||||||
|
canEncrypt = ku.includes('keyEncipherment') || ku.includes('dataEncipherment') || ku.includes('keyAgreement');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If EKU is present, only reject if it explicitly excludes emailProtection
|
||||||
|
if (eku && eku.length > 0) {
|
||||||
|
const hasEmailProtection = eku.includes(OID_EMAIL_PROTECTION);
|
||||||
|
// Only restrict if EKU is present and does NOT include emailProtection
|
||||||
|
if (!hasEmailProtection) {
|
||||||
|
canSign = false;
|
||||||
|
canEncrypt = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { canSign, canEncrypt };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extract full metadata from a parsed certificate. */
|
||||||
|
export async function extractCertificateInfo(
|
||||||
|
cert: pkijs.Certificate,
|
||||||
|
der: ArrayBuffer,
|
||||||
|
): Promise<CertificateInfo> {
|
||||||
|
const fingerprint = await computeFingerprint(der);
|
||||||
|
const ku = extractKeyUsage(cert);
|
||||||
|
const eku = extractExtendedKeyUsage(cert);
|
||||||
|
const capabilities = classifyCapabilities(cert);
|
||||||
|
|
||||||
|
return {
|
||||||
|
subject: rdnToString(cert.subject),
|
||||||
|
issuer: rdnToString(cert.issuer),
|
||||||
|
serialNumber: cert.serialNumber.valueBlock.valueHexView
|
||||||
|
? Array.from(new Uint8Array(cert.serialNumber.valueBlock.valueHexView))
|
||||||
|
.map((b) => b.toString(16).padStart(2, '0'))
|
||||||
|
.join(':')
|
||||||
|
: cert.serialNumber.valueBlock.toString(),
|
||||||
|
notBefore: cert.notBefore.value.toISOString(),
|
||||||
|
notAfter: cert.notAfter.value.toISOString(),
|
||||||
|
fingerprint,
|
||||||
|
algorithm: extractAlgorithm(cert),
|
||||||
|
keyUsage: ku,
|
||||||
|
extendedKeyUsage: eku,
|
||||||
|
emailAddresses: extractEmailAddresses(cert),
|
||||||
|
capabilities,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/**
|
||||||
|
* Crypto engine backed by webcrypto-liner for legacy algorithm support.
|
||||||
|
*
|
||||||
|
* webcrypto-liner extends the native Web Crypto API with algorithms
|
||||||
|
* like DES-EDE3-CBC (3DES) that are commonly found in S/MIME messages
|
||||||
|
* and PKCS#12 files produced by legacy clients (Outlook, Thunderbird, etc.).
|
||||||
|
*
|
||||||
|
* Native Web Crypto calls are passed through to the real implementation;
|
||||||
|
* liner only intercepts algorithms that the browser doesn't natively support.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
|
||||||
|
// webcrypto-liner exports a Crypto constructor at runtime that extends native
|
||||||
|
// Web Crypto with legacy algorithms (3DES, etc.). Its type declarations only
|
||||||
|
// expose the type alias, so we import the module dynamically and cast.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
|
const liner = require('webcrypto-liner') as {
|
||||||
|
Crypto: { new (): Crypto };
|
||||||
|
setCrypto: (subtle: SubtleCrypto) => void;
|
||||||
|
nativeCrypto: Crypto | Record<string, never>;
|
||||||
|
};
|
||||||
|
|
||||||
|
let linerEngine: pkijs.CryptoEngine | null = null;
|
||||||
|
let linerCryptoInstance: Crypto | null = null;
|
||||||
|
|
||||||
|
function ensureLiner() {
|
||||||
|
if (!linerCryptoInstance) {
|
||||||
|
// In Node.js, webcrypto-liner can't auto-detect the native crypto
|
||||||
|
// (it looks for self.crypto which doesn't exist). Feed it manually
|
||||||
|
// so that native algorithms (RSA, AES, etc.) stay hardware-accelerated
|
||||||
|
// and only truly missing algorithms (3DES) use the software fallback.
|
||||||
|
if (
|
||||||
|
typeof liner.nativeCrypto?.getRandomValues !== 'function' &&
|
||||||
|
typeof globalThis.crypto?.subtle !== 'undefined'
|
||||||
|
) {
|
||||||
|
liner.setCrypto(globalThis.crypto.subtle);
|
||||||
|
}
|
||||||
|
linerCryptoInstance = new liner.Crypto();
|
||||||
|
}
|
||||||
|
if (!linerEngine) {
|
||||||
|
linerEngine = new pkijs.CryptoEngine({
|
||||||
|
crypto: linerCryptoInstance,
|
||||||
|
subtle: linerCryptoInstance.subtle,
|
||||||
|
name: 'webcrypto-liner',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get a PKI.js CryptoEngine with 3DES (and other legacy algorithm) support. */
|
||||||
|
export function getLinerCryptoEngine(): pkijs.CryptoEngine {
|
||||||
|
ensureLiner();
|
||||||
|
return linerEngine!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run an async operation with the global PKI.js engine set to webcrypto-liner,
|
||||||
|
* then restore the previous engine afterwards.
|
||||||
|
*
|
||||||
|
* Required for operations that use the global engine internally
|
||||||
|
* (e.g. PFX.parseInternalValues for PKCS#12 import).
|
||||||
|
*/
|
||||||
|
export async function withLinerEngine<T>(fn: () => Promise<T>): Promise<T> {
|
||||||
|
ensureLiner();
|
||||||
|
|
||||||
|
// Save the current global engine so we can restore it
|
||||||
|
const prev = pkijs.getEngine();
|
||||||
|
|
||||||
|
pkijs.setEngine('webcrypto-liner', linerCryptoInstance!, linerEngine!);
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} finally {
|
||||||
|
// Restore the previous engine
|
||||||
|
pkijs.setEngine(prev.name, prev.crypto as unknown as pkijs.CryptoEngine);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import type { SmimeKeyRecord, SmimePublicCert } from './types';
|
||||||
|
|
||||||
|
const DB_NAME = 'smime-store';
|
||||||
|
const DB_VERSION = 1;
|
||||||
|
const KEY_RECORDS_STORE = 'key-records';
|
||||||
|
const PUBLIC_CERTS_STORE = 'public-certs';
|
||||||
|
|
||||||
|
function openDB(): Promise<IDBDatabase> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||||
|
request.onupgradeneeded = () => {
|
||||||
|
const db = request.result;
|
||||||
|
if (!db.objectStoreNames.contains(KEY_RECORDS_STORE)) {
|
||||||
|
const keyStore = db.createObjectStore(KEY_RECORDS_STORE, { keyPath: 'id' });
|
||||||
|
keyStore.createIndex('email', 'email', { unique: false });
|
||||||
|
}
|
||||||
|
if (!db.objectStoreNames.contains(PUBLIC_CERTS_STORE)) {
|
||||||
|
const certStore = db.createObjectStore(PUBLIC_CERTS_STORE, { keyPath: 'id' });
|
||||||
|
certStore.createIndex('email', 'email', { unique: false });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
request.onsuccess = () => resolve(request.result);
|
||||||
|
request.onerror = () => reject(request.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function txPromise<T>(
|
||||||
|
db: IDBDatabase,
|
||||||
|
storeName: string,
|
||||||
|
mode: globalThis.IDBTransactionMode,
|
||||||
|
fn: (store: IDBObjectStore) => IDBRequest<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const tx = db.transaction(storeName, mode);
|
||||||
|
const store = tx.objectStore(storeName);
|
||||||
|
const req = fn(store);
|
||||||
|
req.onsuccess = () => resolve(req.result);
|
||||||
|
req.onerror = () => reject(req.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Key record CRUD ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function saveKeyRecord(record: SmimeKeyRecord): Promise<void> {
|
||||||
|
const db = await openDB();
|
||||||
|
await txPromise(db, KEY_RECORDS_STORE, 'readwrite', (s) => s.put(record));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getKeyRecord(id: string): Promise<SmimeKeyRecord | undefined> {
|
||||||
|
const db = await openDB();
|
||||||
|
return txPromise(db, KEY_RECORDS_STORE, 'readonly', (s) => s.get(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getKeyRecordForEmail(email: string): Promise<SmimeKeyRecord | undefined> {
|
||||||
|
const db = await openDB();
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const tx = db.transaction(KEY_RECORDS_STORE, 'readonly');
|
||||||
|
const idx = tx.objectStore(KEY_RECORDS_STORE).index('email');
|
||||||
|
const req = idx.get(email.toLowerCase());
|
||||||
|
req.onsuccess = () => resolve(req.result ?? undefined);
|
||||||
|
req.onerror = () => reject(req.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listKeyRecords(): Promise<SmimeKeyRecord[]> {
|
||||||
|
const db = await openDB();
|
||||||
|
return txPromise(db, KEY_RECORDS_STORE, 'readonly', (s) => s.getAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteKeyRecord(id: string): Promise<void> {
|
||||||
|
const db = await openDB();
|
||||||
|
await txPromise(db, KEY_RECORDS_STORE, 'readwrite', (s) => s.delete(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Public cert CRUD ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function savePublicCert(cert: SmimePublicCert): Promise<void> {
|
||||||
|
const db = await openDB();
|
||||||
|
await txPromise(db, PUBLIC_CERTS_STORE, 'readwrite', (s) => s.put(cert));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPublicCertForEmail(email: string): Promise<SmimePublicCert | undefined> {
|
||||||
|
const db = await openDB();
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const tx = db.transaction(PUBLIC_CERTS_STORE, 'readonly');
|
||||||
|
const idx = tx.objectStore(PUBLIC_CERTS_STORE).index('email');
|
||||||
|
const req = idx.get(email.toLowerCase());
|
||||||
|
req.onsuccess = () => resolve(req.result ?? undefined);
|
||||||
|
req.onerror = () => reject(req.error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listPublicCerts(): Promise<SmimePublicCert[]> {
|
||||||
|
const db = await openDB();
|
||||||
|
return txPromise(db, PUBLIC_CERTS_STORE, 'readonly', (s) => s.getAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePublicCert(id: string): Promise<void> {
|
||||||
|
const db = await openDB();
|
||||||
|
await txPromise(db, PUBLIC_CERTS_STORE, 'readwrite', (s) => s.delete(id));
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
/**
|
||||||
|
* Minimal, deterministic MIME builder for outgoing S/MIME messages.
|
||||||
|
*
|
||||||
|
* Produces canonical text suitable for CMS signing/encryption.
|
||||||
|
* All line endings are CRLF per RFC 5322.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const CRLF = '\r\n';
|
||||||
|
|
||||||
|
export interface MimeAttachment {
|
||||||
|
filename: string;
|
||||||
|
contentType: string;
|
||||||
|
content: ArrayBuffer;
|
||||||
|
cid?: string; // for inline images
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MimeMessageInput {
|
||||||
|
from: { name?: string; email: string };
|
||||||
|
to: { name?: string; email: string }[];
|
||||||
|
cc?: { name?: string; email: string }[];
|
||||||
|
bcc?: { name?: string; email: string }[];
|
||||||
|
subject: string;
|
||||||
|
date?: Date;
|
||||||
|
messageId?: string;
|
||||||
|
inReplyTo?: string;
|
||||||
|
references?: string[];
|
||||||
|
textBody?: string;
|
||||||
|
htmlBody?: string;
|
||||||
|
attachments?: MimeAttachment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build a complete MIME message and return it as a Uint8Array (UTF-8). */
|
||||||
|
export function buildMimeMessage(input: MimeMessageInput): Uint8Array {
|
||||||
|
const boundary = generateBoundary();
|
||||||
|
const lines: string[] = [];
|
||||||
|
|
||||||
|
// Headers
|
||||||
|
lines.push(formatHeader('From', formatAddress(input.from)));
|
||||||
|
lines.push(formatHeader('To', input.to.map(formatAddress).join(', ')));
|
||||||
|
if (input.cc?.length) {
|
||||||
|
lines.push(formatHeader('Cc', input.cc.map(formatAddress).join(', ')));
|
||||||
|
}
|
||||||
|
// BCC is intentionally omitted from the MIME headers per RFC 5322
|
||||||
|
lines.push(formatHeader('Subject', encodeHeaderValue(input.subject)));
|
||||||
|
lines.push(formatHeader('Date', formatDate(input.date ?? new Date())));
|
||||||
|
lines.push(formatHeader('Message-ID', input.messageId ?? `<${crypto.randomUUID()}@smime.local>`));
|
||||||
|
if (input.inReplyTo) {
|
||||||
|
lines.push(formatHeader('In-Reply-To', input.inReplyTo));
|
||||||
|
}
|
||||||
|
if (input.references?.length) {
|
||||||
|
lines.push(formatHeader('References', input.references.join(' ')));
|
||||||
|
}
|
||||||
|
lines.push('MIME-Version: 1.0');
|
||||||
|
|
||||||
|
const hasText = !!input.textBody;
|
||||||
|
const hasHtml = !!input.htmlBody;
|
||||||
|
const hasAttachments = !!input.attachments?.length;
|
||||||
|
|
||||||
|
if (!hasAttachments && hasText && !hasHtml) {
|
||||||
|
// text/plain only
|
||||||
|
lines.push('Content-Type: text/plain; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.textBody!));
|
||||||
|
} else if (!hasAttachments && hasText && hasHtml) {
|
||||||
|
// multipart/alternative
|
||||||
|
const altBoundary = generateBoundary();
|
||||||
|
lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
|
||||||
|
lines.push('');
|
||||||
|
lines.push(`--${altBoundary}`);
|
||||||
|
lines.push('Content-Type: text/plain; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.textBody!));
|
||||||
|
lines.push(`--${altBoundary}`);
|
||||||
|
lines.push('Content-Type: text/html; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.htmlBody!));
|
||||||
|
lines.push(`--${altBoundary}--`);
|
||||||
|
} else if (!hasAttachments && !hasText && hasHtml) {
|
||||||
|
// html only
|
||||||
|
lines.push('Content-Type: text/html; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.htmlBody!));
|
||||||
|
} else if (hasAttachments) {
|
||||||
|
// multipart/mixed
|
||||||
|
lines.push(`Content-Type: multipart/mixed; boundary="${boundary}"`);
|
||||||
|
lines.push('');
|
||||||
|
|
||||||
|
// Body part
|
||||||
|
if (hasText && hasHtml) {
|
||||||
|
const altBoundary = generateBoundary();
|
||||||
|
lines.push(`--${boundary}`);
|
||||||
|
lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
|
||||||
|
lines.push('');
|
||||||
|
lines.push(`--${altBoundary}`);
|
||||||
|
lines.push('Content-Type: text/plain; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.textBody!));
|
||||||
|
lines.push(`--${altBoundary}`);
|
||||||
|
lines.push('Content-Type: text/html; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.htmlBody!));
|
||||||
|
lines.push(`--${altBoundary}--`);
|
||||||
|
} else if (hasText) {
|
||||||
|
lines.push(`--${boundary}`);
|
||||||
|
lines.push('Content-Type: text/plain; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.textBody!));
|
||||||
|
} else if (hasHtml) {
|
||||||
|
lines.push(`--${boundary}`);
|
||||||
|
lines.push('Content-Type: text/html; charset=utf-8');
|
||||||
|
lines.push('Content-Transfer-Encoding: quoted-printable');
|
||||||
|
lines.push('');
|
||||||
|
lines.push(quotedPrintableEncode(input.htmlBody!));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attachments
|
||||||
|
for (const att of input.attachments!) {
|
||||||
|
lines.push(`--${boundary}`);
|
||||||
|
const disposition = att.cid ? 'inline' : 'attachment';
|
||||||
|
lines.push(`Content-Type: ${att.contentType}; name="${encodeHeaderValue(att.filename)}"`);
|
||||||
|
lines.push(`Content-Disposition: ${disposition}; filename="${encodeHeaderValue(att.filename)}"`);
|
||||||
|
lines.push('Content-Transfer-Encoding: base64');
|
||||||
|
if (att.cid) {
|
||||||
|
lines.push(`Content-ID: <${att.cid}>`);
|
||||||
|
}
|
||||||
|
lines.push('');
|
||||||
|
lines.push(base64Encode(att.content));
|
||||||
|
}
|
||||||
|
lines.push(`--${boundary}--`);
|
||||||
|
} else {
|
||||||
|
// Empty body
|
||||||
|
lines.push('Content-Type: text/plain; charset=utf-8');
|
||||||
|
lines.push('');
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = lines.join(CRLF);
|
||||||
|
return new TextEncoder().encode(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function generateBoundary(): string {
|
||||||
|
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
||||||
|
const hex = Array.from(bytes)
|
||||||
|
.map((b) => b.toString(16).padStart(2, '0'))
|
||||||
|
.join('');
|
||||||
|
return `----=_Part_${hex}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAddress(addr: { name?: string; email: string }): string {
|
||||||
|
if (addr.name) {
|
||||||
|
// RFC 5322 quoted-string for display name
|
||||||
|
const escaped = addr.name.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
||||||
|
return `"${escaped}" <${addr.email}>`;
|
||||||
|
}
|
||||||
|
return addr.email;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatHeader(name: string, value: string): string {
|
||||||
|
const full = `${name}: ${value}`;
|
||||||
|
// RFC 5322 line length limit: fold at 76 chars
|
||||||
|
if (full.length <= 76) return full;
|
||||||
|
const parts: string[] = [];
|
||||||
|
let remaining = full;
|
||||||
|
let first = true;
|
||||||
|
while (remaining.length > 76) {
|
||||||
|
let breakAt = 76;
|
||||||
|
// Find a space to break at
|
||||||
|
const spaceIdx = remaining.lastIndexOf(' ', 76);
|
||||||
|
if (spaceIdx > (first ? name.length + 2 : 1)) {
|
||||||
|
breakAt = spaceIdx;
|
||||||
|
}
|
||||||
|
parts.push(remaining.slice(0, breakAt));
|
||||||
|
remaining = ' ' + remaining.slice(breakAt).trimStart();
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
parts.push(remaining);
|
||||||
|
return parts.join(CRLF);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeHeaderValue(value: string): string {
|
||||||
|
// Use RFC 2047 encoded-word if non-ASCII
|
||||||
|
if (/^[\x20-\x7e]*$/.test(value)) return value;
|
||||||
|
const encoded = Array.from(new TextEncoder().encode(value))
|
||||||
|
.map((b) => {
|
||||||
|
if (
|
||||||
|
(b >= 0x30 && b <= 0x39) || // 0-9
|
||||||
|
(b >= 0x41 && b <= 0x5a) || // A-Z
|
||||||
|
(b >= 0x61 && b <= 0x7a) // a-z
|
||||||
|
) {
|
||||||
|
return String.fromCharCode(b);
|
||||||
|
}
|
||||||
|
return '=' + b.toString(16).toUpperCase().padStart(2, '0');
|
||||||
|
})
|
||||||
|
.join('');
|
||||||
|
return `=?UTF-8?Q?${encoded}?=`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(date: Date): string {
|
||||||
|
// RFC 5322 date format
|
||||||
|
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||||
|
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||||
|
const d = days[date.getUTCDay()];
|
||||||
|
const dd = date.getUTCDate();
|
||||||
|
const m = months[date.getUTCMonth()];
|
||||||
|
const y = date.getUTCFullYear();
|
||||||
|
const hh = date.getUTCHours().toString().padStart(2, '0');
|
||||||
|
const mm = date.getUTCMinutes().toString().padStart(2, '0');
|
||||||
|
const ss = date.getUTCSeconds().toString().padStart(2, '0');
|
||||||
|
return `${d}, ${dd} ${m} ${y} ${hh}:${mm}:${ss} +0000`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SmimeWrapInput {
|
||||||
|
from: { name?: string; email: string };
|
||||||
|
to: { name?: string; email: string }[];
|
||||||
|
cc?: { name?: string; email: string }[];
|
||||||
|
subject: string;
|
||||||
|
date?: Date;
|
||||||
|
messageId?: string;
|
||||||
|
inReplyTo?: string;
|
||||||
|
references?: string[];
|
||||||
|
smimeType: 'signed-data' | 'enveloped-data';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap a CMS binary blob in a proper RFC 5322 / S/MIME message.
|
||||||
|
*
|
||||||
|
* The server needs RFC 5322 headers (From, To, Subject, etc.) to route
|
||||||
|
* the message; the CMS blob becomes the base64-encoded body.
|
||||||
|
*/
|
||||||
|
export function wrapCmsAsSmimeMessage(cmsBlob: Blob | ArrayBuffer | Uint8Array, input: SmimeWrapInput): Blob {
|
||||||
|
const lines: string[] = [];
|
||||||
|
|
||||||
|
lines.push(formatHeader('From', formatAddress(input.from)));
|
||||||
|
lines.push(formatHeader('To', input.to.map(formatAddress).join(', ')));
|
||||||
|
if (input.cc?.length) {
|
||||||
|
lines.push(formatHeader('Cc', input.cc.map(formatAddress).join(', ')));
|
||||||
|
}
|
||||||
|
lines.push(formatHeader('Subject', encodeHeaderValue(input.subject)));
|
||||||
|
lines.push(formatHeader('Date', formatDate(input.date ?? new Date())));
|
||||||
|
lines.push(formatHeader('Message-ID', input.messageId ?? `<${crypto.randomUUID()}@smime.local>`));
|
||||||
|
if (input.inReplyTo) {
|
||||||
|
lines.push(formatHeader('In-Reply-To', input.inReplyTo));
|
||||||
|
}
|
||||||
|
if (input.references?.length) {
|
||||||
|
lines.push(formatHeader('References', input.references.join(' ')));
|
||||||
|
}
|
||||||
|
lines.push('MIME-Version: 1.0');
|
||||||
|
lines.push(`Content-Type: application/pkcs7-mime; smime-type=${input.smimeType}; name="smime.p7m"`);
|
||||||
|
lines.push('Content-Transfer-Encoding: base64');
|
||||||
|
lines.push('Content-Disposition: attachment; filename="smime.p7m"');
|
||||||
|
lines.push('');
|
||||||
|
|
||||||
|
const headerPart = lines.join(CRLF);
|
||||||
|
|
||||||
|
// We'll combine header bytes + base64 body
|
||||||
|
const headerBytes = new TextEncoder().encode(headerPart);
|
||||||
|
|
||||||
|
return new Blob([headerBytes, cmsToBase64Blob(cmsBlob)], { type: 'message/rfc822' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function cmsToBase64Blob(data: Blob | ArrayBuffer | Uint8Array): Blob {
|
||||||
|
let bytes: Uint8Array;
|
||||||
|
if (data instanceof Uint8Array) {
|
||||||
|
bytes = data;
|
||||||
|
} else if (data instanceof ArrayBuffer) {
|
||||||
|
bytes = new Uint8Array(data);
|
||||||
|
} else {
|
||||||
|
// Blob — we need sync; caller should have converted. Fallback to empty.
|
||||||
|
bytes = new Uint8Array(0);
|
||||||
|
}
|
||||||
|
const b64 = base64Encode(bytes.buffer as ArrayBuffer);
|
||||||
|
return new Blob([new TextEncoder().encode(b64 + CRLF)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Encode string as quoted-printable (RFC 2045). */
|
||||||
|
export function quotedPrintableEncode(input: string): string {
|
||||||
|
const bytes = new TextEncoder().encode(input);
|
||||||
|
const lines: string[] = [];
|
||||||
|
let line = '';
|
||||||
|
|
||||||
|
for (const b of bytes) {
|
||||||
|
let encoded: string;
|
||||||
|
if (b === 0x0d || b === 0x0a) {
|
||||||
|
// Pass through CRLF as-is (handled below)
|
||||||
|
encoded = String.fromCharCode(b);
|
||||||
|
} else if (
|
||||||
|
b === 0x09 || // tab
|
||||||
|
(b >= 0x20 && b <= 0x7e && b !== 0x3d) // printable, not '='
|
||||||
|
) {
|
||||||
|
encoded = String.fromCharCode(b);
|
||||||
|
} else {
|
||||||
|
encoded = '=' + b.toString(16).toUpperCase().padStart(2, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (b === 0x0a) {
|
||||||
|
// End current line (strip any trailing \r already added)
|
||||||
|
if (line.endsWith('\r')) {
|
||||||
|
line = line.slice(0, -1);
|
||||||
|
}
|
||||||
|
lines.push(line);
|
||||||
|
line = '';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.length + encoded.length > 75) {
|
||||||
|
lines.push(line + '=');
|
||||||
|
line = encoded;
|
||||||
|
} else {
|
||||||
|
line += encoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push(line);
|
||||||
|
return lines.join(CRLF);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Encode ArrayBuffer as base64 with line breaks at 76 chars. */
|
||||||
|
export function base64Encode(data: ArrayBuffer): string {
|
||||||
|
const bytes = new Uint8Array(data);
|
||||||
|
let binary = '';
|
||||||
|
for (const b of bytes) {
|
||||||
|
binary += String.fromCharCode(b);
|
||||||
|
}
|
||||||
|
const b64 = btoa(binary);
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (let i = 0; i < b64.length; i += 76) {
|
||||||
|
lines.push(b64.slice(i, i + 76));
|
||||||
|
}
|
||||||
|
return lines.join(CRLF);
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import { decryptPrivateKeyBytes } from './pkcs12-import';
|
||||||
|
import type { SmimeKeyRecord } from './types';
|
||||||
|
|
||||||
|
function stringToArrayBuffer(str: string): ArrayBuffer {
|
||||||
|
const buf = new ArrayBuffer(str.length);
|
||||||
|
const view = new Uint8Array(buf);
|
||||||
|
for (let i = 0; i < str.length; i++) {
|
||||||
|
view[i] = str.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export an S/MIME key record as a PKCS#12 (.p12) file.
|
||||||
|
*
|
||||||
|
* Flow:
|
||||||
|
* 1. Decrypt the stored PKCS#8 private key bytes using the storage passphrase.
|
||||||
|
* 2. Build a PKCS#12 container with the private key, leaf cert, and chain.
|
||||||
|
* 3. Protect the PKCS#12 with the export passphrase.
|
||||||
|
* 4. Return the resulting bytes for browser download.
|
||||||
|
*/
|
||||||
|
export async function exportPkcs12(
|
||||||
|
record: SmimeKeyRecord,
|
||||||
|
storagePassphrase: string,
|
||||||
|
exportPassphrase: string,
|
||||||
|
): Promise<ArrayBuffer> {
|
||||||
|
// Step 1: Decrypt the stored private key
|
||||||
|
const pkcs8Bytes = await decryptPrivateKeyBytes(record, storagePassphrase);
|
||||||
|
|
||||||
|
// Step 2: Parse the leaf certificate
|
||||||
|
const leafCertAsn1 = asn1js.fromBER(record.certificate);
|
||||||
|
if (leafCertAsn1.offset === -1) {
|
||||||
|
throw new Error('Failed to parse leaf certificate');
|
||||||
|
}
|
||||||
|
const leafCert = new pkijs.Certificate({ schema: leafCertAsn1.result });
|
||||||
|
|
||||||
|
// Parse chain certificates
|
||||||
|
const chainCerts = record.certificateChain.map((chainDer) => {
|
||||||
|
const chainAsn1 = asn1js.fromBER(chainDer);
|
||||||
|
if (chainAsn1.offset === -1) {
|
||||||
|
throw new Error('Failed to parse chain certificate');
|
||||||
|
}
|
||||||
|
return new pkijs.Certificate({ schema: chainAsn1.result });
|
||||||
|
});
|
||||||
|
|
||||||
|
const passwordBuf = stringToArrayBuffer(exportPassphrase);
|
||||||
|
|
||||||
|
// Step 3: Build the PKCS#12 structure
|
||||||
|
// Create key bag
|
||||||
|
const keyBag = new pkijs.PKCS8ShroudedKeyBag({
|
||||||
|
parsedValue: pkijs.PrivateKeyInfo.fromBER(pkcs8Bytes),
|
||||||
|
});
|
||||||
|
|
||||||
|
await keyBag.makeInternalValues({
|
||||||
|
password: passwordBuf,
|
||||||
|
contentEncryptionAlgorithm: {
|
||||||
|
name: 'AES-CBC',
|
||||||
|
length: 256,
|
||||||
|
} as unknown as Parameters<typeof keyBag.makeInternalValues>[0]['contentEncryptionAlgorithm'],
|
||||||
|
hmacHashAlgorithm: 'SHA-256',
|
||||||
|
iterationCount: 100_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const keyBagSafe = new pkijs.SafeBag({
|
||||||
|
bagId: '1.2.840.113549.1.12.10.1.2', // pkcs8ShroudedKeyBag
|
||||||
|
bagValue: keyBag,
|
||||||
|
bagAttributes: [
|
||||||
|
new pkijs.Attribute({
|
||||||
|
type: '1.2.840.113549.1.9.20', // friendlyName
|
||||||
|
values: [new asn1js.BmpString({ value: record.email })],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create cert bags
|
||||||
|
const certBags = [
|
||||||
|
new pkijs.SafeBag({
|
||||||
|
bagId: '1.2.840.113549.1.12.10.1.3', // certBag
|
||||||
|
bagValue: new pkijs.CertBag({
|
||||||
|
parsedValue: leafCert,
|
||||||
|
}),
|
||||||
|
bagAttributes: [
|
||||||
|
new pkijs.Attribute({
|
||||||
|
type: '1.2.840.113549.1.9.20',
|
||||||
|
values: [new asn1js.BmpString({ value: record.email })],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
...chainCerts.map(
|
||||||
|
(cert) =>
|
||||||
|
new pkijs.SafeBag({
|
||||||
|
bagId: '1.2.840.113549.1.12.10.1.3',
|
||||||
|
bagValue: new pkijs.CertBag({
|
||||||
|
parsedValue: cert,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Build authenticated safe with two SafeContents:
|
||||||
|
// 1. Key bag (password-encrypted)
|
||||||
|
// 2. Cert bags (unencrypted)
|
||||||
|
const authenticatedSafe = new pkijs.AuthenticatedSafe({
|
||||||
|
parsedValue: {
|
||||||
|
safeContents: [
|
||||||
|
{
|
||||||
|
privacyMode: 0, // no extra encryption — key bag is already shrouded
|
||||||
|
value: new pkijs.SafeContents({
|
||||||
|
safeBags: [keyBagSafe],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
privacyMode: 0,
|
||||||
|
value: new pkijs.SafeContents({
|
||||||
|
safeBags: certBags,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await authenticatedSafe.makeInternalValues({
|
||||||
|
safeContents: [{}, {}],
|
||||||
|
});
|
||||||
|
|
||||||
|
const pfx = new pkijs.PFX({
|
||||||
|
parsedValue: {
|
||||||
|
integrityMode: 0,
|
||||||
|
authenticatedSafe,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await pfx.makeInternalValues({
|
||||||
|
password: passwordBuf,
|
||||||
|
iterations: 100_000,
|
||||||
|
pbkdf2HashAlgorithm: 'SHA-256',
|
||||||
|
hmacHashAlgorithm: 'SHA-256',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Step 4: Serialize to DER
|
||||||
|
return pfx.toSchema().toBER(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Trigger a browser download of the PKCS#12 file. */
|
||||||
|
export function downloadPkcs12(p12Bytes: ArrayBuffer, filename: string): void {
|
||||||
|
const blob = new Blob([p12Bytes], { type: 'application/x-pkcs12' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = filename;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import {
|
||||||
|
parseCertificateDer,
|
||||||
|
extractCertificateInfo,
|
||||||
|
classifyCapabilities,
|
||||||
|
} from './certificate-utils';
|
||||||
|
import type { SmimeKeyRecord, Pkcs12ImportResult } from './types';
|
||||||
|
import { withLinerEngine } from './crypto-engine';
|
||||||
|
|
||||||
|
const KDF_ITERATIONS = 600_000;
|
||||||
|
const AES_KEY_LENGTH = 256;
|
||||||
|
|
||||||
|
function stringToAB(str: string): ArrayBuffer {
|
||||||
|
const buf = new ArrayBuffer(str.length);
|
||||||
|
const view = new Uint8Array(buf);
|
||||||
|
for (let i = 0; i < str.length; i++) {
|
||||||
|
view[i] = str.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a PKCS#12 (.p12/.pfx) file and produce an encrypted-at-rest key record. */
|
||||||
|
export async function importPkcs12(
|
||||||
|
p12Bytes: ArrayBuffer,
|
||||||
|
p12Passphrase: string,
|
||||||
|
storagePassphrase: string,
|
||||||
|
): Promise<Pkcs12ImportResult> {
|
||||||
|
// Parse PKCS#12 container
|
||||||
|
const asn1 = asn1js.fromBER(p12Bytes);
|
||||||
|
if (asn1.offset === -1) {
|
||||||
|
throw new Error('Invalid PKCS#12 file: ASN.1 parsing failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const pfx = new pkijs.PFX({ schema: asn1.result });
|
||||||
|
|
||||||
|
// Verify MAC if present
|
||||||
|
if (pfx.macData) {
|
||||||
|
const macOk = await pfx.parsedValue?.integrityMode === undefined || true;
|
||||||
|
// PKIjs handles MAC verification internally during parseInternalValues
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use webcrypto-liner as the global engine for 3DES support.
|
||||||
|
// Many PKCS#12 files use pbeWithSHAAnd3-KeyTripleDES-CBC internally.
|
||||||
|
await withLinerEngine(async () => {
|
||||||
|
await pfx.parseInternalValues({
|
||||||
|
password: stringToAB(p12Passphrase),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Extract certificates and private key from parsed PKCS#12
|
||||||
|
let leafCertDer: ArrayBuffer | null = null;
|
||||||
|
let leafCert: pkijs.Certificate | null = null;
|
||||||
|
const chainCertsDer: ArrayBuffer[] = [];
|
||||||
|
let privateKeyInfo: pkijs.PrivateKeyInfo | null = null;
|
||||||
|
|
||||||
|
if (!pfx.parsedValue?.authenticatedSafe) {
|
||||||
|
throw new Error('PKCS#12 file does not contain an authenticated safe');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the authenticated safe contents (inner SafeContents)
|
||||||
|
const authSafe = pfx.parsedValue.authenticatedSafe;
|
||||||
|
const safeContentsParams = authSafe.safeContents.map((ci: pkijs.ContentInfo) => {
|
||||||
|
// encryptedData (1.2.840.113549.1.7.6) needs the password
|
||||||
|
if (ci.contentType === '1.2.840.113549.1.7.6') {
|
||||||
|
return { password: stringToAB(p12Passphrase) };
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
await withLinerEngine(async () => {
|
||||||
|
await authSafe.parseInternalValues({ safeContents: safeContentsParams });
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const safeContent of authSafe.parsedValue.safeContents) {
|
||||||
|
const sc = safeContent.value ?? safeContent.parsedValue;
|
||||||
|
if (!sc) continue;
|
||||||
|
|
||||||
|
for (const safeBag of sc.safeBags) {
|
||||||
|
// PKCS#12 bag types
|
||||||
|
switch (safeBag.bagId) {
|
||||||
|
case '1.2.840.113549.1.12.10.1.3': {
|
||||||
|
// CertBag
|
||||||
|
const certBag = safeBag.bagValue as pkijs.CertBag;
|
||||||
|
|
||||||
|
// parsedValue may already be a Certificate (built in-memory)
|
||||||
|
let cert: pkijs.Certificate | null = null;
|
||||||
|
let der: ArrayBuffer | null = null;
|
||||||
|
|
||||||
|
if (certBag.parsedValue instanceof pkijs.Certificate) {
|
||||||
|
cert = certBag.parsedValue;
|
||||||
|
der = cert.toSchema(true).toBER(false);
|
||||||
|
} else if (certBag.certId === '1.2.840.113549.1.9.22.1' && certBag.certValue) {
|
||||||
|
// x509Certificate — extract DER from the OCTET STRING
|
||||||
|
const certDerBytes = (certBag.certValue as asn1js.OctetString).valueBlock.valueHexView;
|
||||||
|
const certAsn1 = asn1js.fromBER(certDerBytes);
|
||||||
|
if (certAsn1.offset !== -1) {
|
||||||
|
cert = new pkijs.Certificate({ schema: certAsn1.result });
|
||||||
|
der = new Uint8Array(certDerBytes).buffer as ArrayBuffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cert && der) {
|
||||||
|
if (!leafCertDer) {
|
||||||
|
leafCertDer = der;
|
||||||
|
leafCert = cert;
|
||||||
|
} else {
|
||||||
|
chainCertsDer.push(der);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '1.2.840.113549.1.12.10.1.1': {
|
||||||
|
// KeyBag (unencrypted private key)
|
||||||
|
privateKeyInfo = safeBag.bagValue as pkijs.PrivateKeyInfo;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '1.2.840.113549.1.12.10.1.2': {
|
||||||
|
// PKCS8ShroudedKeyBag (encrypted private key)
|
||||||
|
const shroudedBag = safeBag.bagValue as pkijs.PKCS8ShroudedKeyBag;
|
||||||
|
if (shroudedBag.parsedValue) {
|
||||||
|
privateKeyInfo = shroudedBag.parsedValue;
|
||||||
|
} else {
|
||||||
|
// Decrypt shrouded key bag to get private key info
|
||||||
|
await withLinerEngine(async () => {
|
||||||
|
await (shroudedBag as unknown as { parseInternalValues(params: { password: ArrayBuffer }): Promise<void> }).parseInternalValues({
|
||||||
|
password: stringToAB(p12Passphrase),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (shroudedBag.parsedValue) {
|
||||||
|
privateKeyInfo = shroudedBag.parsedValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!leafCert || !leafCertDer) {
|
||||||
|
throw new Error('No certificate found in PKCS#12 file');
|
||||||
|
}
|
||||||
|
if (!privateKeyInfo) {
|
||||||
|
throw new Error('No private key found in PKCS#12 file');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract PKCS#8 private key bytes
|
||||||
|
const pkcs8Bytes = privateKeyInfo.toSchema().toBER(false);
|
||||||
|
|
||||||
|
// Encrypt the private key for at-rest storage
|
||||||
|
const { encrypted, salt, iv } = await encryptPrivateKey(pkcs8Bytes, storagePassphrase);
|
||||||
|
|
||||||
|
// Extract certificate metadata
|
||||||
|
const certInfo = await extractCertificateInfo(leafCert, leafCertDer);
|
||||||
|
const capabilities = classifyCapabilities(leafCert);
|
||||||
|
|
||||||
|
const email = certInfo.emailAddresses[0] ?? '';
|
||||||
|
|
||||||
|
const keyRecord: SmimeKeyRecord = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
email: email.toLowerCase(),
|
||||||
|
certificate: leafCertDer,
|
||||||
|
certificateChain: chainCertsDer,
|
||||||
|
encryptedPrivateKey: encrypted,
|
||||||
|
salt,
|
||||||
|
iv,
|
||||||
|
kdfIterations: KDF_ITERATIONS,
|
||||||
|
issuer: certInfo.issuer,
|
||||||
|
subject: certInfo.subject,
|
||||||
|
serialNumber: certInfo.serialNumber,
|
||||||
|
notBefore: certInfo.notBefore,
|
||||||
|
notAfter: certInfo.notAfter,
|
||||||
|
fingerprint: certInfo.fingerprint,
|
||||||
|
algorithm: certInfo.algorithm,
|
||||||
|
capabilities,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { keyRecord, certInfo };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Private key encryption / decryption ──────────────────────────────
|
||||||
|
|
||||||
|
async function deriveWrappingKey(
|
||||||
|
passphrase: string,
|
||||||
|
salt: ArrayBuffer,
|
||||||
|
iterations: number,
|
||||||
|
): Promise<CryptoKey> {
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
const keyMaterial = await crypto.subtle.importKey(
|
||||||
|
'raw',
|
||||||
|
enc.encode(passphrase),
|
||||||
|
'PBKDF2',
|
||||||
|
false,
|
||||||
|
['deriveKey'],
|
||||||
|
);
|
||||||
|
return crypto.subtle.deriveKey(
|
||||||
|
{ name: 'PBKDF2', salt, iterations, hash: 'SHA-256' },
|
||||||
|
keyMaterial,
|
||||||
|
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||||
|
false,
|
||||||
|
['encrypt', 'decrypt'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function encryptPrivateKey(
|
||||||
|
pkcs8Bytes: ArrayBuffer,
|
||||||
|
passphrase: string,
|
||||||
|
): Promise<{ encrypted: ArrayBuffer; salt: ArrayBuffer; iv: ArrayBuffer }> {
|
||||||
|
const salt = crypto.getRandomValues(new Uint8Array(32)).buffer;
|
||||||
|
const iv = crypto.getRandomValues(new Uint8Array(12)).buffer;
|
||||||
|
const wrappingKey = await deriveWrappingKey(passphrase, salt, KDF_ITERATIONS);
|
||||||
|
const encrypted = await crypto.subtle.encrypt(
|
||||||
|
{ name: 'AES-GCM', iv },
|
||||||
|
wrappingKey,
|
||||||
|
pkcs8Bytes,
|
||||||
|
);
|
||||||
|
return { encrypted, salt, iv };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnlockedKeyPair {
|
||||||
|
signingKey: CryptoKey;
|
||||||
|
decryptionKey?: CryptoKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decrypt stored PKCS#8 bytes and import as non-extractable CryptoKeys for signing and decryption. */
|
||||||
|
export async function unlockPrivateKey(
|
||||||
|
record: SmimeKeyRecord,
|
||||||
|
passphrase: string,
|
||||||
|
): Promise<UnlockedKeyPair> {
|
||||||
|
const wrappingKey = await deriveWrappingKey(
|
||||||
|
passphrase,
|
||||||
|
record.salt,
|
||||||
|
record.kdfIterations,
|
||||||
|
);
|
||||||
|
|
||||||
|
let pkcs8Bytes: ArrayBuffer;
|
||||||
|
try {
|
||||||
|
pkcs8Bytes = await crypto.subtle.decrypt(
|
||||||
|
{ name: 'AES-GCM', iv: record.iv },
|
||||||
|
wrappingKey,
|
||||||
|
record.encryptedPrivateKey,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
throw new Error('Incorrect passphrase');
|
||||||
|
}
|
||||||
|
|
||||||
|
const isEcdsa = record.algorithm.startsWith('ECDSA');
|
||||||
|
const signAlg = isEcdsa
|
||||||
|
? { name: 'ECDSA', namedCurve: ecdsaCurveFromAlg(record.algorithm) }
|
||||||
|
: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
|
||||||
|
const decryptAlg = isEcdsa
|
||||||
|
? { name: 'ECDH', namedCurve: ecdsaCurveFromAlg(record.algorithm) }
|
||||||
|
: { name: 'RSA-OAEP', hash: 'SHA-256' };
|
||||||
|
const decryptUsages: globalThis.KeyUsage[] = isEcdsa ? ['deriveBits'] : ['decrypt'];
|
||||||
|
|
||||||
|
// Import for signing
|
||||||
|
let signingKey: CryptoKey;
|
||||||
|
try {
|
||||||
|
signingKey = await crypto.subtle.importKey('pkcs8', pkcs8Bytes, signAlg, false, ['sign']);
|
||||||
|
} catch {
|
||||||
|
// Key may only support decryption (key-encipherment-only cert)
|
||||||
|
const decryptionKey = await crypto.subtle.importKey('pkcs8', pkcs8Bytes, decryptAlg, false, decryptUsages);
|
||||||
|
return { signingKey: decryptionKey, decryptionKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also import for decryption (separate CryptoKey handle required by Web Crypto)
|
||||||
|
let decryptionKey: CryptoKey | undefined;
|
||||||
|
try {
|
||||||
|
decryptionKey = await crypto.subtle.importKey('pkcs8', pkcs8Bytes, decryptAlg, false, decryptUsages);
|
||||||
|
} catch {
|
||||||
|
// Key may only support signing (digitalSignature-only cert)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { signingKey, decryptionKey };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get decrypted PKCS#8 bytes (for export flow). */
|
||||||
|
export async function decryptPrivateKeyBytes(
|
||||||
|
record: SmimeKeyRecord,
|
||||||
|
passphrase: string,
|
||||||
|
): Promise<ArrayBuffer> {
|
||||||
|
const wrappingKey = await deriveWrappingKey(
|
||||||
|
passphrase,
|
||||||
|
record.salt,
|
||||||
|
record.kdfIterations,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await crypto.subtle.decrypt(
|
||||||
|
{ name: 'AES-GCM', iv: record.iv },
|
||||||
|
wrappingKey,
|
||||||
|
record.encryptedPrivateKey,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
throw new Error('Incorrect passphrase');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ecdsaCurveFromAlg(alg: string): string {
|
||||||
|
if (alg.includes('P256') || alg.includes('P-256')) return 'P-256';
|
||||||
|
if (alg.includes('P384') || alg.includes('P-384')) return 'P-384';
|
||||||
|
if (alg.includes('P521') || alg.includes('P-521')) return 'P-521';
|
||||||
|
return 'P-256';
|
||||||
|
}
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
/**
|
||||||
|
* Decrypt CMS EnvelopedData to recover the inner MIME content.
|
||||||
|
*
|
||||||
|
* Supports both issuerAndSerialNumber and subjectKeyIdentifier
|
||||||
|
* recipient identifier types per RFC 8551.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import type { SmimeKeyRecord } from './types';
|
||||||
|
import { getLinerCryptoEngine } from './crypto-engine';
|
||||||
|
|
||||||
|
export interface DecryptionInput {
|
||||||
|
/** Raw CMS EnvelopedData bytes (DER) */
|
||||||
|
cmsBytes: ArrayBuffer;
|
||||||
|
/** All imported key records to try matching against */
|
||||||
|
keyRecords: SmimeKeyRecord[];
|
||||||
|
/** Unlocked CryptoKey map: keyRecordId → CryptoKey */
|
||||||
|
unlockedKeys: Map<string, CryptoKey>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DecryptionResult {
|
||||||
|
/** The decrypted inner MIME bytes */
|
||||||
|
mimeBytes: Uint8Array;
|
||||||
|
/** The key record that was used to decrypt */
|
||||||
|
keyRecordId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempt to decrypt CMS EnvelopedData.
|
||||||
|
*
|
||||||
|
* Tries each matching key record against the recipient infos in the CMS structure.
|
||||||
|
*
|
||||||
|
* @throws Error if no matching key is found, key is locked, or decryption fails
|
||||||
|
*/
|
||||||
|
export async function smimeDecrypt(input: DecryptionInput): Promise<DecryptionResult> {
|
||||||
|
const { cmsBytes, keyRecords, unlockedKeys } = input;
|
||||||
|
|
||||||
|
// Parse the CMS ContentInfo wrapper
|
||||||
|
const contentInfo = parseContentInfo(cmsBytes);
|
||||||
|
const envelopedData = extractEnvelopedData(contentInfo);
|
||||||
|
|
||||||
|
// Find matching key records
|
||||||
|
const matchedRecords = findMatchingKeyRecords(envelopedData, keyRecords);
|
||||||
|
|
||||||
|
if (matchedRecords.length === 0) {
|
||||||
|
throw new Error('No imported S/MIME key matches any recipient in this encrypted message');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try each matched record
|
||||||
|
for (const { keyRecord, recipientIndex } of matchedRecords) {
|
||||||
|
const privateKey = unlockedKeys.get(keyRecord.id);
|
||||||
|
if (!privateKey) {
|
||||||
|
continue; // Key exists but isn't unlocked — skip, caller should unlock first
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decrypted = await decryptWithKey(envelopedData, recipientIndex, privateKey, keyRecord);
|
||||||
|
return {
|
||||||
|
mimeBytes: new Uint8Array(decrypted),
|
||||||
|
keyRecordId: keyRecord.id,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
// This key didn't work, try the next one
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we had matching records but none were unlocked
|
||||||
|
const hasLockedMatch = matchedRecords.some(m => !unlockedKeys.has(m.keyRecord.id));
|
||||||
|
if (hasLockedMatch) {
|
||||||
|
const lockedRecord = matchedRecords.find(m => !unlockedKeys.has(m.keyRecord.id))!;
|
||||||
|
throw new SmimeKeyLockedError(
|
||||||
|
'S/MIME key is locked. Unlock it to decrypt this message.',
|
||||||
|
lockedRecord.keyRecord.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Failed to decrypt message with any available key');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the key record IDs that could potentially decrypt a message.
|
||||||
|
* Useful for prompting the user to unlock the right key.
|
||||||
|
*/
|
||||||
|
export function findDecryptionCandidates(
|
||||||
|
cmsBytes: ArrayBuffer,
|
||||||
|
keyRecords: SmimeKeyRecord[],
|
||||||
|
): string[] {
|
||||||
|
try {
|
||||||
|
const contentInfo = parseContentInfo(cmsBytes);
|
||||||
|
const envelopedData = extractEnvelopedData(contentInfo);
|
||||||
|
const matches = findMatchingKeyRecords(envelopedData, keyRecords);
|
||||||
|
return matches.map(m => m.keyRecord.id);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SmimeKeyLockedError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public readonly keyRecordId: string,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'SmimeKeyLockedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Internal helpers ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize raw blob bytes into DER-encoded CMS data.
|
||||||
|
*
|
||||||
|
* JMAP servers may return the CMS blob in various formats:
|
||||||
|
* - Raw DER binary (starts with 0x30 ASN.1 SEQUENCE tag)
|
||||||
|
* - Base64-encoded DER
|
||||||
|
* - Full MIME part with headers followed by base64 body
|
||||||
|
* - PEM-wrapped (-----BEGIN PKCS7-----)
|
||||||
|
*
|
||||||
|
* This function detects the format and returns raw DER bytes.
|
||||||
|
*/
|
||||||
|
export function normalizeCmsBytes(raw: ArrayBuffer): ArrayBuffer {
|
||||||
|
if (raw.byteLength === 0) {
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes = new Uint8Array(raw);
|
||||||
|
|
||||||
|
// Already valid DER — starts with ASN.1 SEQUENCE tag
|
||||||
|
if (bytes[0] === 0x30) {
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
let text = new TextDecoder().decode(raw);
|
||||||
|
|
||||||
|
const looksMostlyText = (() => {
|
||||||
|
const sample = text.slice(0, Math.min(text.length, 2048));
|
||||||
|
if (sample.length === 0) return false;
|
||||||
|
let printable = 0;
|
||||||
|
for (let i = 0; i < sample.length; i++) {
|
||||||
|
const code = sample.charCodeAt(i);
|
||||||
|
if (
|
||||||
|
code === 0x09 ||
|
||||||
|
code === 0x0a ||
|
||||||
|
code === 0x0d ||
|
||||||
|
(code >= 0x20 && code <= 0x7e)
|
||||||
|
) {
|
||||||
|
printable++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return printable / sample.length > 0.85;
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Check if the blob contains MIME headers (e.g., server returned full part
|
||||||
|
// including Content-Transfer-Encoding header)
|
||||||
|
const headerEndMatch = text.match(/\r?\n\r?\n/);
|
||||||
|
const hasMimeHeaderHints = /content-type:|content-transfer-encoding:|mime-version:/i.test(text.slice(0, Math.min(text.length, 8192)));
|
||||||
|
if (looksMostlyText && headerEndMatch && headerEndMatch.index !== undefined && hasMimeHeaderHints) {
|
||||||
|
// Strip everything before the blank line separating headers from body
|
||||||
|
text = text.substring(headerEndMatch.index + headerEndMatch[0].length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip PEM armour if present
|
||||||
|
text = text
|
||||||
|
.replace(/-----BEGIN [A-Z0-9 ]+-----/g, '')
|
||||||
|
.replace(/-----END [A-Z0-9 ]+-----/g, '');
|
||||||
|
|
||||||
|
// Remove all whitespace and try base64 decode
|
||||||
|
text = text.replace(/\s/g, '');
|
||||||
|
|
||||||
|
if (text.length === 0) {
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const binary = atob(text);
|
||||||
|
const decoded = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) decoded[i] = binary.charCodeAt(i);
|
||||||
|
if (decoded.length > 0 && decoded[0] === 0x30) {
|
||||||
|
return decoded.buffer as ArrayBuffer;
|
||||||
|
}
|
||||||
|
} catch { /* non-DER data, continue to fallback */ }
|
||||||
|
|
||||||
|
// Fallback: parse explicit MIME base64 sections
|
||||||
|
if (looksMostlyText) {
|
||||||
|
const originalText = new TextDecoder().decode(raw);
|
||||||
|
const sectionRegex = /content-transfer-encoding:\s*base64[\s\S]*?\r?\n\r?\n([\s\S]*?)(?:\r?\n--[^\r\n]+|$)/ig;
|
||||||
|
const sectionBlocks: string[] = [];
|
||||||
|
let sectionMatch: RegExpExecArray | null = null;
|
||||||
|
while ((sectionMatch = sectionRegex.exec(originalText)) !== null) {
|
||||||
|
sectionBlocks.push(sectionMatch[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const block of sectionBlocks) {
|
||||||
|
const cleaned = block.replace(/\s/g, '');
|
||||||
|
if (cleaned.length < 8 || !/^[A-Za-z0-9+/=]+$/.test(cleaned)) continue;
|
||||||
|
try {
|
||||||
|
const binary = atob(cleaned);
|
||||||
|
const decoded = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) decoded[i] = binary.charCodeAt(i);
|
||||||
|
if (decoded.length > 0 && decoded[0] === 0x30) {
|
||||||
|
return decoded.buffer as ArrayBuffer;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// try next section
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Last resort: find base64-like blocks and keep only DER-looking decodes
|
||||||
|
const base64Blocks = originalText.match(/[A-Za-z0-9+/=\r\n]{128,}/g) || [];
|
||||||
|
const cleaned = base64Blocks
|
||||||
|
.map(block => block.replace(/\s/g, ''))
|
||||||
|
.filter(block => block.length >= 128 && /^[A-Za-z0-9+/=]+$/.test(block));
|
||||||
|
|
||||||
|
cleaned.sort((a, b) => b.length - a.length);
|
||||||
|
|
||||||
|
for (const block of cleaned) {
|
||||||
|
try {
|
||||||
|
const binary = atob(block);
|
||||||
|
const decoded = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) decoded[i] = binary.charCodeAt(i);
|
||||||
|
if (decoded.length > 0 && decoded[0] === 0x30) {
|
||||||
|
return decoded.buffer as ArrayBuffer;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// try next block
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not decodable — return original bytes
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseContentInfo(der: ArrayBuffer): pkijs.ContentInfo {
|
||||||
|
const asn1 = asn1js.fromBER(der);
|
||||||
|
if (asn1.offset === -1) {
|
||||||
|
throw new Error('Invalid ASN.1 data — cannot parse CMS envelope');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return new pkijs.ContentInfo({ schema: asn1.result });
|
||||||
|
} catch {
|
||||||
|
throw new Error('Invalid ASN.1 data — cannot parse CMS envelope');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractEnvelopedData(contentInfo: pkijs.ContentInfo): pkijs.EnvelopedData {
|
||||||
|
// OID 1.2.840.113549.1.7.3 = enveloped-data
|
||||||
|
if (contentInfo.contentType !== '1.2.840.113549.1.7.3') {
|
||||||
|
throw new Error(`Unexpected CMS content type: ${contentInfo.contentType}`);
|
||||||
|
}
|
||||||
|
return new pkijs.EnvelopedData({ schema: contentInfo.content });
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RecipientMatch {
|
||||||
|
keyRecord: SmimeKeyRecord;
|
||||||
|
recipientIndex: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMatchingKeyRecords(
|
||||||
|
envelopedData: pkijs.EnvelopedData,
|
||||||
|
keyRecords: SmimeKeyRecord[],
|
||||||
|
): RecipientMatch[] {
|
||||||
|
const matches: RecipientMatch[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < envelopedData.recipientInfos.length; i++) {
|
||||||
|
const ri = envelopedData.recipientInfos[i];
|
||||||
|
|
||||||
|
// RecipientInfo is a wrapper: variant=1 → KeyTransRecipientInfo
|
||||||
|
const ktri = ri instanceof pkijs.KeyTransRecipientInfo
|
||||||
|
? ri
|
||||||
|
: (ri as { variant?: number; value?: unknown }).variant === 1 && (ri as { value?: unknown }).value instanceof pkijs.KeyTransRecipientInfo
|
||||||
|
? (ri as { value: pkijs.KeyTransRecipientInfo }).value
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (ktri) {
|
||||||
|
for (const keyRecord of keyRecords) {
|
||||||
|
if (matchesKeyTransRecipient(ktri, keyRecord)) {
|
||||||
|
matches.push({ keyRecord, recipientIndex: i });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchesKeyTransRecipient(
|
||||||
|
recipientInfo: pkijs.KeyTransRecipientInfo,
|
||||||
|
keyRecord: SmimeKeyRecord,
|
||||||
|
): boolean {
|
||||||
|
const rid = recipientInfo.rid;
|
||||||
|
|
||||||
|
// IssuerAndSerialNumber matching
|
||||||
|
if (rid instanceof pkijs.IssuerAndSerialNumber) {
|
||||||
|
try {
|
||||||
|
const certAsn1 = asn1js.fromBER(keyRecord.certificate);
|
||||||
|
if (certAsn1.offset === -1) return false;
|
||||||
|
const cert = new pkijs.Certificate({ schema: certAsn1.result });
|
||||||
|
|
||||||
|
// Compare serial numbers
|
||||||
|
const ridSerial = Buffer.from(rid.serialNumber.valueBlock.valueHexView).toString('hex');
|
||||||
|
const certSerial = Buffer.from(cert.serialNumber.valueBlock.valueHexView).toString('hex');
|
||||||
|
if (ridSerial !== certSerial) return false;
|
||||||
|
|
||||||
|
// Compare issuers (compare DER encoding)
|
||||||
|
const ridIssuerDer = rid.issuer.toSchema().toBER(false);
|
||||||
|
const certIssuerDer = cert.issuer.toSchema().toBER(false);
|
||||||
|
return arraysEqual(new Uint8Array(ridIssuerDer), new Uint8Array(certIssuerDer));
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubjectKeyIdentifier matching
|
||||||
|
if (rid instanceof asn1js.OctetString) {
|
||||||
|
try {
|
||||||
|
const certAsn1 = asn1js.fromBER(keyRecord.certificate);
|
||||||
|
if (certAsn1.offset === -1) return false;
|
||||||
|
const cert = new pkijs.Certificate({ schema: certAsn1.result });
|
||||||
|
|
||||||
|
// Find the SubjectKeyIdentifier extension
|
||||||
|
const skiExt = cert.extensions?.find(
|
||||||
|
ext => ext.extnID === '2.5.29.14', // id-ce-subjectKeyIdentifier
|
||||||
|
);
|
||||||
|
if (!skiExt) return false;
|
||||||
|
|
||||||
|
const skiValue = asn1js.fromBER(skiExt.extnValue.valueBlock.valueHexView);
|
||||||
|
if (skiValue.offset === -1) return false;
|
||||||
|
const ski = (skiValue.result as asn1js.OctetString).valueBlock.valueHexView;
|
||||||
|
|
||||||
|
return arraysEqual(
|
||||||
|
new Uint8Array(ski),
|
||||||
|
new Uint8Array(rid.valueBlock.valueHexView),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function arraysEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
if (a[i] !== b[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decryptWithKey(
|
||||||
|
envelopedData: pkijs.EnvelopedData,
|
||||||
|
recipientIndex: number,
|
||||||
|
privateKey: CryptoKey,
|
||||||
|
keyRecord: SmimeKeyRecord,
|
||||||
|
): Promise<ArrayBuffer> {
|
||||||
|
// Parse the certificate for pkijs
|
||||||
|
const certAsn1 = asn1js.fromBER(keyRecord.certificate);
|
||||||
|
const cert = new pkijs.Certificate({ schema: certAsn1.result });
|
||||||
|
|
||||||
|
// Use webcrypto-liner engine for legacy algorithm support (e.g. 3DES)
|
||||||
|
const cryptoEngine = getLinerCryptoEngine();
|
||||||
|
|
||||||
|
const result = await envelopedData.decrypt(
|
||||||
|
recipientIndex,
|
||||||
|
{
|
||||||
|
recipientCertificate: cert,
|
||||||
|
recipientPrivateKey: privateKey,
|
||||||
|
},
|
||||||
|
cryptoEngine,
|
||||||
|
);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
/**
|
||||||
|
* Detect S/MIME content in an email message.
|
||||||
|
*
|
||||||
|
* Checks Content-Type headers, bodyStructure, and attachment metadata
|
||||||
|
* to determine if a message contains CMS signed or encrypted content.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type SmimeContentType =
|
||||||
|
| 'enveloped-data' // encrypted
|
||||||
|
| 'signed-data' // opaque signed
|
||||||
|
| 'detached-sig' // multipart/signed (deferred in v1)
|
||||||
|
| null;
|
||||||
|
|
||||||
|
export interface SmimeDetectionResult {
|
||||||
|
/** Primary S/MIME content type detected, or null if none */
|
||||||
|
type: SmimeContentType;
|
||||||
|
/** The blobId to fetch for CMS processing (enveloped-data or signed-data) */
|
||||||
|
blobId?: string;
|
||||||
|
/** The partId containing the CMS data */
|
||||||
|
partId?: string;
|
||||||
|
/** Whether this is a v1-supported type */
|
||||||
|
supported: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EmailBodyPart {
|
||||||
|
partId?: string;
|
||||||
|
blobId?: string;
|
||||||
|
type?: string;
|
||||||
|
name?: string;
|
||||||
|
disposition?: string;
|
||||||
|
subParts?: EmailBodyPart[];
|
||||||
|
headers?: Array<{ name: string; value: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect S/MIME content from email metadata.
|
||||||
|
*
|
||||||
|
* @param contentType - The top-level Content-Type header value
|
||||||
|
* @param bodyStructure - The JMAP bodyStructure tree
|
||||||
|
* @param attachments - Flat list of attachment parts (from `attachments` property)
|
||||||
|
*/
|
||||||
|
export function detectSmime(
|
||||||
|
contentType?: string,
|
||||||
|
bodyStructure?: EmailBodyPart | null,
|
||||||
|
attachments?: EmailBodyPart[],
|
||||||
|
): SmimeDetectionResult {
|
||||||
|
const noResult: SmimeDetectionResult = { type: null, supported: false };
|
||||||
|
|
||||||
|
// 1. Check top-level Content-Type header
|
||||||
|
if (contentType) {
|
||||||
|
const ct = contentType.toLowerCase();
|
||||||
|
|
||||||
|
if (ct.includes('application/pkcs7-mime') || ct.includes('application/x-pkcs7-mime')) {
|
||||||
|
if (ct.includes('smime-type=enveloped-data')) {
|
||||||
|
const part = findCmsPart(bodyStructure, 'enveloped-data');
|
||||||
|
return {
|
||||||
|
type: 'enveloped-data',
|
||||||
|
blobId: part?.blobId,
|
||||||
|
partId: part?.partId,
|
||||||
|
supported: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (ct.includes('smime-type=signed-data')) {
|
||||||
|
const part = findCmsPart(bodyStructure, 'signed-data');
|
||||||
|
return {
|
||||||
|
type: 'signed-data',
|
||||||
|
blobId: part?.blobId,
|
||||||
|
partId: part?.partId,
|
||||||
|
supported: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Generic pkcs7-mime without explicit smime-type — try bodyStructure
|
||||||
|
const part = findCmsPart(bodyStructure, null);
|
||||||
|
if (part) {
|
||||||
|
const partType = inferSmimeType(part);
|
||||||
|
return {
|
||||||
|
type: partType,
|
||||||
|
blobId: part.blobId,
|
||||||
|
partId: part.partId,
|
||||||
|
supported: partType === 'enveloped-data' || partType === 'signed-data',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ct.includes('multipart/signed') && ct.includes('application/pkcs7-signature')) {
|
||||||
|
return { type: 'detached-sig', supported: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Walk bodyStructure tree
|
||||||
|
if (bodyStructure) {
|
||||||
|
const result = walkBodyStructure(bodyStructure);
|
||||||
|
if (result) return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Check attachment list for .p7m files
|
||||||
|
if (attachments) {
|
||||||
|
for (const att of attachments) {
|
||||||
|
const type = att.type?.toLowerCase() || '';
|
||||||
|
const name = att.name?.toLowerCase() || '';
|
||||||
|
|
||||||
|
if (type.includes('application/pkcs7-mime') || type.includes('application/x-pkcs7-mime')) {
|
||||||
|
const smimeType = inferSmimeTypeFromContentType(type);
|
||||||
|
return {
|
||||||
|
type: smimeType,
|
||||||
|
blobId: att.blobId,
|
||||||
|
partId: att.partId,
|
||||||
|
supported: smimeType === 'enveloped-data' || smimeType === 'signed-data',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name.endsWith('.p7m')) {
|
||||||
|
return {
|
||||||
|
type: 'enveloped-data', // .p7m is ambiguous but commonly encrypted
|
||||||
|
blobId: att.blobId,
|
||||||
|
partId: att.partId,
|
||||||
|
supported: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name.endsWith('.p7s')) {
|
||||||
|
return { type: 'detached-sig', blobId: att.blobId, partId: att.partId, supported: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return noResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
function walkBodyStructure(part: EmailBodyPart): SmimeDetectionResult | null {
|
||||||
|
const type = part.type?.toLowerCase() || '';
|
||||||
|
|
||||||
|
if (type.includes('application/pkcs7-mime') || type.includes('application/x-pkcs7-mime')) {
|
||||||
|
const smimeType = inferSmimeTypeFromContentType(type);
|
||||||
|
return {
|
||||||
|
type: smimeType,
|
||||||
|
blobId: part.blobId,
|
||||||
|
partId: part.partId,
|
||||||
|
supported: smimeType === 'enveloped-data' || smimeType === 'signed-data',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === 'multipart/signed') {
|
||||||
|
// Check for pkcs7-signature protocol in subparts
|
||||||
|
if (part.subParts?.some(sp => sp.type?.toLowerCase().includes('application/pkcs7-signature'))) {
|
||||||
|
return { type: 'detached-sig', supported: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (part.subParts) {
|
||||||
|
for (const sub of part.subParts) {
|
||||||
|
const result = walkBodyStructure(sub);
|
||||||
|
if (result) return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findCmsPart(bodyStructure: EmailBodyPart | null | undefined, smimeType: string | null): EmailBodyPart | null {
|
||||||
|
if (!bodyStructure) return null;
|
||||||
|
|
||||||
|
const type = bodyStructure.type?.toLowerCase() || '';
|
||||||
|
if (type.includes('application/pkcs7-mime') || type.includes('application/x-pkcs7-mime')) {
|
||||||
|
// JMAP bodyStructure.type may not include smime-type parameter,
|
||||||
|
// so accept any pkcs7-mime part when the smime-type was already
|
||||||
|
// determined from the Content-Type header.
|
||||||
|
return bodyStructure;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bodyStructure.subParts) {
|
||||||
|
for (const sub of bodyStructure.subParts) {
|
||||||
|
const found = findCmsPart(sub, smimeType);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function inferSmimeType(part: EmailBodyPart): SmimeContentType {
|
||||||
|
return inferSmimeTypeFromContentType(part.type || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function inferSmimeTypeFromContentType(ct: string): SmimeContentType {
|
||||||
|
const lower = ct.toLowerCase();
|
||||||
|
if (lower.includes('smime-type=enveloped-data')) return 'enveloped-data';
|
||||||
|
if (lower.includes('smime-type=signed-data')) return 'signed-data';
|
||||||
|
// Default for generic pkcs7-mime: assume enveloped-data (most common)
|
||||||
|
if (lower.includes('application/pkcs7-mime') || lower.includes('application/x-pkcs7-mime')) {
|
||||||
|
return 'enveloped-data';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import { parseCertificateDer } from './certificate-utils';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Produce CMS EnvelopedData for the given MIME content.
|
||||||
|
*
|
||||||
|
* Content type: application/pkcs7-mime; smime-type=enveloped-data
|
||||||
|
*
|
||||||
|
* Always includes the sender's cert so the sender can decrypt their Sent mail.
|
||||||
|
*/
|
||||||
|
export async function smimeEncrypt(
|
||||||
|
mimeBytes: Uint8Array,
|
||||||
|
recipientCertsDer: ArrayBuffer[],
|
||||||
|
senderCertDer: ArrayBuffer,
|
||||||
|
useAes128?: boolean,
|
||||||
|
): Promise<Blob> {
|
||||||
|
// Combine recipient + sender certs, deduplicate by DER bytes
|
||||||
|
const allCertDers = deduplicateCerts([...recipientCertsDer, senderCertDer]);
|
||||||
|
|
||||||
|
if (allCertDers.length === 0) {
|
||||||
|
throw new Error('No recipient certificates provided');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse all certificates
|
||||||
|
const recipientCerts = allCertDers.map((der) => parseCertificateDer(der));
|
||||||
|
|
||||||
|
// Build EnvelopedData
|
||||||
|
const cmsEnveloped = new pkijs.EnvelopedData();
|
||||||
|
|
||||||
|
// Add recipient info for each certificate
|
||||||
|
for (const cert of recipientCerts) {
|
||||||
|
cmsEnveloped.addRecipientByCertificate(cert, {
|
||||||
|
oaepHashAlgorithm: 'SHA-256',
|
||||||
|
}, undefined, new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encrypt the content
|
||||||
|
const contentEncryptionAlgorithm = useAes128
|
||||||
|
? { name: 'AES-GCM', length: 128 }
|
||||||
|
: { name: 'AES-GCM', length: 256 };
|
||||||
|
|
||||||
|
await cmsEnveloped.encrypt(contentEncryptionAlgorithm, mimeBytes.buffer.slice(mimeBytes.byteOffset, mimeBytes.byteOffset + mimeBytes.byteLength) as ArrayBuffer, new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Wrap in ContentInfo
|
||||||
|
const cms = new pkijs.ContentInfo({
|
||||||
|
contentType: '1.2.840.113549.1.7.3', // id-envelopedData
|
||||||
|
content: cmsEnveloped.toSchema(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmsBytes = cms.toSchema().toBER(false);
|
||||||
|
return new Blob([cmsBytes], { type: 'application/pkcs7-mime; smime-type=enveloped-data' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove duplicate DER-encoded certificates based on byte equality. */
|
||||||
|
function deduplicateCerts(certs: ArrayBuffer[]): ArrayBuffer[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const result: ArrayBuffer[] = [];
|
||||||
|
for (const cert of certs) {
|
||||||
|
const key = arrayBufferToHex(cert);
|
||||||
|
if (!seen.has(key)) {
|
||||||
|
seen.add(key);
|
||||||
|
result.push(cert);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function arrayBufferToHex(buf: ArrayBuffer): string {
|
||||||
|
return Array.from(new Uint8Array(buf))
|
||||||
|
.map((b) => b.toString(16).padStart(2, '0'))
|
||||||
|
.join('');
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import { Convert } from 'pvtsutils';
|
||||||
|
import { parseCertificateDer } from './certificate-utils';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Produce an opaque CMS SignedData wrapping the given MIME content.
|
||||||
|
*
|
||||||
|
* Content type: application/pkcs7-mime; smime-type=signed-data
|
||||||
|
* This is the "opaque" form — the content is embedded inside the CMS structure.
|
||||||
|
*/
|
||||||
|
export async function smimeSign(
|
||||||
|
mimeBytes: Uint8Array,
|
||||||
|
privateKey: CryptoKey,
|
||||||
|
signerCertDer: ArrayBuffer,
|
||||||
|
chainCertsDer: ArrayBuffer[] = [],
|
||||||
|
): Promise<Blob> {
|
||||||
|
// Parse signer certificate
|
||||||
|
const signerCert = parseCertificateDer(signerCertDer);
|
||||||
|
|
||||||
|
// Parse chain certificates
|
||||||
|
const chainCerts = chainCertsDer.map((der) => parseCertificateDer(der));
|
||||||
|
|
||||||
|
// Build CMS SignedData
|
||||||
|
const cmsSigned = new pkijs.SignedData({
|
||||||
|
version: 1,
|
||||||
|
encapContentInfo: new pkijs.EncapsulatedContentInfo({
|
||||||
|
eContentType: '1.2.840.113549.1.7.1', // id-data
|
||||||
|
eContent: new asn1js.OctetString({ valueHex: new Uint8Array(mimeBytes.buffer.slice(mimeBytes.byteOffset, mimeBytes.byteOffset + mimeBytes.byteLength)) }),
|
||||||
|
}),
|
||||||
|
signerInfos: [
|
||||||
|
new pkijs.SignerInfo({
|
||||||
|
version: 1,
|
||||||
|
sid: new pkijs.IssuerAndSerialNumber({
|
||||||
|
issuer: signerCert.issuer,
|
||||||
|
serialNumber: signerCert.serialNumber,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
certificates: [signerCert, ...chainCerts],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Determine signing algorithm from the key
|
||||||
|
const algorithm = privateKey.algorithm;
|
||||||
|
const hashAlgorithm = 'SHA-256';
|
||||||
|
|
||||||
|
let signAlg: string;
|
||||||
|
if (algorithm.name === 'RSASSA-PKCS1-v1_5' || algorithm.name === 'RSA-PSS') {
|
||||||
|
signAlg = algorithm.name;
|
||||||
|
} else if (algorithm.name === 'ECDSA') {
|
||||||
|
signAlg = 'ECDSA';
|
||||||
|
} else {
|
||||||
|
signAlg = 'RSASSA-PKCS1-v1_5';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sign
|
||||||
|
await cmsSigned.sign(privateKey, 0, hashAlgorithm, undefined, new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Wrap in ContentInfo
|
||||||
|
const cms = new pkijs.ContentInfo({
|
||||||
|
contentType: '1.2.840.113549.1.7.2', // id-signedData
|
||||||
|
content: cmsSigned.toSchema(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmsBytes = cms.toSchema().toBER(false);
|
||||||
|
return new Blob([cmsBytes], { type: 'application/pkcs7-mime; smime-type=signed-data' });
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
/**
|
||||||
|
* Verify CMS SignedData (opaque signed) and extract the inner content.
|
||||||
|
*
|
||||||
|
* v1 performs cryptographic signature validation and cert validity checks
|
||||||
|
* but does NOT implement full trust-chain or revocation validation.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as pkijs from 'pkijs';
|
||||||
|
import * as asn1js from 'asn1js';
|
||||||
|
import { extractCertificateInfo } from './certificate-utils';
|
||||||
|
import type { SmimeStatus, SmimePublicCert } from './types';
|
||||||
|
|
||||||
|
export interface VerificationResult {
|
||||||
|
/** The inner MIME bytes extracted from the opaque SignedData */
|
||||||
|
mimeBytes: Uint8Array;
|
||||||
|
/** Full S/MIME status for display */
|
||||||
|
status: SmimeStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a CMS SignedData structure and extract the encapsulated content.
|
||||||
|
*
|
||||||
|
* @param cmsBytes - Raw DER-encoded CMS SignedData
|
||||||
|
* @param fromHeader - The From header email address for signer identity matching
|
||||||
|
*/
|
||||||
|
export async function smimeVerify(
|
||||||
|
cmsBytes: ArrayBuffer,
|
||||||
|
fromHeader?: string,
|
||||||
|
): Promise<VerificationResult> {
|
||||||
|
const contentInfo = parseContentInfo(cmsBytes);
|
||||||
|
const signedData = extractSignedData(contentInfo);
|
||||||
|
|
||||||
|
// Extract inner content
|
||||||
|
const innerContent = extractInnerContent(signedData);
|
||||||
|
|
||||||
|
// Extract signer certificate
|
||||||
|
const signerCert = extractSignerCertificate(signedData);
|
||||||
|
if (!signerCert) {
|
||||||
|
return {
|
||||||
|
mimeBytes: innerContent,
|
||||||
|
status: {
|
||||||
|
isSigned: true,
|
||||||
|
isEncrypted: false,
|
||||||
|
signatureValid: false,
|
||||||
|
signatureError: 'Signer certificate not found in CMS structure',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the signature cryptographically
|
||||||
|
let signatureValid = false;
|
||||||
|
let signatureError: string | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const cryptoEngine = new pkijs.CryptoEngine({
|
||||||
|
crypto: crypto,
|
||||||
|
subtle: crypto.subtle,
|
||||||
|
name: 'webcrypto',
|
||||||
|
});
|
||||||
|
|
||||||
|
const verifyResult = await signedData.verify(
|
||||||
|
{
|
||||||
|
signer: 0,
|
||||||
|
checkChain: false, // v1: no trust-chain validation
|
||||||
|
},
|
||||||
|
cryptoEngine,
|
||||||
|
);
|
||||||
|
signatureValid = verifyResult;
|
||||||
|
} catch (err) {
|
||||||
|
signatureError = err instanceof Error ? err.message : 'Signature verification failed';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract certificate info for display
|
||||||
|
const certDer = signerCert.toSchema(true).toBER(false);
|
||||||
|
const certInfo = await extractCertificateInfo(signerCert, certDer);
|
||||||
|
|
||||||
|
// Check certificate validity period
|
||||||
|
const now = new Date();
|
||||||
|
const notBefore = new Date(certInfo.notBefore);
|
||||||
|
const notAfter = new Date(certInfo.notAfter);
|
||||||
|
const certExpired = now > notAfter;
|
||||||
|
const certNotYetValid = now < notBefore;
|
||||||
|
|
||||||
|
if (certExpired && !signatureError) {
|
||||||
|
signatureError = 'Signer certificate has expired';
|
||||||
|
}
|
||||||
|
if (certNotYetValid && !signatureError) {
|
||||||
|
signatureError = 'Signer certificate is not yet valid';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the signer public cert object
|
||||||
|
const signerEmail = certInfo.emailAddresses[0] ?? '';
|
||||||
|
const signerPublicCert: SmimePublicCert = {
|
||||||
|
id: `signer-${certInfo.fingerprint}`,
|
||||||
|
email: signerEmail.toLowerCase(),
|
||||||
|
certificate: certDer,
|
||||||
|
issuer: certInfo.issuer,
|
||||||
|
subject: certInfo.subject,
|
||||||
|
notBefore: certInfo.notBefore,
|
||||||
|
notAfter: certInfo.notAfter,
|
||||||
|
fingerprint: certInfo.fingerprint,
|
||||||
|
source: 'signed-email',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check signer identity vs From header
|
||||||
|
let signerEmailMatch: boolean | undefined;
|
||||||
|
if (fromHeader && signerEmail) {
|
||||||
|
signerEmailMatch = fromHeader.toLowerCase() === signerEmail.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
mimeBytes: innerContent,
|
||||||
|
status: {
|
||||||
|
isSigned: true,
|
||||||
|
isEncrypted: false,
|
||||||
|
signatureValid: signatureValid && !certExpired && !certNotYetValid,
|
||||||
|
signatureError,
|
||||||
|
signerCert: signerPublicCert,
|
||||||
|
signerEmailMatch,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Internal helpers ---
|
||||||
|
|
||||||
|
function parseContentInfo(der: ArrayBuffer): pkijs.ContentInfo {
|
||||||
|
const asn1 = asn1js.fromBER(der);
|
||||||
|
if (asn1.offset === -1) {
|
||||||
|
throw new Error('Invalid ASN.1 data — cannot parse CMS structure');
|
||||||
|
}
|
||||||
|
return new pkijs.ContentInfo({ schema: asn1.result });
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractSignedData(contentInfo: pkijs.ContentInfo): pkijs.SignedData {
|
||||||
|
// OID 1.2.840.113549.1.7.2 = signed-data
|
||||||
|
if (contentInfo.contentType !== '1.2.840.113549.1.7.2') {
|
||||||
|
throw new Error(`Unexpected CMS content type: ${contentInfo.contentType}`);
|
||||||
|
}
|
||||||
|
return new pkijs.SignedData({ schema: contentInfo.content });
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractInnerContent(signedData: pkijs.SignedData): Uint8Array {
|
||||||
|
const eContent = signedData.encapContentInfo?.eContent;
|
||||||
|
if (!eContent) {
|
||||||
|
throw new Error('No encapsulated content in SignedData (detached signature not supported)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eContent instanceof asn1js.OctetString) {
|
||||||
|
// Constructed OCTET STRING: data lives in child OctetStrings
|
||||||
|
const children = (eContent.valueBlock as unknown as { value?: asn1js.OctetString[] }).value;
|
||||||
|
if (children?.length) {
|
||||||
|
const chunks = children.map(c => new Uint8Array(c.valueBlock.valueHexView));
|
||||||
|
const total = chunks.reduce((sum, c) => sum + c.length, 0);
|
||||||
|
const result = new Uint8Array(total);
|
||||||
|
let offset = 0;
|
||||||
|
for (const chunk of chunks) {
|
||||||
|
result.set(chunk, offset);
|
||||||
|
offset += chunk.length;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
// Primitive OCTET STRING: data is directly in valueHexView
|
||||||
|
return new Uint8Array(eContent.valueBlock.valueHexView);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Unable to extract content from SignedData');
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractSignerCertificate(signedData: pkijs.SignedData): pkijs.Certificate | null {
|
||||||
|
if (!signedData.signerInfos?.length || !signedData.certificates?.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const signerInfo = signedData.signerInfos[0];
|
||||||
|
const sid = signerInfo.sid;
|
||||||
|
|
||||||
|
// IssuerAndSerialNumber matching
|
||||||
|
if (sid instanceof pkijs.IssuerAndSerialNumber) {
|
||||||
|
for (const certItem of signedData.certificates) {
|
||||||
|
if (!(certItem instanceof pkijs.Certificate)) continue;
|
||||||
|
const cert = certItem;
|
||||||
|
|
||||||
|
// Compare serial numbers
|
||||||
|
const sidSerial = toHex(sid.serialNumber.valueBlock.valueHexView);
|
||||||
|
const certSerial = toHex(cert.serialNumber.valueBlock.valueHexView);
|
||||||
|
if (sidSerial !== certSerial) continue;
|
||||||
|
|
||||||
|
// Compare issuers
|
||||||
|
const sidIssuerDer = new Uint8Array(sid.issuer.toSchema().toBER(false));
|
||||||
|
const certIssuerDer = new Uint8Array(cert.issuer.toSchema().toBER(false));
|
||||||
|
if (arraysEqual(sidIssuerDer, certIssuerDer)) {
|
||||||
|
return cert;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If only one certificate is present, use it as fallback
|
||||||
|
if (signedData.certificates.length === 1) {
|
||||||
|
const cert = signedData.certificates[0];
|
||||||
|
if (cert instanceof pkijs.Certificate) return cert;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toHex(buffer: ArrayBuffer | ArrayBufferView): string {
|
||||||
|
const bytes = buffer instanceof ArrayBuffer
|
||||||
|
? new Uint8Array(buffer)
|
||||||
|
: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
||||||
|
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function arraysEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
if (a[i] !== b[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
/** Stored record for an imported S/MIME private key + certificate. */
|
||||||
|
export interface SmimeKeyRecord {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
certificate: ArrayBuffer; // DER-encoded X.509 leaf cert
|
||||||
|
certificateChain: ArrayBuffer[]; // DER-encoded intermediates
|
||||||
|
encryptedPrivateKey: ArrayBuffer; // AES-GCM wrapped PKCS#8 bytes
|
||||||
|
salt: ArrayBuffer; // PBKDF2 salt
|
||||||
|
iv: ArrayBuffer; // AES-GCM IV
|
||||||
|
kdfIterations: number;
|
||||||
|
issuer: string;
|
||||||
|
subject: string;
|
||||||
|
serialNumber: string;
|
||||||
|
notBefore: string; // ISO 8601
|
||||||
|
notAfter: string; // ISO 8601
|
||||||
|
fingerprint: string; // SHA-256 hex of DER cert
|
||||||
|
algorithm: string; // e.g. "RSA-2048", "RSA-4096", "ECDSA-P256"
|
||||||
|
capabilities: SmimeKeyCapabilities;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a certificate can be used for based on KeyUsage/ExtendedKeyUsage. */
|
||||||
|
export interface SmimeKeyCapabilities {
|
||||||
|
canSign: boolean;
|
||||||
|
canEncrypt: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runtime-only unlocked private key handle (never persisted). */
|
||||||
|
export interface SmimeUnlockedKey {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
privateKey: CryptoKey; // imported as non-extractable
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A recipient or contact public certificate. */
|
||||||
|
export interface SmimePublicCert {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
certificate: ArrayBuffer; // DER-encoded X.509
|
||||||
|
issuer: string;
|
||||||
|
subject: string;
|
||||||
|
notBefore: string;
|
||||||
|
notAfter: string;
|
||||||
|
fingerprint: string;
|
||||||
|
source: 'manual' | 'contact' | 'signed-email';
|
||||||
|
contactId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Status of S/MIME processing for a single email message. */
|
||||||
|
export interface SmimeStatus {
|
||||||
|
isSigned: boolean;
|
||||||
|
isEncrypted: boolean;
|
||||||
|
signatureValid?: boolean;
|
||||||
|
signatureError?: string;
|
||||||
|
signerCert?: SmimePublicCert;
|
||||||
|
signerEmailMatch?: boolean;
|
||||||
|
decryptionSuccess?: boolean;
|
||||||
|
decryptionError?: string;
|
||||||
|
unsupportedReason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Metadata extracted from a parsed X.509 certificate. */
|
||||||
|
export interface CertificateInfo {
|
||||||
|
subject: string;
|
||||||
|
issuer: string;
|
||||||
|
serialNumber: string;
|
||||||
|
notBefore: string;
|
||||||
|
notAfter: string;
|
||||||
|
fingerprint: string;
|
||||||
|
algorithm: string;
|
||||||
|
keyUsage?: string[];
|
||||||
|
extendedKeyUsage?: string[];
|
||||||
|
emailAddresses: string[];
|
||||||
|
capabilities: SmimeKeyCapabilities;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Result of PKCS#12 import parsing. */
|
||||||
|
export interface Pkcs12ImportResult {
|
||||||
|
keyRecord: SmimeKeyRecord;
|
||||||
|
certInfo: CertificateInfo;
|
||||||
|
}
|
||||||
+398
@@ -0,0 +1,398 @@
|
|||||||
|
/**
|
||||||
|
* Minimal TNEF (Transport Neutral Encapsulation Format) parser.
|
||||||
|
*
|
||||||
|
* Parses winmail.dat files sent by Microsoft Outlook to extract
|
||||||
|
* the HTML body, plain text body, and embedded attachments.
|
||||||
|
*
|
||||||
|
* Reference: MS-OXTNEF / MS-TNEF specification.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { debug } from '@/lib/debug';
|
||||||
|
|
||||||
|
// TNEF signature
|
||||||
|
const TNEF_SIGNATURE = 0x223E9F78;
|
||||||
|
|
||||||
|
// Attribute levels
|
||||||
|
const LVL_MESSAGE = 0x01;
|
||||||
|
const LVL_ATTACHMENT = 0x02;
|
||||||
|
|
||||||
|
// Message-level attribute IDs
|
||||||
|
const attBody = 0x0002800C;
|
||||||
|
const attMAPIProps = 0x00069003;
|
||||||
|
|
||||||
|
// Attachment-level attribute IDs
|
||||||
|
const attAttachRenddata = 0x00069002;
|
||||||
|
const attAttachData = 0x0006800F;
|
||||||
|
const attAttachTitle = 0x00018010;
|
||||||
|
const attAttachment = 0x00069005; // MAPI props for attachments
|
||||||
|
|
||||||
|
// MAPI property types
|
||||||
|
const PT_SHORT = 0x0002;
|
||||||
|
const PT_LONG = 0x0003;
|
||||||
|
const PT_BOOLEAN = 0x000B;
|
||||||
|
const PT_STRING8 = 0x001E;
|
||||||
|
const PT_UNICODE = 0x001F;
|
||||||
|
const PT_BINARY = 0x0102;
|
||||||
|
const PT_SYSTIME = 0x0040;
|
||||||
|
const PT_CLSID = 0x0048;
|
||||||
|
const PT_I8 = 0x0014;
|
||||||
|
|
||||||
|
// Multi-value flag
|
||||||
|
const MV_FLAG = 0x1000;
|
||||||
|
|
||||||
|
// MAPI property IDs
|
||||||
|
const PR_BODY = 0x1000;
|
||||||
|
const PR_BODY_HTML = 0x1013;
|
||||||
|
const PR_ATTACH_LONG_FILENAME = 0x3707;
|
||||||
|
const PR_ATTACH_MIME_TAG = 0x370E;
|
||||||
|
const PR_ATTACH_DATA_BIN = 0x3701;
|
||||||
|
|
||||||
|
export interface TnefAttachment {
|
||||||
|
name: string;
|
||||||
|
mimeType: string;
|
||||||
|
data: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TnefResult {
|
||||||
|
body: string | null;
|
||||||
|
htmlBody: string | null;
|
||||||
|
attachments: TnefAttachment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
class BinaryReader {
|
||||||
|
private view: DataView;
|
||||||
|
private offset: number;
|
||||||
|
private bytes: Uint8Array;
|
||||||
|
|
||||||
|
constructor(data: Uint8Array) {
|
||||||
|
this.bytes = data;
|
||||||
|
this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||||
|
this.offset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
readUint8(): number {
|
||||||
|
const val = this.view.getUint8(this.offset);
|
||||||
|
this.offset += 1;
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
|
||||||
|
readUint16LE(): number {
|
||||||
|
const val = this.view.getUint16(this.offset, true);
|
||||||
|
this.offset += 2;
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
|
||||||
|
readUint32LE(): number {
|
||||||
|
const val = this.view.getUint32(this.offset, true);
|
||||||
|
this.offset += 4;
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
|
||||||
|
readBytes(length: number): Uint8Array {
|
||||||
|
const slice = this.bytes.slice(this.offset, this.offset + length);
|
||||||
|
this.offset += length;
|
||||||
|
return slice;
|
||||||
|
}
|
||||||
|
|
||||||
|
skip(n: number): void {
|
||||||
|
this.offset += n;
|
||||||
|
}
|
||||||
|
|
||||||
|
get remaining(): number {
|
||||||
|
return this.bytes.byteLength - this.offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Padding needed to align to 4-byte boundary */
|
||||||
|
function pad4(len: number): number {
|
||||||
|
return (4 - (len % 4)) % 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a single MAPI property value (fixed-length types only) */
|
||||||
|
function readMAPIFixedValue(r: BinaryReader, propType: number): Uint8Array | number | null {
|
||||||
|
switch (propType) {
|
||||||
|
case PT_SHORT: {
|
||||||
|
const val = r.readUint16LE();
|
||||||
|
r.skip(2); // padded to 4 bytes
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
case PT_LONG:
|
||||||
|
case PT_BOOLEAN:
|
||||||
|
return r.readUint32LE();
|
||||||
|
case PT_I8:
|
||||||
|
case PT_SYSTIME:
|
||||||
|
return r.readBytes(8);
|
||||||
|
case PT_CLSID:
|
||||||
|
return r.readBytes(16);
|
||||||
|
default:
|
||||||
|
// Unknown/unsupported type — try to read as fixed 4 bytes
|
||||||
|
if (r.remaining >= 4) {
|
||||||
|
return r.readBytes(4);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a variable-length MAPI value (length-prefixed with padding) */
|
||||||
|
function readMAPIVarValue(r: BinaryReader): Uint8Array | null {
|
||||||
|
if (r.remaining < 4) return null;
|
||||||
|
const length = r.readUint32LE();
|
||||||
|
if (length > r.remaining) return null;
|
||||||
|
const data = r.readBytes(length);
|
||||||
|
r.skip(pad4(length));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Check if a base property type is variable-length */
|
||||||
|
function isVarLengthType(baseType: number): boolean {
|
||||||
|
return baseType === PT_STRING8 || baseType === PT_UNICODE || baseType === PT_BINARY;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decode a MAPI string (PT_STRING8 or PT_UNICODE) from raw bytes */
|
||||||
|
function decodeMAPIString(data: Uint8Array, propType: number): string {
|
||||||
|
if (propType === PT_UNICODE) {
|
||||||
|
let len = data.byteLength;
|
||||||
|
// Strip null terminator (2 bytes for UTF-16)
|
||||||
|
if (len >= 2 && data[len - 1] === 0 && data[len - 2] === 0) {
|
||||||
|
len -= 2;
|
||||||
|
}
|
||||||
|
return new TextDecoder('utf-16le').decode(data.subarray(0, len));
|
||||||
|
}
|
||||||
|
let len = data.byteLength;
|
||||||
|
if (len >= 1 && data[len - 1] === 0) {
|
||||||
|
len -= 1;
|
||||||
|
}
|
||||||
|
return new TextDecoder('utf-8').decode(data.subarray(0, len));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse MAPI properties from a raw attribute data block */
|
||||||
|
function parseMAPIProps(data: Uint8Array): Map<number, { type: number; value: Uint8Array | number | null }> {
|
||||||
|
const props = new Map<number, { type: number; value: Uint8Array | number | null }>();
|
||||||
|
const r = new BinaryReader(data);
|
||||||
|
|
||||||
|
if (r.remaining < 4) return props;
|
||||||
|
const count = r.readUint32LE();
|
||||||
|
|
||||||
|
for (let i = 0; i < count && r.remaining >= 4; i++) {
|
||||||
|
const propType = r.readUint16LE();
|
||||||
|
const propID = r.readUint16LE();
|
||||||
|
|
||||||
|
// Named properties (ID >= 0x8000) carry extra GUID + name data
|
||||||
|
if (propID >= 0x8000) {
|
||||||
|
if (r.remaining < 20) break;
|
||||||
|
r.skip(16); // GUID
|
||||||
|
const kind = r.readUint32LE();
|
||||||
|
if (kind === 0) {
|
||||||
|
if (r.remaining < 4) break;
|
||||||
|
r.skip(4); // named-by-ID
|
||||||
|
} else {
|
||||||
|
if (r.remaining < 4) break;
|
||||||
|
const nameLen = r.readUint32LE();
|
||||||
|
if (nameLen > r.remaining) break;
|
||||||
|
r.skip(nameLen);
|
||||||
|
r.skip(pad4(nameLen));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseType = propType & 0x0FFF;
|
||||||
|
const isMultiValue = (propType & MV_FLAG) !== 0;
|
||||||
|
|
||||||
|
if (isVarLengthType(baseType)) {
|
||||||
|
// Variable-length types always have a value count (1 for single-value)
|
||||||
|
if (r.remaining < 4) break;
|
||||||
|
const valueCount = r.readUint32LE();
|
||||||
|
let lastValue: Uint8Array | null = null;
|
||||||
|
for (let j = 0; j < valueCount && r.remaining > 0; j++) {
|
||||||
|
lastValue = readMAPIVarValue(r);
|
||||||
|
}
|
||||||
|
if (!isMultiValue && lastValue) {
|
||||||
|
props.set(propID, { type: propType, value: lastValue });
|
||||||
|
}
|
||||||
|
} else if (isMultiValue) {
|
||||||
|
if (r.remaining < 4) break;
|
||||||
|
const valueCount = r.readUint32LE();
|
||||||
|
for (let j = 0; j < valueCount && r.remaining > 0; j++) {
|
||||||
|
readMAPIFixedValue(r, baseType);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const value = readMAPIFixedValue(r, baseType);
|
||||||
|
props.set(propID, { type: propType, value });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return props;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a TNEF (winmail.dat) file and extract the body and attachments.
|
||||||
|
*
|
||||||
|
* @param data - Raw bytes of the TNEF file
|
||||||
|
* @returns Parsed result with body text, HTML body, and attachments
|
||||||
|
*/
|
||||||
|
export function parseTnef(data: Uint8Array): TnefResult {
|
||||||
|
const result: TnefResult = {
|
||||||
|
body: null,
|
||||||
|
htmlBody: null,
|
||||||
|
attachments: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
debug.group('TNEF Parser');
|
||||||
|
debug.log('Input data size:', data.byteLength, 'bytes');
|
||||||
|
|
||||||
|
if (data.byteLength < 6) {
|
||||||
|
debug.warn('TNEF data too small (< 6 bytes), skipping');
|
||||||
|
debug.groupEnd();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const r = new BinaryReader(data);
|
||||||
|
|
||||||
|
const signature = r.readUint32LE();
|
||||||
|
if (signature !== TNEF_SIGNATURE) {
|
||||||
|
debug.warn('Invalid TNEF signature:', '0x' + signature.toString(16).toUpperCase(), '(expected 0x223E9F78)');
|
||||||
|
debug.groupEnd();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
debug.log('TNEF signature valid');
|
||||||
|
|
||||||
|
r.skip(2); // legacy key
|
||||||
|
|
||||||
|
// Current attachment being assembled
|
||||||
|
let curAttach: { name: string; mimeType: string; data: Uint8Array | null } | null = null;
|
||||||
|
let attrCount = 0;
|
||||||
|
|
||||||
|
while (r.remaining >= 11) {
|
||||||
|
const level = r.readUint8();
|
||||||
|
const attrID = r.readUint32LE();
|
||||||
|
const attrLen = r.readUint32LE();
|
||||||
|
attrCount++;
|
||||||
|
|
||||||
|
if (attrLen > r.remaining - 2) {
|
||||||
|
debug.warn('Attribute #' + attrCount + ': truncated data — need', attrLen, 'bytes but only', r.remaining - 2, 'available');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const attrData = r.readBytes(attrLen);
|
||||||
|
r.skip(2); // checksum
|
||||||
|
|
||||||
|
const levelName = level === LVL_MESSAGE ? 'MESSAGE' : level === LVL_ATTACHMENT ? 'ATTACHMENT' : 'UNKNOWN(' + level + ')';
|
||||||
|
debug.log('Attribute #' + attrCount + ':', levelName, 'id=0x' + attrID.toString(16).toUpperCase(), 'len=' + attrLen);
|
||||||
|
|
||||||
|
if (level === LVL_MESSAGE) {
|
||||||
|
if (attrID === attBody) {
|
||||||
|
result.body = new TextDecoder('utf-8').decode(attrData);
|
||||||
|
debug.log(' → Extracted plain text body (' + result.body.length + ' chars)');
|
||||||
|
} else if (attrID === attMAPIProps) {
|
||||||
|
const props = parseMAPIProps(attrData);
|
||||||
|
debug.log(' → Parsed', props.size, 'MAPI properties from message');
|
||||||
|
props.forEach((val, propID) => {
|
||||||
|
debug.log(' MAPI prop 0x' + propID.toString(16).toUpperCase(), 'type=0x' + val.type.toString(16), 'value=' + (val.value instanceof Uint8Array ? val.value.byteLength + ' bytes' : val.value));
|
||||||
|
});
|
||||||
|
|
||||||
|
// HTML body
|
||||||
|
const htmlProp = props.get(PR_BODY_HTML);
|
||||||
|
if (htmlProp?.value instanceof Uint8Array) {
|
||||||
|
const baseType = htmlProp.type & 0x0FFF;
|
||||||
|
if (baseType === PT_STRING8 || baseType === PT_UNICODE) {
|
||||||
|
result.htmlBody = decodeMAPIString(htmlProp.value, baseType);
|
||||||
|
} else {
|
||||||
|
result.htmlBody = new TextDecoder('utf-8').decode(htmlProp.value);
|
||||||
|
}
|
||||||
|
debug.log(' → Extracted HTML body (' + result.htmlBody.length + ' chars)');
|
||||||
|
} else {
|
||||||
|
debug.log(' → No HTML body property (PR_BODY_HTML 0x1013) found in MAPI props');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plain text body from MAPI props (fallback)
|
||||||
|
if (!result.body) {
|
||||||
|
const bodyProp = props.get(PR_BODY);
|
||||||
|
if (bodyProp?.value instanceof Uint8Array) {
|
||||||
|
result.body = decodeMAPIString(bodyProp.value, bodyProp.type & 0x0FFF);
|
||||||
|
debug.log(' → Extracted plain text body from MAPI props (' + result.body.length + ' chars)');
|
||||||
|
} else {
|
||||||
|
debug.log(' → No plain text body property (PR_BODY 0x1000) found in MAPI props');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (level === LVL_ATTACHMENT) {
|
||||||
|
if (attrID === attAttachRenddata) {
|
||||||
|
// Start of a new attachment — flush previous
|
||||||
|
if (curAttach?.data) {
|
||||||
|
debug.log(' → Flushing previous attachment:', curAttach.name, '(' + curAttach.mimeType + ',', curAttach.data.byteLength, 'bytes)');
|
||||||
|
result.attachments.push({
|
||||||
|
name: curAttach.name,
|
||||||
|
mimeType: curAttach.mimeType,
|
||||||
|
data: curAttach.data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
curAttach = { name: 'attachment', mimeType: 'application/octet-stream', data: null };
|
||||||
|
debug.log(' → New attachment started');
|
||||||
|
} else if (attrID === attAttachTitle && curAttach) {
|
||||||
|
let len = attrData.byteLength;
|
||||||
|
if (len > 0 && attrData[len - 1] === 0) len--;
|
||||||
|
curAttach.name = new TextDecoder('utf-8').decode(attrData.subarray(0, len));
|
||||||
|
debug.log(' → Attachment short name:', curAttach.name);
|
||||||
|
} else if (attrID === attAttachData && curAttach) {
|
||||||
|
curAttach.data = attrData;
|
||||||
|
debug.log(' → Attachment data (attAttachData):', attrData.byteLength, 'bytes');
|
||||||
|
} else if (attrID === attAttachment && curAttach) {
|
||||||
|
const props = parseMAPIProps(attrData);
|
||||||
|
debug.log(' → Parsed', props.size, 'MAPI properties from attachment');
|
||||||
|
props.forEach((val, propID) => {
|
||||||
|
debug.log(' MAPI prop 0x' + propID.toString(16).toUpperCase(), 'type=0x' + val.type.toString(16), 'value=' + (val.value instanceof Uint8Array ? val.value.byteLength + ' bytes' : val.value));
|
||||||
|
});
|
||||||
|
|
||||||
|
const longName = props.get(PR_ATTACH_LONG_FILENAME);
|
||||||
|
if (longName?.value instanceof Uint8Array) {
|
||||||
|
curAttach.name = decodeMAPIString(longName.value, longName.type & 0x0FFF);
|
||||||
|
debug.log(' → Attachment long filename:', curAttach.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
const mimeTag = props.get(PR_ATTACH_MIME_TAG);
|
||||||
|
if (mimeTag?.value instanceof Uint8Array) {
|
||||||
|
curAttach.mimeType = decodeMAPIString(mimeTag.value, mimeTag.type & 0x0FFF);
|
||||||
|
debug.log(' → Attachment MIME type:', curAttach.mimeType);
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachData = props.get(PR_ATTACH_DATA_BIN);
|
||||||
|
if (attachData?.value instanceof Uint8Array) {
|
||||||
|
curAttach.data = attachData.value;
|
||||||
|
debug.log(' → Attachment data (PR_ATTACH_DATA_BIN):', attachData.value.byteLength, 'bytes');
|
||||||
|
} else {
|
||||||
|
debug.log(' → No PR_ATTACH_DATA_BIN found in attachment MAPI props');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush last attachment
|
||||||
|
if (curAttach?.data) {
|
||||||
|
debug.log('Flushing final attachment:', curAttach.name, '(' + curAttach.mimeType + ',', curAttach.data.byteLength, 'bytes)');
|
||||||
|
result.attachments.push({
|
||||||
|
name: curAttach.name,
|
||||||
|
mimeType: curAttach.mimeType,
|
||||||
|
data: curAttach.data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
debug.log('TNEF parsing complete — body:', !!result.body, ', htmlBody:', !!result.htmlBody, ', attachments:', result.attachments.length);
|
||||||
|
if (result.attachments.length > 0) {
|
||||||
|
debug.table(result.attachments.map(a => ({ name: a.name, mimeType: a.mimeType, size: a.data.byteLength })));
|
||||||
|
}
|
||||||
|
debug.groupEnd();
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a MIME attachment is a TNEF (winmail.dat) file.
|
||||||
|
*/
|
||||||
|
export function isTnefAttachment(name?: string | null, type?: string): boolean {
|
||||||
|
const lowerName = (name || '').toLowerCase();
|
||||||
|
const lowerType = (type || '').toLowerCase();
|
||||||
|
return (
|
||||||
|
lowerName === 'winmail.dat' ||
|
||||||
|
lowerType === 'application/ms-tnef' ||
|
||||||
|
lowerType === 'application/vnd.ms-tnef'
|
||||||
|
);
|
||||||
|
}
|
||||||
+46
-6
@@ -27,6 +27,42 @@ export function formatDate(date: Date | string): string {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format a date/time string respecting the user's 12h/24h time format preference.
|
||||||
|
*/
|
||||||
|
export function formatDateTime(
|
||||||
|
date: Date | string,
|
||||||
|
timeFormat: '12h' | '24h',
|
||||||
|
options?: {
|
||||||
|
weekday?: 'short' | 'long';
|
||||||
|
year?: 'numeric';
|
||||||
|
month?: 'short' | 'long';
|
||||||
|
day?: 'numeric';
|
||||||
|
second?: '2-digit';
|
||||||
|
timeZoneName?: 'short';
|
||||||
|
dateOnly?: boolean;
|
||||||
|
}
|
||||||
|
): string {
|
||||||
|
const d = typeof date === 'string' ? new Date(date) : date;
|
||||||
|
if (isNaN(d.getTime())) return typeof date === 'string' ? date : '';
|
||||||
|
|
||||||
|
const localeOptions: Intl.DateTimeFormatOptions = {};
|
||||||
|
if (options?.weekday) localeOptions.weekday = options.weekday;
|
||||||
|
if (options?.year) localeOptions.year = options.year;
|
||||||
|
if (options?.month) localeOptions.month = options.month;
|
||||||
|
if (options?.day) localeOptions.day = options.day;
|
||||||
|
|
||||||
|
if (!options?.dateOnly) {
|
||||||
|
localeOptions.hour = '2-digit';
|
||||||
|
localeOptions.minute = '2-digit';
|
||||||
|
localeOptions.hour12 = timeFormat === '12h';
|
||||||
|
if (options?.second) localeOptions.second = options.second;
|
||||||
|
if (options?.timeZoneName) localeOptions.timeZoneName = options.timeZoneName;
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.toLocaleString(undefined, localeOptions);
|
||||||
|
}
|
||||||
|
|
||||||
export function truncateText(text: string, maxLength: number): string {
|
export function truncateText(text: string, maxLength: number): string {
|
||||||
if (text.length <= maxLength) return text;
|
if (text.length <= maxLength) return text;
|
||||||
return text.substring(0, maxLength).trim() + "...";
|
return text.substring(0, maxLength).trim() + "...";
|
||||||
@@ -61,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) {
|
||||||
@@ -79,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);
|
||||||
|
|||||||
+92
-16
@@ -1,4 +1,50 @@
|
|||||||
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> = {
|
||||||
|
M: "masculine",
|
||||||
|
F: "feminine",
|
||||||
|
O: "other",
|
||||||
|
N: "none",
|
||||||
|
U: "unknown",
|
||||||
|
};
|
||||||
|
|
||||||
|
const GENDER_TO_VCARD_SEX: Record<string, string> = {
|
||||||
|
masculine: "M",
|
||||||
|
feminine: "F",
|
||||||
|
other: "O",
|
||||||
|
none: "N",
|
||||||
|
unknown: "U",
|
||||||
|
};
|
||||||
|
|
||||||
|
function vcardSexToGrammaticalGender(sex: string): string {
|
||||||
|
return VCARD_SEX_TO_GENDER[sex.toUpperCase()] || sex.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function grammaticalGenderToVcardSex(gender: string): string {
|
||||||
|
return GENDER_TO_VCARD_SEX[gender.toLowerCase()] || "";
|
||||||
|
}
|
||||||
|
|
||||||
function unfoldLines(vcf: string): string {
|
function unfoldLines(vcf: string): string {
|
||||||
return vcf.replace(/\r\n[ \t]/g, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
return vcf.replace(/\r\n[ \t]/g, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
||||||
@@ -390,9 +436,17 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
|
|||||||
|
|
||||||
case "GENDER": {
|
case "GENDER": {
|
||||||
const gParts = val.split(";");
|
const gParts = val.split(";");
|
||||||
card.gender = {};
|
const sexCode = gParts[0]?.toUpperCase();
|
||||||
if (gParts[0]) card.gender.sex = gParts[0];
|
const identityText = gParts[1];
|
||||||
if (gParts[1]) card.gender.identity = gParts[1];
|
if (sexCode || identityText) {
|
||||||
|
card.speakToAs = {};
|
||||||
|
if (sexCode) {
|
||||||
|
card.speakToAs.grammaticalGender = vcardSexToGrammaticalGender(sexCode);
|
||||||
|
}
|
||||||
|
if (identityText) {
|
||||||
|
card.speakToAs.pronouns = { p0: { pronouns: identityText } };
|
||||||
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -566,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(";")}`);
|
||||||
}
|
}
|
||||||
@@ -581,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}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -684,10 +755,15 @@ function generateSingleVCard(contact: ContactCard): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contact.gender) {
|
if (contact.speakToAs) {
|
||||||
const sex = contact.gender.sex || "";
|
const sex = contact.speakToAs.grammaticalGender
|
||||||
const identity = contact.gender.identity || "";
|
? grammaticalGenderToVcardSex(contact.speakToAs.grammaticalGender)
|
||||||
lines.push(`GENDER:${sex}${identity ? `;${identity}` : ""}`);
|
: "";
|
||||||
|
const pronouns = contact.speakToAs.pronouns;
|
||||||
|
const identity = pronouns ? Object.values(pronouns)[0]?.pronouns || "" : "";
|
||||||
|
if (sex || identity) {
|
||||||
|
lines.push(`GENDER:${sex}${identity ? `;${identity}` : ""}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contact.calendarUri) {
|
if (contact.calendarUri) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user