Compare commits

..
48 Commits
Author SHA1 Message Date
Linus Rath 8c5aec9ca4 chore: update version to 1.6.7 2026-05-17 18:17:13 +02:00
Linus Rath 375220298d i18n: add missing translation keys across 16 locales 2026-05-17 18:12:17 +02:00
Linus Rath 452976ed95 fix: apply dark background to email content wrapper in dark mode 2026-05-17 17:40:35 +02:00
Linus Rath 243a2adfbf fix: improve dark mode background colors in email viewer 2026-05-17 17:39:49 +02:00
Linus Rath 1ba4a13353 fix: show "no body content" instead of infinite skeleton for bodyless emails 2026-05-17 17:33:06 +02:00
Linus Rath 5de12dfb79 perf: speed up calendar invitation banner load
Parallelize ICS parse with raw blob fetch, render the banner as soon
as parsing returns instead of awaiting the existing-event lookup, and
filter that lookup by UID server-side instead of fetching every event
on the calendar.
2026-05-17 17:28:10 +02:00
Linus Rath 689d646c57 fix: show contact popup when clicking sender name in email header 2026-05-17 17:19:43 +02:00
Linus Rath 49cd7f8130 feat: show details toggle and panel on mobile sender info 2026-05-17 17:15:19 +02:00
Linus Rath 4545e212f4 fix: align quick reply with mobile bottom toolbar 2026-05-17 17:06:30 +02:00
Linus Rath b1f4f6eae0 fix: pin quick reply to bottom for short emails 2026-05-17 16:56:54 +02:00
Linus Rath 9a431a873b fix: close attachment preview when clicking outside content 2026-05-17 16:49:13 +02:00
Linus Rath bb7e1c4538 fix: per-account push subscriptions so multi-account notifications work #298 2026-05-16 22:50:01 +02:00
Linus Rath 356abcfc2d fix: redact sensitive config secrets from admin API response 2026-05-16 22:48:06 +02:00
Linus Rath 3099b4801e fix: sandbox thread email HTML in srcDoc iframe with CSP meta 2026-05-16 20:49:59 +02:00
Linus Rath fc641e94ac fix: carry configSchema + settingsSchema through marketplace install 2026-05-16 19:51:59 +02:00
Linus Rath 0e758409ee fix: prevent long addresses from overflowing email details columns #297 2026-05-16 19:47:03 +02:00
Linus Rath 8c93941d8d feat: render app-top-banner slot on every authenticated page 2026-05-16 19:39:45 +02:00
Linus Rath 4221c9a50f fix: strip Stalwart master-user '%' suffix from displayed account 2026-05-16 19:07:10 +02:00
Linus Rath 3a559479bd fix: make impersonation cookies session-only 2026-05-16 18:59:46 +02:00
Linus Rath 482493a10d fix: register app-top-banner in plugin-store SLOT_NAMES 2026-05-16 18:53:06 +02:00
Linus Rath 0e1036eb49 fix: adopt orphan session cookie on first SPA load 2026-05-16 18:45:30 +02:00
Linus Rath 349406723c fix: use relative Location header in redirect 2026-05-16 18:33:44 +02:00
Linus Rath 997bedc91b feat: allow admin password overwrite during setup recovery 2026-05-16 18:21:48 +02:00
Linus Rath 307e6d5d34 fix: warn + block install when app version is below plugin's minAppVersion 2026-05-16 18:11:52 +02:00
Linus Rath ca1108f455 feat: master-user impersonation route + app-top-banner plugin slot 2026-05-16 17:59:07 +02:00
Linus Rath 0ff88f36ed Merge branch 'main' of https://github.com/bulwarkmail/webmail 2026-05-16 16:35:43 +02:00
Linus Rath 285b4e349c fix: add outputFileTracingExcludes to optimize Turbopack memory tracing 2026-05-16 16:35:06 +02:00
Linus Rath 2b4ebb1fbb feat: add HTTPS requirement warning in setup wizard 2026-05-16 16:31:12 +02:00
Timo StreuleandLinus Rath a829c2818f fix: pad safe-area-inset-top 2026-05-16 00:55:24 +02:00
Timo StreuleandLinus Rath c54cf73c3a fix: respect safe-area insets on mobile bottom bars 2026-05-15 23:50:29 +02:00
Timo StreuleandLinus Rath c45ef86924 fix: add viewport export with 'initialScale: 1' 2026-05-15 23:01:39 +02:00
Linus Rath f39366b470 fix: read OAUTH_SCOPES at runtime instead of build time 2026-05-15 20:37:00 +02:00
Linus Rath b725000f4d feat: implement vCard 4.0 parsing and generation support 2026-05-15 20:10:18 +02:00
Linus Rath 105194a8b9 chore: update version to 1.6.6 2026-05-15 15:20:07 +02:00
Linus Rath 8dbb538c98 feat: sync onboarding status across devices #285 2026-05-15 15:09:42 +02:00
Linus Rath e435356c53 Merge branch 'main' of https://github.com/bulwarkmail/webmail 2026-05-15 14:49:58 +02:00
Linus Rath 6f9982540c feat: add icons for shared, important, memos, scheduled, snoozed folders #288 2026-05-15 14:48:39 +02:00
Timo StreuleandLinus Rath d0d6632b24 chore: drop redundant '-- ' prefix from dev identity signatures
The signature separator is already controlled by the
signatureSeparatorEnabled setting (lib/email-composer), which prepends
'-- ' at compose time when enabled. Baking it into the fixture
double-prefixed it.
2026-05-15 14:46:43 +02:00
Timo StreuleandLinus Rath 4b7009dfc2 feat: raise HTML signature length cap to 50000 chars
5000 chars is too tight for signatures containing base64-embedded images (even a small PNG can run a few thousand chars).
2026-05-15 14:46:43 +02:00
Timo StreuleandLinus Rath 55a408e810 feat: allow img in HTML identity signatures
- Restricts src to https: URLs or base64-embedded raster data: URIs (png/jpeg/gif/webp).
- SVG is excluded for safety reasons.
- Images with a disallowed src are removed entirely so they don't render as broken-image icons.
2026-05-15 14:46:43 +02:00
Linus Rath d5dddba6df fix: hide Files settings/nav when filesEnabled policy is off #291 2026-05-15 14:41:57 +02:00
Linus Rath d1a0667c79 i18n: clean up Danish locale wiring and sort language lists 286 2026-05-15 14:31:24 +02:00
Jesper OrdrupandLinus Rath e700e4fd04 match any translation 2026-05-15 14:26:33 +02:00
Jesper OrdrupandLinus Rath cf993c1036 adjust flag 2026-05-15 14:26:33 +02:00
Jesper OrdrupandLinus Rath 5fdf226ebe feat(i18n): add danish localization 2026-05-15 14:26:33 +02:00
Linus Rath fae15f073e fix: honor cookieSameSite admin config override #284 2026-05-14 21:49:37 +02:00
Linus Rath c646c87030 fix: standardize punctuation in tooltips and comments across multiple locales and code files 2026-05-14 21:44:24 +02:00
Linus Rath b4a76bc4d1 chore: expand demo fixtures with more emails, contacts, and portrait photos 2026-05-14 15:19:24 +02:00
103 changed files with 6328 additions and 775 deletions
+67
View File
@@ -1,5 +1,72 @@
# Changelog
## 1.6.7 (2026-05-17)
### Features
- **Contacts**: vCard 4.0 parsing and generation support
- **Admin**: Master-user impersonation route with `app-top-banner` plugin slot rendered on every authenticated page
- **Admin**: Allow admin password overwrite during setup recovery
- **Setup**: HTTPS requirement warning in the setup wizard
- **Mobile**: Show details toggle and expandable panel for sender info
### Performance
- **Calendar**: Speed up calendar invitation banner load
### Security
- **Mail**: Sandbox thread email HTML in `srcDoc` iframe with a CSP `<meta>` tag
- **Admin**: Redact sensitive config secrets from the admin API response
- **Admin**: Make impersonation cookies session-only
### Fixes
- **Auth**: Read `OAUTH_SCOPES` at runtime instead of build time
- **Auth**: Use a relative `Location` header in redirects
- **Auth**: Adopt orphan session cookie on first SPA load
- **Mail**: Per-account push subscriptions so multi-account notifications work (#298)
- **Mail**: Close attachment preview when clicking outside the content area
- **Mail**: Pin quick reply to the bottom for short emails
- **Mail**: Show "no body content" instead of an infinite skeleton for bodyless emails
- **Mail**: Show contact popup when clicking the sender name in the email header
- **Mail**: Prevent long addresses from overflowing email details columns (#297)
- **Mobile**: Align quick reply with the mobile bottom toolbar
- **Mobile**: Respect safe-area insets on mobile bottom bars
- **Mobile**: Pad `safe-area-inset-top`
- **UI**: Apply dark background to the email content wrapper in dark mode
- **UI**: Improve dark mode background colors in the email viewer
- **UI**: Add viewport export with `initialScale: 1`
- **UI**: Strip the Stalwart master-user `%` suffix from the displayed account
- **Plugins**: Warn and block install when the app version is below the plugin's `minAppVersion`
- **Plugins**: Register `app-top-banner` in plugin-store `SLOT_NAMES`
- **Plugins**: Carry `configSchema` + `settingsSchema` through marketplace install
- **Build**: Add `outputFileTracingExcludes` to reduce Turbopack memory tracing
### i18n
- Add missing translation keys across 16 locales
## 1.6.6 (2026-05-15)
### Features
- **Mail**: Sync onboarding completion state across devices so the welcome flow only runs once per account (#285)
- **Mail**: Distinct icons for Shared, Important, Memos, Scheduled, and Snoozed folders (#288)
- **Compose**: Raise HTML identity signature length cap to 50,000 characters
- **Compose**: Allow `<img>` tags in HTML identity signatures for inline logos and banners
### Fixes
- **Files**: Hide Files settings entry and sidebar nav when the `filesEnabled` policy is off (#291)
- **Admin**: Honor the `cookieSameSite` admin config override instead of always defaulting (#284)
- **UI**: Standardize punctuation in tooltips and inline comments across locales
### i18n
- Add Danish localization
- Clean up Danish locale wiring and sort the language picker alphabetically (#286)
## 1.6.5 (2026-05-13)
### Features
+12 -12
View File
@@ -101,24 +101,24 @@ This project uses **next-intl**. English (`/locales/en/common.json`) is the sour
### Rules
1. **Never hardcode user-facing text** always use translations:
1. **Never hardcode user-facing text** - always use translations:
```tsx
const t = useTranslations("namespace");
return <div>{t("key")}</div>;
```
2. **Add new keys to `en/common.json` first.** Other locales can follow in the same PR or a follow-up missing keys fall back to English.
2. **Add new keys to `en/common.json` first.** Other locales can follow in the same PR or a follow-up - missing keys fall back to English.
3. **Namespace organization**:
- `login.*` login page
- `sidebar.*` sidebar navigation
- `email_list.*` email list
- `email_viewer.*` email viewer
- `email_composer.*` composer
- `settings.*` settings page
- `notifications.*` toasts and alerts
- `common.*` shared strings
- `login.*` - login page
- `sidebar.*` - sidebar navigation
- `email_list.*` - email list
- `email_viewer.*` - email viewer
- `email_composer.*` - composer
- `settings.*` - settings page
- `notifications.*` - toasts and alerts
- `common.*` - shared strings
4. **Locale-aware navigation**:
@@ -200,9 +200,9 @@ webmail/
## Security
- **Never commit secrets** API keys, passwords, tokens, `.env*` files
- **Never commit secrets** - API keys, passwords, tokens, `.env*` files
- **Sanitize user input** and email content
- **Block external content** by default privacy is the point
- **Block external content** by default - privacy is the point
- **Report vulnerabilities privately** to bulwark@rbm.systems, not via public issues
## Questions?
+1 -1
View File
@@ -98,7 +98,7 @@
## Internationalization
15 languages: English · Français · 日本語 · Español · Italiano · Deutsch · Nederlands · Português · Русский · Türkçe · 한국어 · Polski · Latviešu · 简体中文 · Українська
17 languages: Česky · Dansk · Deutsch · English · Español · Français · Italiano · Latviešu · Nederlands · Polski · Português · Türkçe · Русский · Українська · 한국어 · 日本語 · 简体中文
Automatic browser detection with persistent preference. Configurable locale URL prefix via `NEXT_PUBLIC_LOCALE_PREFIX`.
+1 -1
View File
@@ -12,7 +12,7 @@ A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.ar
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg?logo=gnu&logoColor=white)](LICENSE)
[![Discord](https://img.shields.io/discord/1482128142939455674?color=7289da&label=discord&logo=discord&logoColor=white)](https://discord.gg/tYCujymGrT)
[![Version](https://img.shields.io/badge/version-1.6.5-green.svg?logo=git&logoColor=white)](CHANGELOG.md)
[![Version](https://img.shields.io/badge/version-1.6.7-green.svg?logo=git&logoColor=white)](CHANGELOG.md)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fbulwarkmail%2Fwebmail-blue?logo=docker&logoColor=white)](https://ghcr.io/bulwarkmail/webmail)
[![Grafana](https://img.shields.io/badge/grafana-dashboard-orange?logo=grafana&logoColor=white)](https://grafana.external.bulwarkmail.org/)
+1 -1
View File
@@ -1 +1 @@
1.6.5
1.6.6
+5 -1
View File
@@ -32,6 +32,7 @@ import { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-pan
import { EventModal, type PendingEventPreview } from "@/components/calendar/event-modal";
import { EventDetailPopover } from "@/components/calendar/event-detail-popover";
import { EventContextMenu } from "@/components/calendar/event-context-menu";
import { AppTopBannerSlot } from "@/components/plugins/app-top-banner-slot";
import { EmptySpaceContextMenu } from "@/components/calendar/empty-space-context-menu";
import { useContextMenu } from "@/hooks/use-context-menu";
import { useRefreshGesture } from "@/hooks/use-refresh-gesture";
@@ -1216,7 +1217,9 @@ export default function CalendarPage() {
};
return (
<div className={cn("flex h-dvh bg-background overflow-hidden", isMobile && "flex-col")}>
<div className="flex flex-col h-dvh bg-background overflow-hidden pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
<div className={cn("flex flex-1 min-h-0 overflow-hidden", isMobile && "flex-col")}>
{/* Left Navigation Rail */}
{!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
@@ -1580,6 +1583,7 @@ export default function CalendarPage() {
/>
);
})()}
</div>
</div>
);
}
+5 -1
View File
@@ -15,6 +15,7 @@ import { ContactsSidebar, type ContactCategory } from "@/components/contacts/con
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
import { RenameDialog } from "@/components/files/rename-dialog";
import { exportContacts } from "@/components/contacts/contact-export";
import { AppTopBannerSlot } from "@/components/plugins/app-top-banner-slot";
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
@@ -649,7 +650,9 @@ export default function ContactsPage() {
};
return (
<div className={cn("flex h-dvh bg-background overflow-hidden", isMobile && "flex-col")}>
<div className="flex flex-col h-dvh bg-background overflow-hidden pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
<div className={cn("flex flex-1 min-h-0 overflow-hidden", isMobile && "flex-col")}>
{/* Navigation Rail - desktop only */}
{!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
@@ -882,6 +885,7 @@ export default function ContactsPage() {
/>
);
})()}
</div>
</div>
);
}
+5 -1
View File
@@ -24,6 +24,7 @@ import { ImagePreviewModal } from "@/components/files/image-preview-modal";
import { FilePreviewModal } from "@/components/files/file-preview-modal";
import { loadFilesSettings } from "@/components/files/files-settings-dialog";
import type { FolderLayout } from "@/components/files/files-settings-dialog";
import { AppTopBannerSlot } from "@/components/plugins/app-top-banner-slot";
import { AlertTriangle } from "lucide-react";
export default function FilesPage() {
@@ -374,7 +375,9 @@ export default function FilesPage() {
if (!isAuthenticated) return null;
return (
<div className="flex h-dvh bg-background overflow-hidden">
<div className="flex flex-col h-dvh bg-background overflow-hidden pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
<div className="flex flex-1 min-h-0 overflow-hidden">
{!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
<NavigationRail
@@ -514,6 +517,7 @@ export default function FilesPage() {
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
<ConfirmDialog {...confirmDialogProps} />
</div>
</div>
);
}
+2 -3
View File
@@ -16,7 +16,6 @@ import { cn } from "@/lib/utils";
import { AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play, Copy } from "lucide-react";
import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
import { useUpdateStore, selectBanner } from "@/stores/update-store";
import type { PublicJmapServerEntry } from "@/lib/admin/jmap-servers";
@@ -117,7 +116,7 @@ export default function LoginPage() {
const isAddAccountMode = searchParams.get("mode") === "add-account";
const { login, loginDemo, isLoading, error, clearError, isAuthenticated } = useAuthStore();
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
const { appName, jmapServerUrl: configuredServerUrl, oauthEnabled, oauthOnly, oauthClientId: globalOauthClientId, oauthIssuerUrl: globalOauthIssuerUrl, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode, allowCustomJmapEndpoint, jmapServers, jmapServerAutoPickByDomain } = useConfig();
const { appName, jmapServerUrl: configuredServerUrl, oauthEnabled, oauthOnly, oauthClientId: globalOauthClientId, oauthIssuerUrl: globalOauthIssuerUrl, oauthScopes, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode, allowCustomJmapEndpoint, jmapServers, jmapServerAutoPickByDomain } = useConfig();
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
const [formData, setFormData] = useState({
@@ -532,7 +531,7 @@ export default function LoginPage() {
authUrl.searchParams.set("response_type", "code");
authUrl.searchParams.set("client_id", effectiveOauthClientId);
authUrl.searchParams.set("redirect_uri", redirectUri);
authUrl.searchParams.set("scope", OAUTH_SCOPES);
authUrl.searchParams.set("scope", oauthScopes || "openid email profile");
authUrl.searchParams.set("state", state);
authUrl.searchParams.set("code_challenge", challenge);
authUrl.searchParams.set("code_challenge_method", "S256");
+5 -3
View File
@@ -60,6 +60,7 @@ import { ResizeHandle } from "@/components/layout/resize-handle";
import { Button } from "@/components/ui/button";
import { useConfig } from "@/hooks/use-config";
import { usePluginStore } from "@/stores/plugin-store";
import { AppTopBannerSlot } from "@/components/plugins/app-top-banner-slot";
import { useThemeStore } from "@/stores/theme-store";
import { consumePendingMailto, subscribeToPendingMailto } from "@/lib/protocol-handlers/session";
import type { ParsedMailto } from "@/lib/protocol-handlers/mailto";
@@ -1959,7 +1960,8 @@ export default function Home() {
return (
<DragDropProvider>
<div className="flex flex-col h-dvh bg-background overflow-hidden">
<div className="flex flex-col h-dvh bg-background overflow-hidden pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
{isRateLimited && rateLimitSecondsLeft !== null && (
<div className="flex items-center justify-center gap-2 bg-amber-500/10 border-b border-amber-500/30 text-amber-700 dark:text-amber-300 text-sm py-1.5 px-4 flex-shrink-0">
<AlertTriangle className="h-3.5 w-3.5" />
@@ -2009,7 +2011,7 @@ export default function Home() {
"flex-shrink-0 h-full z-50",
!isResizing && "transition-[width] duration-300",
// Mobile/Tablet: fixed overlay
"max-lg:fixed max-lg:inset-y-0 max-lg:left-0 max-lg:w-72",
"max-lg:fixed max-lg:inset-y-0 max-lg:left-0 max-lg:w-72 max-lg:pt-[env(safe-area-inset-top)]",
"max-lg:transform max-lg:transition-transform max-lg:duration-300 max-lg:ease-in-out",
!sidebarOpen && "max-lg:-translate-x-full",
// Desktop: normal flow
@@ -2418,7 +2420,7 @@ export default function Home() {
isHorizontalMailLayout ? "min-h-0" : "h-full",
// Mobile: full screen overlay when active
"max-md:fixed max-md:inset-0 max-md:z-30",
"max-md:h-full",
"max-md:h-full max-md:pt-[env(safe-area-inset-top)]",
isMobile && activeView !== "viewer" && "max-md:hidden",
// Tablet/Desktop: relative
"md:relative",
+10 -4
View File
@@ -39,6 +39,7 @@ import {
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { AppearanceSettings } from '@/components/settings/appearance-settings';
import { AppTopBannerSlot } from '@/components/plugins/app-top-banner-slot';
import { LayoutSettings } from '@/components/settings/layout-settings';
import { LanguageSettings } from '@/components/settings/language-settings';
import { ReadingSettings } from '@/components/settings/reading-settings';
@@ -590,7 +591,7 @@ export default function SettingsPage() {
// Apps
...(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' },
...(supportsFiles ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []),
...(supportsFiles && isFeatureEnabled('filesEnabled') ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []),
...(isFeatureEnabled('sidebarAppsEnabled') ? [{ id: 'sidebar_apps' as Tab, label: t('tabs.sidebar_apps'), icon: tabIcons.sidebar_apps, group: 'apps' as TabGroup }] : []),
// Advanced
@@ -686,7 +687,8 @@ export default function SettingsPage() {
if (!isDesktop) {
if (mobileShowContent) {
return (
<div className="flex flex-col h-dvh bg-background">
<div className="flex flex-col h-dvh bg-background pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
<div className="flex items-center gap-2 px-4 h-14 border-b border-border bg-background shrink-0">
<Button
variant="ghost"
@@ -716,7 +718,8 @@ export default function SettingsPage() {
}
return (
<div className="flex flex-col h-dvh bg-background">
<div className="flex flex-col h-dvh bg-background pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
<div className="flex items-center gap-2 px-4 h-14 border-b border-border bg-background shrink-0">
<Button
variant="ghost"
@@ -826,7 +829,9 @@ export default function SettingsPage() {
// Desktop layout
return (
<div className="flex h-dvh bg-background">
<div className="flex flex-col h-dvh bg-background pt-[env(safe-area-inset-top)]">
<AppTopBannerSlot />
<div className="flex flex-1 min-h-0">
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
<NavigationRail
collapsed
@@ -958,6 +963,7 @@ export default function SettingsPage() {
</>
)}
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
</div>
</div>
);
}
+6 -2
View File
@@ -5,8 +5,12 @@ import { Save, Loader2, RotateCcw, Sparkles } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigEntry {
value: unknown;
// Sensitive keys (sessionSecret, oauthClientSecret) come back with
// `value` omitted and `hasValue` set instead — the server never echoes
// the raw secret to the client.
value?: unknown;
source: 'admin' | 'env' | 'default';
hasValue?: boolean;
}
export function AuthTab() {
@@ -267,7 +271,7 @@ export function AuthTab() {
<Toggle label="OAuth Enabled" configKey="oauthEnabled" value={currentValue('oauthEnabled') as boolean} source={config.oauthEnabled?.source} onChange={handleChange} onRevert={handleRevert} />
<Toggle label="OAuth Only" description="Hide password login form when enabled" configKey="oauthOnly" value={currentValue('oauthOnly') as boolean} source={config.oauthOnly?.source} onChange={handleChange} onRevert={handleRevert} />
<Text label="OAuth Client ID" configKey="oauthClientId" value={currentValue('oauthClientId') as string} source={config.oauthClientId?.source} onChange={handleChange} onRevert={handleRevert} />
<Text label="OAuth Client Secret" configKey="oauthClientSecret" value={currentValue('oauthClientSecret') as string} source={config.oauthClientSecret?.source} onChange={handleChange} onRevert={handleRevert} type="password" />
<Text label="OAuth Client Secret" configKey="oauthClientSecret" value={currentValue('oauthClientSecret') as string} source={config.oauthClientSecret?.source} onChange={handleChange} onRevert={handleRevert} type="password" placeholder={config.oauthClientSecret?.hasValue ? '•••••••• (saved — type to replace)' : undefined} />
<Text label="OAuth Issuer URL" configKey="oauthIssuerUrl" value={currentValue('oauthIssuerUrl') as string} source={config.oauthIssuerUrl?.source} onChange={handleChange} onRevert={handleRevert} placeholder="https://auth.example.com" />
</Section>
+2 -1
View File
@@ -5,8 +5,9 @@ import { Save, Loader2, RotateCcw, ImageIcon, Upload, Trash2 } from 'lucide-reac
import { apiFetch } from '@/lib/browser-navigation';
interface ConfigEntry {
value: unknown;
value?: unknown;
source: 'admin' | 'env' | 'default';
hasValue?: boolean;
}
const IMAGE_FIELDS = [
+4 -2
View File
@@ -26,7 +26,7 @@ export function DashboardTab() {
const [status, setStatus] = useState<AdminStatus | null>(null);
const [recentActivity, setRecentActivity] = useState<AuditEntry[]>([]);
const [config, setConfig] = useState<ConfigData | null>(null);
const [, setConfigSources] = useState<Record<string, { value: unknown; source: string }> | null>(null);
const [, setConfigSources] = useState<Record<string, { value?: unknown; source: string; hasValue?: boolean }> | null>(null);
const [warnings, setWarnings] = useState<string[]>([]);
const [pluginCount, setPluginCount] = useState(0);
const [themeCount, setThemeCount] = useState(0);
@@ -96,7 +96,9 @@ export function DashboardTab() {
const sources = await adminConfigRes.json();
setConfigSources(sources);
const sessionSecret = sources?.sessionSecret;
if (!sessionSecret?.value || sessionSecret.value === 'your-secret-key-here') {
// Server redacts the raw value for sensitive keys; rely on hasValue,
// which is false when unset or matching a known placeholder default.
if (!sessionSecret?.hasValue) {
w.push('SESSION_SECRET is not set or using a default value. Sessions are insecure.');
}
const adminPassword = sources?.adminPassword;
+22 -2
View File
@@ -2,8 +2,11 @@
import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { Search, Download, Check, Loader2, Store, Puzzle, SwatchBook, Star, Eye } from 'lucide-react';
import { Search, Download, Check, Loader2, Store, Puzzle, SwatchBook, Star, Eye, AlertTriangle } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
import { isVersionSatisfied } from '@/lib/version-compare';
const CURRENT_APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || '0.0.0';
interface Extension {
slug: string;
@@ -94,6 +97,13 @@ export function MarketplaceTab() {
}, [searchInput]);
async function handleInstall(ext: Extension) {
if (ext.minAppVersion && !isVersionSatisfied(CURRENT_APP_VERSION, ext.minAppVersion)) {
setMessage({
type: 'error',
text: `"${ext.name}" requires app v${ext.minAppVersion}+. You are running v${CURRENT_APP_VERSION}.`,
});
return;
}
setInstalling(ext.slug);
setMessage(null);
@@ -258,6 +268,8 @@ function ExtensionCard({
}) {
const isPlugin = extension.type === 'plugin';
const previewHref = `/admin/marketplace/${encodeURIComponent(extension.slug)}`;
const versionMismatch = !!extension.minAppVersion
&& !isVersionSatisfied(CURRENT_APP_VERSION, extension.minAppVersion);
return (
<div className="group relative border border-border rounded-lg overflow-hidden hover:border-ring/30 transition-colors">
@@ -346,12 +358,20 @@ function ExtensionCard({
</div>
</Link>
<div className="px-4 pb-4 -mt-1">
<div className="px-4 pb-4 -mt-1 flex items-center gap-2 flex-wrap">
{extension.installed ? (
<span className="inline-flex items-center gap-1 h-7 px-2.5 rounded-md bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400 text-xs font-medium">
<Check className="w-3 h-3" />
Installed
</span>
) : versionMismatch ? (
<span
className="inline-flex items-center gap-1 h-7 px-2.5 rounded-md bg-amber-100 text-amber-800 dark:bg-amber-950/30 dark:text-amber-300 text-xs font-medium"
title={`Requires app v${extension.minAppVersion}+. You are running v${CURRENT_APP_VERSION}.`}
>
<AlertTriangle className="w-3 h-3" />
Requires v{extension.minAppVersion}+
</span>
) : (
<button
onClick={(e) => { e.preventDefault(); e.stopPropagation(); onInstall(); }}
+2 -1
View File
@@ -7,8 +7,9 @@ import { JmapServersSection } from './_jmap-servers-section';
import type { JmapServerEntry } from '@/lib/admin/jmap-servers';
interface ConfigEntry {
value: unknown;
value?: unknown;
source: 'admin' | 'env' | 'default';
hasValue?: boolean;
}
export function SettingsTab() {
+22 -16
View File
@@ -27,6 +27,7 @@ import {
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useConfig } from '@/hooks/use-config';
import { usePolicyStore } from '@/stores/policy-store';
import { useThemeStore } from '@/stores/theme-store';
import { getActiveAccountSlotHeaders } from '@/lib/auth/active-account-slot';
@@ -87,6 +88,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
const [isStalwartAdmin, setIsStalwartAdmin] = useState(false);
const [mobileNavOpen, setMobileNavOpen] = useState(false);
const { appLogoLightUrl, appLogoDarkUrl, loginLogoLightUrl, loginLogoDarkUrl } = useConfig();
const filesEnabled = usePolicyStore((s) => s.isFeatureEnabled('filesEnabled'));
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
const logoUrl = resolvedTheme === 'dark'
? (appLogoDarkUrl || appLogoLightUrl || loginLogoDarkUrl)
@@ -179,7 +181,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
// /admin lives outside the [locale] tree, so links back to the webmail
// apps are bare <a> tags (hard navigation). Next.js only auto-applies
// basePath to <Link>/router APIs for these we prepend it manually so
// basePath to <Link>/router APIs - for these we prepend it manually so
// NEXT_PUBLIC_BASE_PATH=/webmail deployments don't redirect to "/".
const prefix = getPathPrefix();
@@ -300,13 +302,15 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
>
<BookUser className="w-[18px] h-[18px]" />
</a>
<a
href={`${prefix}/files`}
className="flex items-center justify-center w-10 h-10 rounded-md transition-colors text-muted-foreground hover:text-foreground hover:bg-muted"
title="Files"
>
<HardDrive className="w-[18px] h-[18px]" />
</a>
{filesEnabled && (
<a
href={`${prefix}/files`}
className="flex items-center justify-center w-10 h-10 rounded-md transition-colors text-muted-foreground hover:text-foreground hover:bg-muted"
title="Files"
>
<HardDrive className="w-[18px] h-[18px]" />
</a>
)}
<div className="mt-auto flex flex-col items-center gap-2">
<div className="flex items-center justify-center w-10 h-10 rounded-md bg-primary/10 text-primary" title="Admin">
<Shield className="w-[18px] h-[18px]" />
@@ -440,14 +444,16 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
<BookUser className="w-5 h-5" />
<span className="text-[10px] font-medium leading-tight truncate max-w-full">Contacts</span>
</a>
<a
href={`${prefix}/files`}
className="flex flex-col items-center justify-center gap-1 py-2 px-1 min-h-[44px] grow shrink-0 basis-[64px] transition-colors duration-150 text-muted-foreground hover:text-foreground"
title="Files"
>
<HardDrive className="w-5 h-5" />
<span className="text-[10px] font-medium leading-tight truncate max-w-full">Files</span>
</a>
{filesEnabled && (
<a
href={`${prefix}/files`}
className="flex flex-col items-center justify-center gap-1 py-2 px-1 min-h-[44px] grow shrink-0 basis-[64px] transition-colors duration-150 text-muted-foreground hover:text-foreground"
title="Files"
>
<HardDrive className="w-5 h-5" />
<span className="text-[10px] font-medium leading-tight truncate max-w-full">Files</span>
</a>
)}
<div
className="flex flex-col items-center justify-center gap-1 py-2 px-1 min-h-[44px] grow shrink-0 basis-[64px] text-primary"
title="Admin"
+21 -2
View File
@@ -21,6 +21,9 @@ import {
ChevronUp,
} from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
import { isVersionSatisfied } from '@/lib/version-compare';
const CURRENT_APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || '0.0.0';
interface PreviewData {
extension: {
@@ -200,6 +203,7 @@ export default function MarketplacePreviewPage() {
const manifestPerms = (bundle.manifest?.permissions as string[] | undefined) || ext.permissions || [];
const frameOrigins = (bundle.manifest?.frameOrigins as string[] | undefined) || [];
const settingsSchema = bundle.manifest?.settingsSchema as Record<string, { type: string; label: string; description?: string; default?: unknown }> | undefined;
const versionMismatch = !!ext.minAppVersion && !isVersionSatisfied(CURRENT_APP_VERSION, ext.minAppVersion);
return (
<div className="space-y-6 max-w-4xl">
@@ -294,8 +298,11 @@ export default function MarketplacePreviewPage() {
) : (
<button
onClick={handleInstall}
disabled={installing || !!bundle.error}
className="inline-flex items-center gap-1.5 h-9 px-4 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors"
disabled={installing || !!bundle.error || versionMismatch}
title={versionMismatch
? `Requires app v${ext.minAppVersion}+. You are running v${CURRENT_APP_VERSION}. Update Bulwark to install.`
: undefined}
className="inline-flex items-center gap-1.5 h-9 px-4 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{installing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
Install
@@ -310,6 +317,18 @@ export default function MarketplacePreviewPage() {
</div>
)}
{versionMismatch && (
<div className="flex items-start gap-2 text-sm rounded-md px-3 py-2 bg-amber-50 text-amber-800 dark:bg-amber-950/30 dark:text-amber-300">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
<div>
<p className="font-medium">Update Bulwark to install this extension</p>
<p className="text-xs mt-0.5 opacity-90">
Requires app v{ext.minAppVersion}+. You are running v{CURRENT_APP_VERSION}.
</p>
</div>
</div>
)}
{bundle.error && (
<div className="flex items-start gap-2 text-sm rounded-md px-3 py-2 bg-amber-50 text-amber-800 dark:bg-amber-950/30 dark:text-amber-300">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
+25 -2
View File
@@ -2,12 +2,23 @@ import { NextRequest, NextResponse } from 'next/server';
import { configManager } from '@/lib/admin/config-manager';
import { requireAdminAuth, getClientIP } from '@/lib/admin/session';
import { auditLog } from '@/lib/admin/audit';
import { CONFIG_ENV_MAP } from '@/lib/admin/types';
import { CONFIG_ENV_MAP, SENSITIVE_CONFIG_KEYS } from '@/lib/admin/types';
import { parseJmapServers } from '@/lib/admin/jmap-servers';
import { logger } from '@/lib/logger';
// Strings that count as "no real secret configured" — used so the dashboard
// can warn about a placeholder session secret without us ever returning the
// raw value to the client.
const SENSITIVE_PLACEHOLDERS = new Set(['your-secret-key-here']);
/**
* GET /api/admin/config - Get full config with sources (admin-protected)
*
* Sensitive keys (sessionSecret, oauthClientSecret) are returned with
* `value` omitted and a `hasValue` boolean instead. An admin session is
* enough to read every other config knob; the secrets themselves stay on
* the server so that an XSS or session-theft can't lift them in one
* request and forge admin/user session cookies offline.
*/
export async function GET() {
try {
@@ -17,7 +28,19 @@ export async function GET() {
await configManager.ensureLoaded();
const config = configManager.getAllWithSources();
return NextResponse.json(config, {
const safe: Record<string, { value?: unknown; source: 'admin' | 'env' | 'default'; hasValue?: boolean }> = {};
for (const [key, entry] of Object.entries(config)) {
if (SENSITIVE_CONFIG_KEYS.has(key)) {
const v = entry.value;
const hasValue =
typeof v === 'string' && v.length > 0 && !SENSITIVE_PLACEHOLDERS.has(v);
safe[key] = { source: entry.source, hasValue };
} else {
safe[key] = entry;
}
}
return NextResponse.json(safe, {
headers: { 'Cache-Control': 'no-store' },
});
} catch (error) {
+6
View File
@@ -278,6 +278,12 @@ export async function POST(request: NextRequest) {
enabled: true,
installedAt: now,
updatedAt: now,
...(manifest.configSchema && typeof manifest.configSchema === 'object'
? { configSchema: manifest.configSchema as ServerPlugin['configSchema'] }
: {}),
...(manifest.settingsSchema && typeof manifest.settingsSchema === 'object'
? { settingsSchema: manifest.settingsSchema as ServerPlugin['settingsSchema'] }
: {}),
...(declaredFrameOrigins.length > 0
? { frameOrigins: declaredFrameOrigins }
: {}),
+141
View File
@@ -0,0 +1,141 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { encryptSession } from '@/lib/auth/crypto';
import { sessionCookieName } from '@/lib/auth/session-cookie';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
import { normalizeJmapServerUrl } from '@/lib/auth/verify-jmap-auth';
import { setStalwartAuthContextInStore } from '@/lib/stalwart/auth-context';
import { recordLogin } from '@/lib/telemetry/login-tracker';
import {
ImpersonationJwtError,
impersonationReplayCache,
verifyImpersonationJwt,
} from '@/lib/impersonation/jwt';
import {
readImpersonationConfig,
resolveImpersonationServerUrl,
} from '@/lib/impersonation/master-config';
export const runtime = 'nodejs';
const IMPERSONATION_SLOT = 0;
/**
* Impersonation cookies deliberately omit Max-Age so the browser treats
* them as session cookies — the impersonated session ends when the user
* closes the browser, not 30 days later. Impersonation is a temporary
* support handoff; a normal password login is the only thing that should
* survive a browser restart.
*/
function impersonationCookieOptions() {
const { maxAge: _maxAge, ...rest } = getCookieOptions();
return rest;
}
/**
* GET /api/auth/impersonate?token=<jwt>
*
* Master-user impersonation via signed JWT. The token carries the target
* mailbox; Bulwark verifies the signature, resolves the configured Stalwart
* master credentials from env, then mints the same session cookies the
* password-login path produces. The browser is redirected to "/" and the
* SPA hydrates as if the user had just logged in with master@target%master.
*
* Returns 404 when the feature is not configured so an unconfigured
* deployment does not advertise the endpoint.
*/
export async function GET(request: NextRequest) {
const config = readImpersonationConfig();
if (!config) {
// Not configured — behave exactly like an unknown route.
return new NextResponse('Not found', { status: 404 });
}
const token = request.nextUrl.searchParams.get('token');
if (!token) {
return NextResponse.json({ error: 'Missing token' }, { status: 400 });
}
let claims;
try {
claims = verifyImpersonationJwt(token, config.jwtSecret, {
expectedIssuer: config.expectedIssuer,
});
} catch (err) {
if (err instanceof ImpersonationJwtError) {
logger.warn('Impersonation JWT rejected', { code: err.code });
return NextResponse.json({ error: err.message }, { status: err.status });
}
logger.error('Impersonation JWT error', {
error: err instanceof Error ? err.message : 'Unknown',
});
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
if (!impersonationReplayCache.consume(claims.jti, claims.exp)) {
logger.warn('Impersonation JWT replay rejected', { jti: claims.jti });
return NextResponse.json({ error: 'Token already used' }, { status: 401 });
}
const serverUrl = await resolveImpersonationServerUrl();
if (!serverUrl) {
logger.error('Impersonation requested but jmapServerUrl is not configured');
return NextResponse.json({ error: 'JMAP server not configured' }, { status: 500 });
}
let normalizedServerUrl: string;
try {
normalizedServerUrl = normalizeJmapServerUrl(serverUrl);
} catch {
return NextResponse.json({ error: 'Invalid JMAP server URL' }, { status: 500 });
}
// Stalwart master-user impersonation: username = "<target>%<master>",
// password = <master_password>. Per Stalwart docs:
// https://stalw.art/docs/auth/authorization/administrator/
const impersonatedUsername = `${claims.mailbox}%${config.masterUser}`;
const authHeader = `Basic ${Buffer.from(
`${impersonatedUsername}:${config.masterPassword}`,
).toString('base64')}`;
const cookieStore = await cookies();
const sessionToken = encryptSession(
normalizedServerUrl,
impersonatedUsername,
config.masterPassword,
);
cookieStore.set(sessionCookieName(IMPERSONATION_SLOT), sessionToken, impersonationCookieOptions());
setStalwartAuthContextInStore(cookieStore, IMPERSONATION_SLOT, {
serverUrl: normalizedServerUrl,
username: impersonatedUsername,
authHeader,
});
// Structured audit log — operators rely on this for security review.
logger.info('Impersonation session granted', {
event: 'impersonation_granted',
jti: claims.jti,
mailbox: claims.mailbox,
tenant_id: claims.tenant_id,
actor_user_id: claims.actor_user_id,
iss: claims.iss,
ip:
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
request.headers.get('x-real-ip') ||
null,
referer: request.headers.get('referer'),
user_agent: request.headers.get('user-agent'),
});
void recordLogin(impersonatedUsername, normalizedServerUrl);
// Use a relative Location header so the browser resolves it against the
// public request URL. NextResponse.redirect(new URL('/', request.url))
// would absolutise to the container's internal bind (http://0.0.0.0:3000)
// when running behind a reverse proxy that doesn't set X-Forwarded-Host.
return new NextResponse(null, {
status: 303,
headers: { Location: '/' },
});
}
+7 -5
View File
@@ -20,10 +20,12 @@ import { recordLogin } from '@/lib/telemetry/login-tracker';
import { parseJmapServers, resolveTrustedJmapUrl } from '@/lib/admin/jmap-servers';
import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils';
const COOKIE_OPTIONS = {
...getCookieOptions(),
maxAge: SESSION_COOKIE_MAX_AGE,
};
function sessionCookieOptions() {
return {
...getCookieOptions(),
maxAge: SESSION_COOKIE_MAX_AGE,
};
}
function getSlot(request: NextRequest): number {
const raw = request.nextUrl.searchParams.get('slot');
@@ -88,7 +90,7 @@ export async function POST(request: NextRequest) {
: await verifyJmapAuth(upstreamUrl, authHeader, { trusted: false });
const token = encryptSession(normalizedServerUrl, username, password);
const cookieStore = await cookies();
cookieStore.set(cookieName, token, COOKIE_OPTIONS);
cookieStore.set(cookieName, token, sessionCookieOptions());
setStalwartAuthContextInStore(cookieStore, slot, {
serverUrl: normalizedServerUrl,
username,
+2 -2
View File
@@ -5,7 +5,7 @@ import { encryptPayload } from '@/lib/auth/crypto';
import { generateCodeVerifierServer, generateCodeChallengeServer, generateStateServer } from '@/lib/oauth/pkce-server';
import { getRequiredConfig } from '@/lib/oauth/token-exchange';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { OAUTH_SCOPES } from '@/lib/oauth/tokens';
import { getOauthScopes } from '@/lib/oauth/tokens';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
import { hasSessionSecret } from '@/lib/auth/session-secret';
@@ -73,7 +73,7 @@ export async function POST(request: NextRequest) {
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', clientId);
authUrl.searchParams.set('redirect_uri', redirect_uri);
authUrl.searchParams.set('scope', OAUTH_SCOPES);
authUrl.searchParams.set('scope', getOauthScopes());
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
+1 -1
View File
@@ -60,7 +60,7 @@ export async function POST(request: NextRequest) {
// Trusted (admin-configured) URLs skip the upstream re-fetch: the caller
// just authenticated to JMAP with these credentials, and the cookie we
// write here is only ever consumed for requests on behalf of this same
// user a bogus auth header would just yield 401s downstream, not
// user - a bogus auth header would just yield 401s downstream, not
// privilege escalation. For untrusted custom endpoints we still verify
// upstream as before.
const normalizedServerUrl = upstreamTrusted
+2
View File
@@ -3,6 +3,7 @@ import { logger } from '@/lib/logger';
import { configManager } from '@/lib/admin/config-manager';
import { parseJmapServers, redactJmapServers } from '@/lib/admin/jmap-servers';
import { hasSessionSecret } from '@/lib/auth/session-secret';
import { getOauthScopes } from '@/lib/oauth/tokens';
/**
* Runtime configuration endpoint
@@ -35,6 +36,7 @@ export async function GET() {
oauthOnly,
oauthClientId: configManager.get<string>('oauthClientId', ''),
oauthIssuerUrl: configManager.get<string>('oauthIssuerUrl', ''),
oauthScopes: getOauthScopes(),
rememberMeEnabled: hasSessionSecret(),
settingsSyncEnabled: configManager.get<boolean>('settingsSyncEnabled', false) && hasSessionSecret(),
stalwartFeaturesEnabled,
+47 -21
View File
@@ -106,15 +106,15 @@ const emails: MockEmail[] = [
// =====================================================================
{
id: 'email-001', threadId: 'thread-001', mailboxIds: { 'mb-inbox': true }, keywords: {}, size: 4200, receivedAt: daysAgo(0),
from: [{ name: 'Sophie Müller', email: 'sophie@eurotech.example' }],
from: [{ name: 'Sophie Example', email: 'sophie@eurotech.example' }],
to: [{ name: 'Dev User', email: 'dev@localhost' }], cc: [],
subject: 'Willkommen bei Bulwark Webmail!',
preview: 'Hallo! This is a sample email to help you get started with the Bulwark Webmail development environment.',
preview: 'Hallo! Welcome to Bulwark - a modern, open-source webmail client for Stalwart Mail Server, built fresh on JMAP.',
hasAttachment: false,
textBody: [{ partId: 'p1', blobId: 'blob-001', size: 280, type: 'text/plain' }],
textBody: [{ partId: 'p1', blobId: 'blob-001', size: 2200, type: 'text/plain' }],
htmlBody: [],
bodyValues: {
p1: { value: 'Hallo!\n\nThis is a sample email to help you get started with the Bulwark Webmail development environment.\n\nFeel free to explore the UI - all data here is mock data.\n\nBeste Grüße,\nSophie' },
p1: { value: 'Hallo!\n\nWelcome to Bulwark - a modern, open-source webmail client for Stalwart Mail Server, built fresh on the JMAP protocol. No PHP, no 2008 architecture, no plugin-of-plugins archaeology; just clean TypeScript and Next.js, instant push, and a UI that feels like a native app instead of a Gmail polyfill.\n\nWhy JMAP matters: one TLS connection instead of long-polling, push notifications the moment new mail arrives, batched mutations so a click never waits on three round-trips, and threading stitched on the server rather than reassembled in the browser. The result is a webmail that feels quick on a flaky train Wi-Fi and quicker on fibre.\n\nMail, calendar, contacts, and files - everything Stalwart already serves, surfaced through a single window. Threaded inbox with full-text search and Sieve filters. Month, week, day and agenda views with recurring events and iMIP invitations. Multiple address books with vCard import and export. File previews backed by Stalwart\'s JMAP FileNode storage. S/MIME, templates, keyboard shortcuts, dark mode, dozens of languages - the boring stuff that should just work, working.\n\nTwo containers behind your reverse proxy of choice is all it takes to host it yourself: Stalwart for the server side, Bulwark for the client. Caddy, Traefik, nginx - pick one, there are working examples for each. Stalwart stays the source of truth, Bulwark is what you point your browser at, and the setup wizard handles the parts that would otherwise live in a config file.\n\nIt is AGPL, the codebase is small enough to read in an afternoon, and the extension directory already hosts a growing collection of plugins and themes. If something is missing, you can fork it, file an issue, or send a patch - a person will read it.\n\nBeste Grüße,\nSophie' },
},
},
{
@@ -197,7 +197,7 @@ const emails: MockEmail[] = [
id: 'email-014', threadId: 'thread-013', mailboxIds: { 'mb-inbox': true }, keywords: {}, size: 3400, receivedAt: hoursAgo(2),
from: [{ name: 'Lars Johansson', email: 'lars.johansson@fjord-systems.example' }],
to: [{ name: 'Dev User', email: 'dev@localhost' }],
cc: [{ name: 'Sophie Müller', email: 'sophie@eurotech.example' }, { name: 'Élise Moreau', email: 'elise.moreau@fjord-systems.example' }],
cc: [{ name: 'Sophie Example', email: 'sophie@eurotech.example' }, { name: 'Élise Moreau', email: 'elise.moreau@fjord-systems.example' }],
subject: 'Sprint planning - next week priorities',
preview: 'Hej team, here are the priorities for next sprint. Please review before our planning meeting tomorrow.',
hasAttachment: false,
@@ -367,7 +367,7 @@ const emails: MockEmail[] = [
},
{
id: 'email-026', threadId: 'thread-013', mailboxIds: { 'mb-inbox': true }, keywords: {}, size: 2400, receivedAt: hoursAgo(1),
from: [{ name: 'Sophie Müller', email: 'sophie@eurotech.example' }],
from: [{ name: 'Sophie Example', email: 'sophie@eurotech.example' }],
to: [{ name: 'Lars Johansson', email: 'lars.johansson@fjord-systems.example' }],
cc: [{ name: 'Dev User', email: 'dev@localhost' }, { name: 'Élise Moreau', email: 'elise.moreau@fjord-systems.example' }],
subject: 'Re: Sprint planning - next week priorities',
@@ -471,7 +471,7 @@ const emails: MockEmail[] = [
{
id: 'email-008', threadId: 'thread-007', mailboxIds: { 'mb-sent': true }, keywords: { $seen: true }, size: 3100, receivedAt: daysAgo(5),
from: [{ name: 'Dev User', email: 'dev@localhost' }],
to: [{ name: 'Sophie Müller', email: 'sophie@eurotech.example' }], cc: [],
to: [{ name: 'Sophie Example', email: 'sophie@eurotech.example' }], cc: [],
subject: 'Design review feedback',
preview: 'Hallo Sophie, I reviewed the new mockups and have a few suggestions.',
hasAttachment: false,
@@ -485,7 +485,7 @@ const emails: MockEmail[] = [
id: 'email-027', threadId: 'thread-013', mailboxIds: { 'mb-sent': true }, keywords: { $seen: true }, size: 1900, receivedAt: hoursAgo(0.5),
from: [{ name: 'Dev User', email: 'dev@localhost' }],
to: [{ name: 'Lars Johansson', email: 'lars.johansson@fjord-systems.example' }],
cc: [{ name: 'Sophie Müller', email: 'sophie@eurotech.example' }, { name: 'Élise Moreau', email: 'elise.moreau@fjord-systems.example' }],
cc: [{ name: 'Sophie Example', email: 'sophie@eurotech.example' }, { name: 'Élise Moreau', email: 'elise.moreau@fjord-systems.example' }],
subject: 'Re: Sprint planning - next week priorities',
preview: 'Great suggestions Sophie. 10:30 works for me. I\'ll update the calendar invite.',
hasAttachment: false,
@@ -639,7 +639,7 @@ const emails: MockEmail[] = [
},
{
id: 'email-012', threadId: 'thread-011', mailboxIds: { 'mb-archive': true }, keywords: { $seen: true, $flagged: true }, size: 2600, receivedAt: daysAgo(30),
from: [{ name: 'Sophie Müller', email: 'sophie@eurotech.example' }],
from: [{ name: 'Sophie Example', email: 'sophie@eurotech.example' }],
to: [{ name: 'Dev User', email: 'dev@localhost' }], cc: [],
subject: 'Conference talk accepted!',
preview: 'Toll! Your talk proposal for the JMAP Conf has been accepted!',
@@ -728,8 +728,8 @@ const IDENTITIES = [
email: 'dev@localhost',
replyTo: null,
bcc: null,
textSignature: '-- \nDev User\nBulwark Webmail Developer',
htmlSignature: '<p>--<br>Dev User<br><em>Bulwark Webmail Developer</em></p>',
textSignature: 'Dev User\nBulwark Webmail Developer',
htmlSignature: '<p>Dev User<br><em>Bulwark Webmail Developer</em></p>',
mayDelete: false,
},
];
@@ -743,6 +743,12 @@ const addressBooks = [
{ id: 'ab-2', name: 'Arbeit / Work', isDefault: false },
];
// Profile photos served straight from randomuser.me's CDN; the API at
// https://randomuser.me/api/ also returns these portrait URLs, but for a
// fixed mock dataset we link them directly to keep things offline-friendly.
// See https://randomuser.me/documentation#howto
const PORTRAIT = (gender: 'men' | 'women', n: number) => `https://randomuser.me/api/portraits/${gender}/${n}.jpg`;
const contacts = [
// --- Personal address book ---
{ id: 'contact-001', uid: 'urn:uuid:c0000001-0000-0000-0000-000000000001', addressBookIds: { 'ab-1': true }, kind: 'individual',
@@ -752,6 +758,7 @@ const contacts = [
organizations: { o1: { name: 'EuroTech GmbH' } },
addresses: { a1: { street: [{ value: 'Kurfürstendamm 42' }], locality: 'Berlin', region: '', country: 'Germany', postcode: '10719' } },
notes: { n1: { note: 'Frontend lead. Always brings Kuchen to the office.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 14), mediaType: 'image/jpeg' } },
},
{ id: 'contact-002', uid: 'urn:uuid:c0000002-0000-0000-0000-000000000002', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Pierre' }, { kind: 'surname', value: 'Dubois' }] },
@@ -760,6 +767,7 @@ const contacts = [
organizations: { o1: { name: 'Dubois Consulting' } },
addresses: { a1: { street: [{ value: '42 Rue de Rivoli' }], locality: 'Paris', country: 'France', postcode: '75001' } },
notes: { n1: { note: 'Product manager. Knows every boulangerie in Paris.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 23), mediaType: 'image/jpeg' } },
},
{ id: 'contact-003', uid: 'urn:uuid:c0000003-0000-0000-0000-000000000003', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Chiara' }, { kind: 'surname', value: 'Rossi' }] },
@@ -768,6 +776,7 @@ const contacts = [
organizations: { o1: { name: 'Rossi Design Studio' } },
addresses: { a1: { street: [{ value: 'Via Montenapoleone 8' }], locality: 'Milano', country: 'Italy', postcode: '20121' } },
notes: { n1: { note: 'UX designer. Her risotto recipes are legendary.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 40), mediaType: 'image/jpeg' } },
},
{ id: 'contact-004', uid: 'urn:uuid:c0000004-0000-0000-0000-000000000004', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Karel' }, { kind: 'surname', value: 'de Vries' }] },
@@ -775,6 +784,7 @@ const contacts = [
phones: { p1: { number: '+31 20 555 0142' } },
addresses: { a1: { street: [{ value: 'Herengracht 142' }], locality: 'Amsterdam', country: 'Netherlands', postcode: '1015 BN' } },
notes: { n1: { note: 'Backend developer. Cycles to work rain or shine - true Dutchman.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 45), mediaType: 'image/jpeg' } },
},
{ id: 'contact-005', uid: 'urn:uuid:c0000005-0000-0000-0000-000000000005', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Lars' }, { kind: 'surname', value: 'Johansson' }] },
@@ -783,6 +793,7 @@ const contacts = [
organizations: { o1: { name: 'Fjord Systems AB' } },
addresses: { a1: { street: [{ value: 'Drottninggatan 42' }], locality: 'Stockholm', country: 'Sweden', postcode: '111 51' } },
notes: { n1: { note: 'Tech lead. FIKA is sacred. Do not schedule meetings during fika.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 61), mediaType: 'image/jpeg' } },
},
{ id: 'contact-006', uid: 'urn:uuid:c0000006-0000-0000-0000-000000000006', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Élise' }, { kind: 'surname', value: 'Moreau' }] },
@@ -791,6 +802,7 @@ const contacts = [
organizations: { o1: { name: 'Fjord Systems AB' } },
addresses: { a1: { street: [{ value: '15 Boulevard Saint-Germain' }], locality: 'Paris', country: 'France', postcode: '75005' } },
notes: { n1: { note: 'Backend dev. Remote from Paris. Once fixed a production bug from a café terrace.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 29), mediaType: 'image/jpeg' } },
},
{ id: 'contact-007', uid: 'urn:uuid:c0000007-0000-0000-0000-000000000007', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Francesco' }, { kind: 'surname', value: 'Bianchi' }] },
@@ -798,6 +810,7 @@ const contacts = [
phones: { p1: { number: '+39 06 9876 5432' } },
addresses: { a1: { street: [{ value: 'Via dei Condotti 22' }], locality: 'Roma', country: 'Italy', postcode: '00187' } },
notes: { n1: { note: 'Old university friend. Once tried to implement RFC 2549 (IP over Avian Carriers) with actual pigeons. It did not scale.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 72), mediaType: 'image/jpeg' } },
},
{ id: 'contact-008', uid: 'urn:uuid:c0000008-0000-0000-0000-000000000008', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Astrid' }, { kind: 'surname', value: 'van der Berg' }] },
@@ -806,6 +819,7 @@ const contacts = [
organizations: { o1: { name: 'BergLabs' } },
addresses: { a1: { street: [{ value: 'Prinsengracht 263' }], locality: 'Amsterdam', country: 'Netherlands', postcode: '1016 GV' } },
notes: { n1: { note: 'Solutions architect. Her whiteboard diagrams belong in a museum.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 58), mediaType: 'image/jpeg' } },
},
{ id: 'contact-009', uid: 'urn:uuid:c0000009-0000-0000-0000-000000000009', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Henrik' }, { kind: 'surname', value: 'Nielsen' }] },
@@ -814,6 +828,7 @@ const contacts = [
organizations: { o1: { name: 'Nielsen Konsult' } },
addresses: { a1: { street: [{ value: 'Nyhavn 42' }], locality: 'København', country: 'Denmark', postcode: '1051' } },
notes: { n1: { note: 'Freelance DevOps. Speaks 5 languages. Kubernetes kubectl alias: k → kansen.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 35), mediaType: 'image/jpeg' } },
},
{ id: 'contact-010', uid: 'urn:uuid:c0000010-0000-0000-0000-000000000010', addressBookIds: { 'ab-1': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Isabelle' }, { kind: 'surname', value: 'Martin' }] },
@@ -822,6 +837,7 @@ const contacts = [
organizations: { o1: { name: 'Sorbonne Université' } },
addresses: { a1: { street: [{ value: '21 Rue de l\'École de Médecine' }], locality: 'Paris', country: 'France', postcode: '75006' } },
notes: { n1: { note: 'Professor of computer science. Thesis on formal verification of email protocols.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 63), mediaType: 'image/jpeg' } },
},
// --- Work address book ---
{ id: 'contact-011', uid: 'urn:uuid:c0000011-0000-0000-0000-000000000011', addressBookIds: { 'ab-2': true }, kind: 'individual',
@@ -831,6 +847,7 @@ const contacts = [
organizations: { o1: { name: 'Lefèvre & Associés' } },
addresses: { a1: { street: [{ value: '8 Avenue de l\'Opéra' }], locality: 'Paris', country: 'France', postcode: '75001' } },
notes: { n1: { note: 'Lawyer. Specializes in IP and tech law. Always replies within 42 minutes.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 81), mediaType: 'image/jpeg' } },
},
{ id: 'contact-012', uid: 'urn:uuid:c0000012-0000-0000-0000-000000000012', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Katrin' }, { kind: 'surname', value: 'Bauer' }] },
@@ -839,6 +856,7 @@ const contacts = [
organizations: { o1: { name: 'Charité Klinik Berlin' } },
addresses: { a1: { street: [{ value: 'Charitéplatz 1' }], locality: 'Berlin', country: 'Germany', postcode: '10117' } },
notes: { n1: { note: 'Medical center admin. Organizes the best team events in Berlin.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 26), mediaType: 'image/jpeg' } },
},
{ id: 'contact-013', uid: 'urn:uuid:c0000013-0000-0000-0000-000000000013', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Liam' }, { kind: 'surname', value: 'Ó Donaill' }] },
@@ -847,6 +865,7 @@ const contacts = [
organizations: { o1: { name: 'Finanz Dublin' } },
addresses: { a1: { street: [{ value: '42 St. Stephen\'s Green' }], locality: 'Dublin', country: 'Ireland', postcode: 'D02 HX65' } },
notes: { n1: { note: 'Finance lead. Can explain SEPA regulations over a pint of Guinness.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 19), mediaType: 'image/jpeg' } },
},
{ id: 'contact-014', uid: 'urn:uuid:c0000014-0000-0000-0000-000000000014', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'María' }, { kind: 'surname', value: 'García' }] },
@@ -855,6 +874,7 @@ const contacts = [
organizations: { o1: { name: 'García Design Studio' } },
addresses: { a1: { street: [{ value: 'Calle Gran Vía 42' }], locality: 'Madrid', country: 'Spain', postcode: '28013' } },
notes: { n1: { note: 'Brand designer. Her color palettes are pure art. Siesta enthusiast.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 50), mediaType: 'image/jpeg' } },
},
{ id: 'contact-015', uid: 'urn:uuid:c0000015-0000-0000-0000-000000000015', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Nils' }, { kind: 'surname', value: 'Andersson' }] },
@@ -863,6 +883,7 @@ const contacts = [
organizations: { o1: { name: 'Digitaal BV' } },
addresses: { a1: { street: [{ value: 'Vijzelstraat 42' }], locality: 'Amsterdam', country: 'Netherlands', postcode: '1017 HK' } },
notes: { n1: { note: 'Platform engineer. fika buddy. Appreciates a good kanelbulle.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 57), mediaType: 'image/jpeg' } },
},
{ id: 'contact-016', uid: 'urn:uuid:c0000016-0000-0000-0000-000000000016', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Olivia' }, { kind: 'surname', value: 'Kowalska' }] },
@@ -871,6 +892,7 @@ const contacts = [
organizations: { o1: { name: 'Kowalska Marketing' } },
addresses: { a1: { street: [{ value: 'ul. Nowy Świat 42' }], locality: 'Warszawa', country: 'Poland', postcode: '00-363' } },
notes: { n1: { note: 'Marketing strategist. Her campaign analytics dashboards are works of art.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 71), mediaType: 'image/jpeg' } },
},
{ id: 'contact-017', uid: 'urn:uuid:c0000017-0000-0000-0000-000000000017', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Pádraig' }, { kind: 'surname', value: 'Murphy' }] },
@@ -879,6 +901,7 @@ const contacts = [
organizations: { o1: { name: 'Murphy Bau GmbH' } },
addresses: { a1: { street: [{ value: 'Grafton Street 42' }], locality: 'Dublin', country: 'Ireland', postcode: 'D02 R296' } },
notes: { n1: { note: 'Construction project manager. Irish-German bilingual. Builds things that last.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 93), mediaType: 'image/jpeg' } },
},
{ id: 'contact-018', uid: 'urn:uuid:c0000018-0000-0000-0000-000000000018', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Raquel' }, { kind: 'surname', value: 'Ferreira' }] },
@@ -887,6 +910,7 @@ const contacts = [
organizations: { o1: { name: 'Ferreira Media' } },
addresses: { a1: { street: [{ value: 'Rua Augusta 42' }], locality: 'Lisboa', country: 'Portugal', postcode: '1100-053' } },
notes: { n1: { note: 'Media consultant. Can turn any press release into poetry. Loves pastéis de nata.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 82), mediaType: 'image/jpeg' } },
},
{ id: 'contact-019', uid: 'urn:uuid:c0000019-0000-0000-0000-000000000019', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Sébastien' }, { kind: 'surname', value: 'Dumont' }] },
@@ -895,6 +919,7 @@ const contacts = [
organizations: { o1: { name: 'Dumont Conseil' } },
addresses: { a1: { street: [{ value: 'Avenue Louise 42' }], locality: 'Bruxelles', country: 'Belgium', postcode: '1050' } },
notes: { n1: { note: 'Strategy consultant. Knows the difference between Belgian and French chocolate. Will argue passionately about it.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('men', 4), mediaType: 'image/jpeg' } },
},
{ id: 'contact-020', uid: 'urn:uuid:c0000020-0000-0000-0000-000000000020', addressBookIds: { 'ab-2': true }, kind: 'individual',
name: { components: [{ kind: 'given', value: 'Annika' }, { kind: 'surname', value: 'Lindgren' }] },
@@ -904,6 +929,7 @@ const contacts = [
addresses: { a1: { street: [{ value: 'Strandvägen 42' }], locality: 'Stockholm', country: 'Sweden', postcode: '114 56' } },
nicknames: { n1: { name: 'Anni' } },
notes: { n1: { note: 'Independent consultant specializing in GDPR compliance. Yes, she has opinions about cookie banners.' } },
media: { photo1: { kind: 'photo' as const, uri: PORTRAIT('women', 36), mediaType: 'image/jpeg' } },
},
// --- Groups ---
{ id: 'contact-group-001', addressBookIds: { 'ab-1': true }, kind: 'group' as const,
@@ -976,7 +1002,7 @@ const calendarEvents = [
participants: {
p1: participant('Dev User', 'dev@localhost', 'owner'),
p2: participant('Lars Johansson', 'lars.johansson@fjord-systems.example'),
p3: participant('Sophie Müller', 'sophie@eurotech.example'),
p3: participant('Sophie Example', 'sophie@eurotech.example'),
p4: participant('Élise Moreau', 'elise.moreau@fjord-systems.example'),
},
alerts: { a1: { trigger: { '@type': 'OffsetTrigger', offset: '-PT5M', relativeTo: 'start' }, action: 'display' } },
@@ -986,7 +1012,7 @@ const calendarEvents = [
participants: {
p1: participant('Dev User', 'dev@localhost', 'owner'),
p2: participant('Lars Johansson', 'lars.johansson@fjord-systems.example'),
p3: participant('Sophie Müller', 'sophie@eurotech.example'),
p3: participant('Sophie Example', 'sophie@eurotech.example'),
p4: participant('Élise Moreau', 'elise.moreau@fjord-systems.example'),
p5: participant('Astrid van der Berg', 'astrid@berglabs.example'),
},
@@ -1024,7 +1050,7 @@ const calendarEvents = [
virtualLocations: { vl1: { uri: 'https://meet.example/eurotech', name: 'Teams' } },
participants: {
p1: participant('Dev User', 'dev@localhost', 'owner'),
p2: participant('Sophie Müller', 'sophie@eurotech.example'),
p2: participant('Sophie Example', 'sophie@eurotech.example'),
p3: participant('Pierre Dubois', 'pierre@dubois.example'),
},
description: 'Discuss API rate limit escalation for EuroTech enterprise account.',
@@ -1054,7 +1080,7 @@ const calendarEvents = [
participants: {
p1: participant('Dev User', 'dev@localhost', 'owner'),
p2: participant('Lars Johansson', 'lars.johansson@fjord-systems.example'),
p3: participant('Sophie Müller', 'sophie@eurotech.example'),
p3: participant('Sophie Example', 'sophie@eurotech.example'),
p4: participant('Élise Moreau', 'elise.moreau@fjord-systems.example'),
p5: participant('Astrid van der Berg', 'astrid@berglabs.example'),
p6: participant('Pierre Dubois', 'pierre@dubois.example'),
@@ -1066,7 +1092,7 @@ const calendarEvents = [
participants: {
p1: participant('Dev User', 'dev@localhost'),
p2: participant('María García', 'maria@garcia-design.example', 'owner'),
p3: participant('Sophie Müller', 'sophie@eurotech.example'),
p3: participant('Sophie Example', 'sophie@eurotech.example'),
},
}),
makeEvent('evt-011', 'cal-2', 'API Deprecation Deadline', localDateTime(30, 0, 0), 'P1D', {
@@ -1084,7 +1110,7 @@ const calendarEvents = [
p2: participant('Dev User', 'dev@localhost'),
p3: participant('Pierre Dubois', 'pierre@dubois.example'),
p4: participant('Chiara Rossi', 'chiara@rossi.example'),
p5: participant('Sophie Müller', 'sophie@eurotech.example'),
p5: participant('Sophie Example', 'sophie@eurotech.example'),
},
}),
makeEvent('evt-013', 'cal-3', 'Team Retro: What went well?', localDateTime(-2, 16, 0), 'PT1H', {
@@ -1093,7 +1119,7 @@ const calendarEvents = [
p1: participant('Dev User', 'dev@localhost', 'owner'),
p2: participant('Lars Johansson', 'lars.johansson@fjord-systems.example'),
p3: participant('Élise Moreau', 'elise.moreau@fjord-systems.example'),
p4: participant('Sophie Müller', 'sophie@eurotech.example'),
p4: participant('Sophie Example', 'sophie@eurotech.example'),
},
}),
makeEvent('evt-014', 'cal-3', 'Lunch & Learn: JMAP Protocol Deep Dive', localDateTime(4, 12, 0), 'PT1H', {
@@ -1109,7 +1135,7 @@ const calendarEvents = [
location: 'Sophie\'s apartment, Kreuzberg, Berlin',
description: 'Annual Eurovision Song Contest watch party!\n\nRules:\n1. Scorecards mandatory (printed copies provided)\n2. Drink when someone says "douze points"\n3. Best costume contest (prize: a waffle iron)\n4. No spoilers from the semis!\n\nBring: snacks from your home country.',
participants: {
p1: participant('Sophie Müller', 'sophie@eurotech.example', 'owner'),
p1: participant('Sophie Example', 'sophie@eurotech.example', 'owner'),
p2: participant('Dev User', 'dev@localhost'),
p3: participant('Pierre Dubois', 'pierre@dubois.example'),
p4: participant('Chiara Rossi', 'chiara@rossi.example'),
@@ -1192,7 +1218,7 @@ const calendarEvents = [
}),
// ===== Birthday calendar (cal-5) =====
makeEvent('evt-030', 'cal-5', '🎂 Sophie Müller', localDateTime(8, 0, 0), 'P1D', {
makeEvent('evt-030', 'cal-5', '🎂 Sophie Example', localDateTime(8, 0, 0), 'P1D', {
showWithoutTime: true,
recurrence: [{ frequency: 'yearly' }],
description: 'Don\'t forget to bring Kuchen!',
@@ -1220,7 +1246,7 @@ const calendarEvents = [
description: 'Your talk: "Building Modern Webmail with JMAP" - Day 1, 14:00, Main Hall.\nDon\'t forget slide deck!',
participants: {
p1: participant('Dev User', 'dev@localhost'),
p2: participant('Sophie Müller', 'sophie@eurotech.example'),
p2: participant('Sophie Example', 'sophie@eurotech.example'),
p3: participant('Isabelle Martin', 'isabelle.martin@sorbonne.example'),
},
}),
+91 -21
View File
@@ -1,10 +1,73 @@
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils';
import { readStalwartAuthContextFromStore } from '@/lib/stalwart/auth-context';
import {
getStalwartCredentials,
type StalwartCredentials,
} from '@/lib/stalwart/credentials';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
interface ResolvedTarget {
authHeader: string;
apiUrl: string;
accountId: string;
}
// When the SW passes ?accountId=, we need the slot whose JMAP session owns
// that account - not just "the first signed-in slot", which is what
// getStalwartCredentials() defaults to. Probe each candidate's session in
// parallel and return the first match.
async function resolveTargetForAccount(accountId: string): Promise<ResolvedTarget | null> {
const cookieStore = await cookies();
const probes: Promise<ResolvedTarget | null>[] = [];
for (let slot = 0; slot < MAX_ACCOUNT_SLOTS; slot++) {
const ctx = readStalwartAuthContextFromStore(cookieStore, slot);
if (!ctx) continue;
const serverUrl = ctx.serverUrl.replace(/\/+$/, '');
probes.push(
(async () => {
try {
const res = await fetch(`${serverUrl}/.well-known/jmap`, {
headers: { Authorization: ctx.authHeader },
});
if (!res.ok) return null;
const session = (await res.json()) as {
apiUrl?: string;
primaryAccounts?: Record<string, string>;
};
const mailAccountId = session.primaryAccounts?.['urn:ietf:params:jmap:mail'];
if (!session.apiUrl || !mailAccountId) return null;
if (mailAccountId !== accountId) return null;
return { authHeader: ctx.authHeader, apiUrl: session.apiUrl, accountId: mailAccountId };
} catch {
return null;
}
})(),
);
}
const results = await Promise.all(probes);
return results.find((r): r is ResolvedTarget => r !== null) ?? null;
}
async function resolveDefaultTarget(creds: StalwartCredentials): Promise<ResolvedTarget | null> {
const sessionRes = await fetch(`${creds.serverUrl}/.well-known/jmap`, {
headers: { Authorization: creds.authHeader },
});
if (!sessionRes.ok) return null;
const session = (await sessionRes.json()) as {
apiUrl?: string;
primaryAccounts?: Record<string, string>;
};
const apiUrl = session.apiUrl;
const accountId = session.primaryAccounts?.['urn:ietf:params:jmap:mail'];
if (!apiUrl || !accountId) return null;
return { authHeader: creds.authHeader, apiUrl, accountId };
}
/**
* GET /api/push/preview
*
@@ -19,31 +82,38 @@ export const dynamic = 'force-dynamic';
*/
export async function GET(request: NextRequest) {
try {
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
// SW passes ?accountId=<jmap-account-id> derived from the push payload's
// StateChange so multi-account browsers fetch from the right slot. Older
// clients (and the manual /api/push/preview probe) omit it and fall back
// to the first signed-in slot.
const requestedAccountId = request.nextUrl.searchParams.get('accountId');
let target: ResolvedTarget | null = null;
let authHeader: string;
if (requestedAccountId) {
target = await resolveTargetForAccount(requestedAccountId);
if (!target) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
authHeader = target.authHeader;
} else {
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
target = await resolveDefaultTarget(creds);
if (!target) {
return NextResponse.json({ error: 'JMAP session failed' }, { status: 502 });
}
authHeader = creds.authHeader;
}
const sessionRes = await fetch(`${creds.serverUrl}/.well-known/jmap`, {
headers: { Authorization: creds.authHeader },
});
if (!sessionRes.ok) {
return NextResponse.json({ error: 'JMAP session failed' }, { status: 502 });
}
const session = (await sessionRes.json()) as {
apiUrl?: string;
primaryAccounts?: Record<string, string>;
};
const apiUrl = session.apiUrl;
const accountId = session.primaryAccounts?.['urn:ietf:params:jmap:mail'];
if (!apiUrl || !accountId) {
return NextResponse.json({ error: 'Incomplete JMAP session' }, { status: 502 });
}
const { apiUrl, accountId } = target;
const inboxRes = await fetch(apiUrl, {
method: 'POST',
headers: {
Authorization: creds.authHeader,
Authorization: authHeader,
'Content-Type': 'application/json',
},
body: JSON.stringify({
@@ -119,7 +189,7 @@ export async function GET(request: NextRequest) {
const jmapRes = await fetch(apiUrl, {
method: 'POST',
headers: {
Authorization: creds.authHeader,
Authorization: authHeader,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
+5 -5
View File
@@ -47,14 +47,14 @@ function sanitizeFilename(name: string): string {
}
/**
* POST /api/setup/branding wizard branding upload.
* POST /api/setup/branding - wizard branding upload.
*
* Multipart form fields:
* file the image (SVG/PNG/JPEG/WebP/ICO, max 2 MB)
* slot which branding key (faviconUrl, loginLogoLightUrl, etc.)
* file - the image (SVG/PNG/JPEG/WebP/ICO, max 2 MB)
* slot - which branding key (faviconUrl, loginLogoLightUrl, etc.)
*
* Mirrors /api/admin/branding but authenticates via the wizard cookie
* instead of admin session admin auth doesn't exist yet during bootstrap.
* instead of admin session - admin auth doesn't exist yet during bootstrap.
* Files land in the same directory; the public read endpoint at
* /api/admin/branding/<filename> serves both wizard- and admin-uploaded
* assets after setup.
@@ -126,7 +126,7 @@ export async function POST(request: NextRequest) {
}
/**
* DELETE /api/setup/branding remove an uploaded asset and clear the
* DELETE /api/setup/branding - remove an uploaded asset and clear the
* config override so the slot falls back to the system default.
*
* Body: { slot: string }
+8 -5
View File
@@ -58,13 +58,16 @@ export async function POST(request: NextRequest) {
}
try {
// 1. Provision the admin account. Aborts cleanly if one already exists
// (defence in depth - should be impossible in bootstrap state).
const created = await setInitialAdminPassword(adminPassword);
// 1. Provision the admin account. An admin.json file may already exist
// from a previous ADMIN_PASSWORD env var or an aborted earlier wizard
// run while setupComplete is still false — accept the wizard's
// password as authoritative in that case. The finish route is gated
// by the bootstrap state + one-time setup token, so this is safe.
const created = await setInitialAdminPassword(adminPassword, { allowOverwrite: true });
if (!created) {
return NextResponse.json(
{ error: 'Admin account already exists; cannot finish setup again' },
{ status: 409 },
{ error: 'Failed to write admin credentials' },
{ status: 500 },
);
}
+7 -1
View File
@@ -1,4 +1,4 @@
import type { Metadata } from "next";
import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { headers } from "next/headers";
import { getLocale } from "next-intl/server";
@@ -17,6 +17,12 @@ const geistMono = Geist_Mono({
subsets: ["latin"],
});
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
viewportFit: "cover",
};
export async function generateMetadata(): Promise<Metadata> {
await configManager.ensureLoaded();
const faviconUrl = configManager.get<string>("faviconUrl", "/branding/Bulwark_Favicon.svg");
+76 -11
View File
@@ -2,7 +2,7 @@
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { CheckCircle2, AlertTriangle, AlertCircle, Server, ShieldCheck, KeyRound, FileText, Palette, Lock } from 'lucide-react';
import { CheckCircle2, AlertTriangle, AlertCircle, Server, ShieldCheck, KeyRound, FileText, Palette, Lock, ShieldAlert } from 'lucide-react';
import { apiFetch } from '@/lib/browser-navigation';
type State = 'bootstrap' | 'configured' | 'env-managed';
@@ -101,9 +101,20 @@ export default function SetupWizardPage() {
const [config, setConfig] = useState<WizardConfig>(EMPTY_CONFIG);
const [stepIndex, setStepIndex] = useState(0);
const [completed, setCompleted] = useState(false);
// Detect synchronously on first client render so we don't flash the loading
// screen before the warning appears. The session cookie is set with the
// Secure flag in production, which browsers silently drop over plain HTTP -
// every subsequent step call then 401s with "Wizard session required".
const [insecureContext] = useState<boolean>(detectInsecureContext);
// ─── Initial status load ────────────────────────────────────────────────
useEffect(() => {
// Skip the status fetch entirely when we're going to render the HTTPS
// notice - the wizard cookie can't survive an HTTP origin anyway.
if (insecureContext) {
setBootstrapping(false);
return;
}
let cancelled = false;
(async () => {
try {
@@ -141,7 +152,7 @@ export default function SetupWizardPage() {
return () => {
cancelled = true;
};
}, [router]);
}, [router, insecureContext]);
// ─── Token submit (welcome step) ────────────────────────────────────────
async function submitToken(token: string) {
@@ -173,6 +184,10 @@ export default function SetupWizardPage() {
}
// ─── Render shell ───────────────────────────────────────────────────────
if (insecureContext) {
return <InsecureContextScreen />;
}
if (bootstrapping) {
return <CenteredCard><p className="text-muted-foreground">Loading</p></CenteredCard>;
}
@@ -229,7 +244,7 @@ export default function SetupWizardPage() {
} catch (e) {
const msg = humanError(e);
setError(msg);
// Session expired mid-flow kick the user back to the
// Session expired mid-flow - kick the user back to the
// welcome step so they can re-enter the token without
// having to refresh.
if (/wizard session required/i.test(msg)) {
@@ -241,7 +256,7 @@ export default function SetupWizardPage() {
onBack={() => setStepIndex((i) => Math.max(i - 1, 1))}
onFinish={() => {
setCompleted(true);
// Hard navigation after a beat gives the user a moment
// Hard navigation after a beat - gives the user a moment
// to see the success screen and works around any router
// edge cases that swallow client-side replaces after the
// setupComplete flag flips.
@@ -347,6 +362,44 @@ function CompletedScreen() {
);
}
function InsecureContextScreen() {
const httpsUrl =
typeof window !== 'undefined'
? `https://${window.location.host}${window.location.pathname}${window.location.search}`
: '';
return (
<CenteredCard>
<div className="text-center">
<div className="mx-auto h-12 w-12 rounded-full bg-warning/15 text-warning flex items-center justify-center mb-4">
<ShieldAlert className="h-6 w-6" />
</div>
<h1 className="text-xl font-semibold">HTTPS required for setup</h1>
<p className="text-sm text-muted-foreground mt-2">
The setup wizard signs you in with a <code className="font-mono text-xs">Secure</code> cookie,
which your browser will only accept over HTTPS. Loading this page over plain HTTP causes every
step to fail with <em>Wizard session required</em>.
</p>
</div>
<div className="mt-5 text-left text-sm text-muted-foreground space-y-2">
<p className="font-medium text-foreground">To continue, do one of the following:</p>
<ul className="list-disc pl-5 space-y-1">
<li>Reach this page over HTTPS (terminate TLS on the container or a reverse proxy in front of it).</li>
<li>If you already have a reverse proxy, make sure it forwards to the webmail and forwards the
<code className="font-mono text-xs"> X-Forwarded-Proto</code> header.</li>
</ul>
</div>
{httpsUrl && (
<a
href={httpsUrl}
className="mt-6 block w-full rounded-md bg-primary text-primary-foreground text-center px-4 py-2.5 text-sm font-medium hover:bg-primary/90"
>
Open over HTTPS
</a>
)}
</CenteredCard>
);
}
function AlreadyConfiguredScreen() {
return (
<CenteredCard>
@@ -536,7 +589,7 @@ function ServerStep({ config, setConfig, onNext }: Pick<StepProps, 'config' | 's
const data = await res.json();
let entry: { status: ProbeStatus; message: string; url: string };
if (data.status === 'jmap_detected') {
entry = { status: 'jmap_detected', message: 'Connected this looks like a JMAP server.', url: config.jmapServerUrl };
entry = { status: 'jmap_detected', message: 'Connected - this looks like a JMAP server.', url: config.jmapServerUrl };
} else if (data.status === 'reachable_no_jmap') {
entry = { status: 'reachable_no_jmap', message: "We reached the server, but it doesn't look like a JMAP endpoint.", url: config.jmapServerUrl };
} else if (data.status === 'invalid_url') {
@@ -618,7 +671,7 @@ function ServerStep({ config, setConfig, onNext }: Pick<StepProps, 'config' | 's
}
if (!result) return;
// Hard-fail on these no "are you sure" since they can't be right.
// Hard-fail on these - no "are you sure" since they can't be right.
if (result.status === 'invalid_url' || result.status === 'unreachable') {
return;
}
@@ -685,7 +738,7 @@ function ServerStep({ config, setConfig, onNext }: Pick<StepProps, 'config' | 's
This URL uses plain HTTP.
</p>
<p className="text-sm text-muted-foreground mt-0.5 leading-relaxed">
Passwords and email contents will travel unencrypted between users and your server. Use <code className="font-mono text-xs">https://</code> in production terminate TLS on the mail server or a reverse proxy in front of it.
Passwords and email contents will travel unencrypted between users and your server. Use <code className="font-mono text-xs">https://</code> in production - terminate TLS on the mail server or a reverse proxy in front of it.
</p>
</div>
</div>
@@ -720,7 +773,7 @@ function ServerStep({ config, setConfig, onNext }: Pick<StepProps, 'config' | 's
onChange={(e) => setConfirmedNonJmap(e.target.checked)}
className="h-4 w-4"
/>
<span className="text-sm text-foreground">I&apos;m sure this is the right URL continue anyway.</span>
<span className="text-sm text-foreground">I&apos;m sure this is the right URL - continue anyway.</span>
</label>
</div>
) : (
@@ -1105,7 +1158,7 @@ function BrandingStep({ config, setConfig, onNext, onBack }: Pick<StepProps, 'co
<form onSubmit={handle} className="space-y-4">
<StepHeader
title="Branding"
subtitle="All fields optional. Upload a file or paste a URL defaults are used for anything you skip."
subtitle="All fields optional. Upload a file or paste a URL - defaults are used for anything you skip."
/>
<Field label="Company / organization name">
<Input value={config.loginCompanyName} onChange={(v) => setConfig({ ...config, loginCompanyName: v })} />
@@ -1174,7 +1227,7 @@ function BrandingStep({ config, setConfig, onNext, onBack }: Pick<StepProps, 'co
* One branding asset slot: shows a thumbnail preview if a value is set,
* a file picker (uploads to /api/setup/branding), and a URL field for
* operators who'd rather paste a link. Upload and URL are mutually
* compatible the URL field always reflects the persisted value.
* compatible - the URL field always reflects the persisted value.
*/
function BrandingAsset({
label,
@@ -1522,7 +1575,7 @@ function SummaryRow({ label, value, mono }: { label: string; value: string; mono
<div className="flex justify-between items-baseline gap-3 text-sm">
<span className="text-muted-foreground shrink-0">{label}</span>
<span className={'text-foreground text-right truncate min-w-0 ' + (mono ? 'font-mono text-xs' : '')}>
{value || <span className="text-muted-foreground italic"></span>}
{value || <span className="text-muted-foreground italic">-</span>}
</span>
</div>
);
@@ -1729,6 +1782,18 @@ function isInsecureHttpUrl(url: string): boolean {
return /^http:\/\//i.test(url.trim());
}
function detectInsecureContext(): boolean {
if (typeof window === 'undefined') return false;
if (window.location.protocol !== 'http:') return false;
// Browsers treat localhost/loopback as "potentially trustworthy" and accept
// Secure cookies even without TLS, so the wizard still works there.
const host = window.location.hostname;
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') {
return false;
}
return true;
}
function humanError(e: unknown): string {
if (e instanceof Error) return e.message;
if (typeof e === 'string') return e;
+47 -32
View File
@@ -388,41 +388,56 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
setActionNotice(null);
setActionError(null);
try {
const events = await client.parseCalendarEvents(client.getCalendarsAccountId(), attachment.blobId);
if (events.length > 0) {
const parsed = events[0];
setParsedEvent(parsed);
// JMAP strips parameters from Content-Type (RFC 8621), so method=REQUEST
// is lost. Fetch raw ICS to extract METHOD as a reliable fallback.
try {
const blob = await client.fetchBlob(attachment.blobId, 'invite.ics', 'text/calendar');
const rawText = await blob.text();
const icsMethod = extractMethodFromRawIcs(rawText);
if (icsMethod !== 'unknown') {
setRawIcsMethod(icsMethod);
// JMAP strips parameters from Content-Type (RFC 8621), so method=REQUEST
// is lost. Fetch raw ICS to extract METHOD as a reliable fallback — in
// parallel with parsing to save a roundtrip.
const [events, rawText] = await Promise.all([
client.parseCalendarEvents(client.getCalendarsAccountId(), attachment.blobId),
(async () => {
try {
const blob = await client.fetchBlob(attachment.blobId, 'invite.ics', 'text/calendar');
return await blob.text();
} catch {
return null;
}
} catch { /* ignore - fall back to heuristic detection */ }
})(),
]);
if (parsed.uid && supportsCalendar) {
const storeHasIt = useCalendarStore.getState().events.some((e) => e.uid === parsed.uid);
if (!storeHasIt) {
try {
const serverEvents = await client.queryCalendarEvents({});
const matching = serverEvents.filter((e) => e.uid === parsed.uid);
if (matching.length > 0) {
useCalendarStore.setState((s) => {
const existingIds = new Set(s.events.map((e) => e.id));
const newEvents = matching.filter((e) => !existingIds.has(e.id));
return newEvents.length > 0 ? { events: [...s.events, ...newEvents] } : s;
});
}
} catch { /* ignore lookup failure */ }
}
}
setState('parsed');
} else {
if (events.length === 0) {
setState('error');
return;
}
const parsed = events[0];
setParsedEvent(parsed);
if (rawText) {
const icsMethod = extractMethodFromRawIcs(rawText);
if (icsMethod !== 'unknown') {
setRawIcsMethod(icsMethod);
}
}
setState('parsed');
// Hydrate the calendar store with the matching event in the background —
// only needed for the "already in calendar" pill, must not block the banner.
// Filter by UID server-side; the previous unfiltered query fetched up to
// 1000 events plus multiple /get batches just to find one match.
if (parsed.uid && supportsCalendar) {
const storeHasIt = useCalendarStore.getState().events.some((e) => e.uid === parsed.uid);
if (!storeHasIt) {
client.queryCalendarEvents({ uid: parsed.uid })
.then((matching) => {
if (matching.length === 0) return;
useCalendarStore.setState((s) => {
const existingIds = new Set(s.events.map((e) => e.id));
const newEvents = matching.filter((e) => !existingIds.has(e.id));
return newEvents.length > 0 ? { events: [...s.events, ...newEvents] } : s;
});
})
.catch(() => { /* ignore lookup failure */ });
}
}
} catch {
setState('error');
+5 -5
View File
@@ -56,7 +56,7 @@ export interface ComposerDraftData {
mode: 'compose' | 'reply' | 'replyAll' | 'forward';
replyTo?: EmailComposerProps['replyTo'];
draftId: string | null;
/** When set, overrides the header From: sent through the selected identity's envelope. */
/** When set, overrides the header From: - sent through the selected identity's envelope. */
fromOverrideEmail?: string;
fromOverrideName?: string;
fromOverrideEnabled?: boolean;
@@ -239,7 +239,7 @@ export function EmailComposer({
// When "above quote" is configured, splice signature between the user's
// drafting area and the quoted content so it reads naturally as a
// closing for the reply body. Send-time append is skipped see
// closing for the reply body. Send-time append is skipped - see
// shouldEmbedSignatureAboveQuote.
const plainSep = signatureSeparatorEnabled ? '\n\n-- \n' : '\n\n';
const signatureBlock = shouldEmbedSignatureAboveQuote
@@ -1106,7 +1106,7 @@ export function EmailComposer({
: undefined;
// When the user has typed a From override, that becomes the header From
// (and MIME-builder From in the S/MIME path). The identity still drives
// the SMTP envelope MAIL FROM set explicitly so it doesn't mistakenly
// the SMTP envelope MAIL FROM - set explicitly so it doesn't mistakenly
// default to the override address.
const overrideActive = fromOverrideEnabled && fromOverrideEmail.trim().length > 0;
const fromEmail = overrideActive ? fromOverrideEmail.trim() : identityFromEmail;
@@ -1184,7 +1184,7 @@ export function EmailComposer({
// would produce a signature whose Subject differs from the visible
// From, which most clients reject or flag. Refuse up front.
if (overrideActive) {
throw new Error('Cannot use From override with S/MIME disable one to send.');
throw new Error('Cannot use From override with S/MIME - disable one to send.');
}
// 2. Ensure key is unlocked for signing
@@ -1793,7 +1793,7 @@ export function EmailComposer({
)}
{/* Bottom toolbar */}
<div className="flex items-center justify-between px-4 py-2.5 border-t bg-background shrink-0">
<div className="flex items-center justify-between px-4 py-2.5 border-t bg-background shrink-0 pb-[calc(env(safe-area-inset-bottom)/2)]">
{/* Left side actions */}
<div className="flex items-center gap-1">
<input
+1 -1
View File
@@ -296,7 +296,7 @@ export function EmailListItem({ email, selected, onClick, onContextMenu, onToggl
? "text-muted-foreground"
: "text-muted-foreground/80"
)}>
{trimmedPreview || "No preview available"}
{trimmedPreview || t('no_preview_available')}
</p>
)}
</>
+368 -328
View File
@@ -2489,7 +2489,7 @@ export function EmailViewer({
}
return {
html: '<p style="color: var(--color-muted-foreground);">No content available</p>',
html: `<p style="color: var(--color-muted-foreground); font-style: italic;">${t('no_body_content')}</p>`,
isHtml: false,
hasStyleTag: false,
};
@@ -2497,7 +2497,7 @@ export function EmailViewer({
// toggling permission imperatively unblocks content via restoreBlockedContent
// in an effect below, so the iframe srcDoc stays stable and doesn't reload/flash.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [email, externalContentPolicy, cidBlobUrls]);
}, [email, externalContentPolicy, cidBlobUrls, t]);
// Override email content with S/MIME decrypted content when available
const effectiveEmailContent = useMemo(() => {
@@ -2740,8 +2740,8 @@ export function EmailViewer({
// i.e. light-on-light. The second rule disables filter on bgcolor-like
// elements that are descendants of another bgcolor-like element.
const darkModeCSS = isDark && !emailHasNativeDarkMode ? `
html { background: #1a1a1a; }
body { filter: invert(1) hue-rotate(180deg); }
html { background: #121212; }
body { filter: invert(1) hue-rotate(180deg); background: #ededed; }
img, video, svg, canvas, object, embed, input[type="image"] {
filter: invert(1) hue-rotate(180deg);
}
@@ -2776,8 +2776,16 @@ export function EmailViewer({
p.MsoNormal, li.MsoNormal, div.MsoNormal { margin: 0 0 6px; }
` : '';
// Defense-in-depth CSP inside srcDoc: even if the sanitizer ever lets a
// <script> tag through, the iframe document forbids script execution
// (default-src 'none'). img/style/font remain permissive to match what the
// sanitizer is allowed to emit and what the host already permits when
// external content is loaded.
const iframeCsp = "default-src 'none'; img-src data: blob: http: https:; style-src 'unsafe-inline'; font-src data: http: https:; media-src data: blob: http: https:; base-uri 'none'; form-action 'none'; frame-src 'none'";
return `<!DOCTYPE html>
<html style="color-scheme: ${colorScheme};"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="${iframeCsp}">
<style>
body { margin: 0; padding: ${bodyPadding}; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.6; color: #1a1a1a; background: #ffffff; word-wrap: break-word; overflow-wrap: break-word; }
img { max-width: 100% !important; height: auto !important; }
@@ -2854,7 +2862,10 @@ export function EmailViewer({
// True while the new email's body is still being fetched. Catches the
// window between selectedEmail changing and isLoading flipping true, so the
// quick reply / body don't flicker through a partial render.
const isBodyLoading = isLoading || !email?.bodyValues || Object.keys(email.bodyValues).length === 0;
// An empty bodyValues with no referenced parts means the email has no body
// (e.g. calendar-only invites) — not "still loading".
const hasBodyParts = (email?.textBody?.length ?? 0) > 0 || (email?.htmlBody?.length ?? 0) > 0;
const isBodyLoading = isLoading || (hasBodyParts && (!email?.bodyValues || Object.keys(email.bodyValues).length === 0));
// Gates the quick reply on the iframe having loaded the current srcDoc, so
// it doesn't flash in below a still-resizing iframe.
@@ -4028,7 +4039,8 @@ export function EmailViewer({
)}
{/* Email Content Area */}
<div className={cn("flex-1 overflow-auto overscroll-contain bg-muted/30", isMobile && "pb-16")}>
<div className={cn("flex-1 overflow-auto overscroll-contain bg-muted/30", isMobile && "pb-[calc(3.25rem+env(safe-area-inset-bottom)/2)] sm:pb-0")}>
<div className="min-h-full flex flex-col">
{/* === SENDER INFO (Desktop) === */}
<div className="hidden lg:block bg-background border-b border-border px-6" style={{ paddingBlock: 'var(--density-header-py)' }}>
@@ -4052,13 +4064,16 @@ export function EmailViewer({
<div>
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<button
onClick={() => sender?.email && handleViewContactSidebar(null, sender.email)}
className="font-semibold text-foreground hover:text-primary hover:underline transition-colors cursor-pointer text-left"
title={t('view_contact')}
>
{sender?.name || sender?.email || t('unknown_sender')}
</button>
{sender?.email ? (
<RecipientPopover
name={sender?.name}
email={sender.email}
onViewContact={handleViewContactSidebar}
className="font-semibold text-left"
/>
) : (
<span className="font-semibold text-foreground">{t('unknown_sender')}</span>
)}
<EmailIdentityBadge email={email} identities={identities} />
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
<UnsubscribeBanner
@@ -4134,310 +4149,6 @@ export function EmailViewer({
</button>
</div>
{/* Expandable Details */}
{showFullHeaders && (() => {
const translateAuthResult = (result?: string) => {
const r = (result || '').toLowerCase();
switch (r) {
case 'pass': return t('authentication.result.pass');
case 'fail': return t('authentication.result.fail');
case 'softfail': return t('authentication.result.softfail');
case 'neutral': return t('authentication.result.neutral');
case 'permerror': return t('authentication.result.permerror');
case 'temperror': return t('authentication.result.temperror');
case 'none': return t('authentication.result.none');
default: return result || '';
}
};
const replyToDifferent = !!email.replyTo?.length &&
(!email.from || email.replyTo[0].email !== email.from[0]?.email);
const deliveryDeltaMs = email.sentAt && email.receivedAt
? Math.abs(new Date(email.receivedAt).getTime() - new Date(email.sentAt).getTime())
: 0;
const formatDelta = (diff: number) => {
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const dayUnit = days > 1 ? t('time.days') : t('time.day');
const hourUnit = (hours % 24) > 1 ? t('time.hours') : t('time.hour');
const minuteUnit = (minutes % 60) > 1 ? t('time.minutes') : t('time.minute');
const minuteUnitSingle = minutes > 1 ? t('time.minutes') : t('time.minute');
if (days > 0) return `${days} ${dayUnit} ${hours % 24} ${hourUnit}`;
if (hours > 0) return `${hours} ${hourUnit} ${minutes % 60} ${minuteUnit}`;
return `${minutes} ${minuteUnitSingle}`;
};
const fullDate = (iso?: string) => iso
? formatDateTime(iso, timeFormat, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', second: '2-digit', timeZoneName: 'short' })
: '-';
const auth = email.authenticationResults;
const totalAttachmentSize = effectiveAttachments.reduce((s, a) => s + (a.size || 0), 0);
const topMimeType = email.bodyStructure?.type;
const SectionHeader = ({ children }: { children: React.ReactNode }) => (
<div className="text-[10px] font-semibold tracking-wider text-muted-foreground uppercase mb-1.5">
{children}
</div>
);
const Row = ({ label, children, mono }: { label: string; children: React.ReactNode; mono?: boolean }) => (
<>
<dt className="text-muted-foreground text-xs pt-1">{label}</dt>
<dd className={cn(
"text-sm text-foreground min-w-0 break-words",
mono && "font-mono text-xs",
)}>{children}</dd>
</>
);
const AuthChip = ({ name, result, extra, tooltip }: { name: string; result?: string; extra?: React.ReactNode; tooltip?: string }) => {
if (!result) return null;
const status = getSecurityStatus(result);
const Icon = status.icon === 'check' ? Check
: status.icon === 'x' ? X
: status.icon === 'alert' ? AlertTriangle
: Minus;
return (
<span
className={cn(
"inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-xs",
tooltip && "cursor-help",
status.icon === 'check' && "bg-green-500/[0.07] border-green-500/30",
status.icon === 'x' && "bg-red-500/[0.07] border-red-500/30",
status.icon === 'alert' && "bg-amber-500/[0.07] border-amber-500/30",
status.icon === 'minus' && "bg-muted/40 border-border",
)}
title={tooltip}
>
<Icon className={cn("w-3.5 h-3.5 flex-shrink-0", status.color)} />
<span className="font-medium text-foreground">{name}</span>
<span className={cn("text-[10px] uppercase tracking-wider", status.color)}>
{translateAuthResult(result)}
</span>
{extra && (
<>
<span className="text-muted-foreground/50">·</span>
<span className="text-muted-foreground">{extra}</span>
</>
)}
</span>
);
};
const hasIdentifiers = !!(email.messageId || email.inReplyTo?.length || email.references?.length || email.threadId);
const hasListInfo = !!(listHeaders?.listId || listHeaders?.listUnsubscribe || listHeaders?.listHelp || listHeaders?.listPost);
const hasAuthSection = !!(auth?.spf || auth?.dkim || auth?.dmarc || auth?.iprev || email.spamScore !== undefined || email.spamLLM);
return (
<div className="mt-3 pt-3 border-t border-border grid grid-cols-1 lg:grid-cols-2 gap-x-10 gap-y-5">
<section>
<SectionHeader>{t('details.recipients_routing')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
<Row label={t('from')}>
<div className="flex flex-wrap items-center gap-1">
<RecipientPopover
name={sender?.name}
email={sender?.email || ''}
displayLabel={sender?.name && sender?.email ? `${sender.name} <${sender.email}>` : undefined}
onViewContact={handleViewContactSidebar}
className="text-sm text-left"
/>
</div>
</Row>
{replyToDifferent && (
<Row label={t('reply_to_label').replace(':', '')}>
<div className="flex flex-wrap items-center gap-1">
{email.replyTo!.map((r, i) => (
<RecipientPopover key={r.email + i} name={r.name} email={r.email} onViewContact={handleViewContactSidebar} className="text-sm" />
))}
</div>
</Row>
)}
{email.to && email.to.length > 0 && (
<Row label={t('to')}>
<div className="flex flex-wrap items-center gap-1">
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar, 100)}
</div>
</Row>
)}
{email.cc && email.cc.length > 0 && (
<Row label={t('cc')}>
<div className="flex flex-wrap items-center gap-1">
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar, 100)}
</div>
</Row>
)}
{email.bcc && email.bcc.length > 0 && (
<Row label={t('bcc')}>
<div className="flex flex-wrap items-center gap-1">
{renderClickableRecipients(email.bcc, currentUserEmail, t, handleViewContactSidebar, 100)}
</div>
</Row>
)}
{email.sentAt && (
<Row label={t('details.sent')}>{fullDate(email.sentAt)}</Row>
)}
<Row label={t('details.received')}>
{fullDate(email.receivedAt)}
{deliveryDeltaMs > 60000 && (
<span className="text-muted-foreground"> · {formatDelta(deliveryDeltaMs)} {t('details.delivery_time').toLowerCase()}</span>
)}
</Row>
</dl>
</section>
{hasAuthSection && (
<section>
<SectionHeader>{t('details.authentication_security')}</SectionHeader>
<div className="flex flex-wrap gap-1.5">
{auth?.spf && (
<AuthChip name="SPF" result={auth.spf.result} extra={auth.spf.domain} tooltip={t('authentication.tooltip_spf')} />
)}
{auth?.dkim && (
<AuthChip name="DKIM" result={auth.dkim.result} extra={auth.dkim.domain} tooltip={t('authentication.tooltip_dkim')} />
)}
{auth?.dmarc && (
<AuthChip name="DMARC" result={auth.dmarc.result} extra={auth.dmarc.policy ? `${t('authentication.policy').toLowerCase()}: ${auth.dmarc.policy}` : undefined} tooltip={t('authentication.tooltip_dmarc')} />
)}
{auth?.iprev && (
<AuthChip name={t('details.iprev')} result={auth.iprev.result} extra={auth.iprev.ip} />
)}
{email.spamScore !== undefined && (
<span className={cn(
"inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-xs",
email.spamScore > 5 ? "bg-red-500/[0.07] border-red-500/30" :
email.spamScore > 2 ? "bg-amber-500/[0.07] border-amber-500/30" :
"bg-green-500/[0.07] border-green-500/30",
)}>
<Shield className={cn(
"w-3.5 h-3.5",
email.spamScore > 5 ? "text-red-700 dark:text-red-400" :
email.spamScore > 2 ? "text-amber-700 dark:text-amber-400" :
"text-green-700 dark:text-green-400",
)} />
<span className="font-medium text-foreground">{t('authentication.spam_score')}</span>
<span className={cn(
"text-[10px] uppercase tracking-wider",
email.spamScore > 5 ? "text-red-700 dark:text-red-400" :
email.spamScore > 2 ? "text-amber-700 dark:text-amber-400" :
"text-green-700 dark:text-green-400",
)}>
{email.spamScore.toFixed(1)}
</span>
{email.spamStatus && (
<>
<span className="text-muted-foreground/50">·</span>
<span className="text-muted-foreground">{email.spamStatus}</span>
</>
)}
</span>
)}
</div>
{email.spamLLM && (
<div className="mt-2 flex items-start gap-2 text-sm">
{email.spamLLM.verdict === 'LEGITIMATE' ? <Brain className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-700 dark:text-green-400" /> :
email.spamLLM.verdict === 'SPAM' ? <ShieldAlert className="w-4 h-4 mt-0.5 flex-shrink-0 text-red-700 dark:text-red-400" /> :
<AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-700 dark:text-amber-400" />}
<div className="min-w-0">
<span className={cn(
"font-medium",
email.spamLLM.verdict === 'LEGITIMATE' ? "text-green-700 dark:text-green-400" :
email.spamLLM.verdict === 'SPAM' ? "text-red-700 dark:text-red-400" :
"text-amber-700 dark:text-amber-400",
)}>
{email.spamLLM.verdict}
</span>
<span className="text-muted-foreground"> · {email.spamLLM.explanation}</span>
</div>
</div>
)}
</section>
)}
{hasIdentifiers && (
<section>
<SectionHeader>{t('details.identifiers_threading')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
{email.messageId && (
<Row label={t('headers.message_id')} mono>{email.messageId}</Row>
)}
{email.inReplyTo && email.inReplyTo.length > 0 && (
<Row label={t('details.in_reply_to')} mono>
<div className="space-y-0.5">
{email.inReplyTo.map((id, i) => <div key={i} className="break-all">{id}</div>)}
</div>
</Row>
)}
{email.references && email.references.length > 0 && (
<Row label={t('details.references')}>
<details className="group">
<summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground transition-colors list-none flex items-center gap-1">
<ChevronDown className="w-3 h-3 group-open:rotate-180 transition-transform" />
{t(email.references.length === 1 ? 'previous_messages' : 'previous_messages_plural', { count: email.references.length })}
</summary>
<div className="mt-1 space-y-0.5 font-mono text-xs">
{email.references.map((id, i) => <div key={i} className="break-all">{id}</div>)}
</div>
</details>
</Row>
)}
{email.threadId && (
<Row label={t('details.thread_id')} mono>{email.threadId}</Row>
)}
</dl>
</section>
)}
<section>
<SectionHeader>{t('details.message_properties')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
{email.subject !== undefined && (
<Row label={t('subject')}>{email.subject || <span className="italic text-muted-foreground">{t('details.no_subject')}</span>}</Row>
)}
<Row label={t('details.size')}>
{formatFileSize(email.size)}
{topMimeType && (
<span className="text-muted-foreground"> · <span className="font-mono text-xs">{topMimeType}</span></span>
)}
</Row>
{effectiveAttachments.length > 0 && (
<Row label={t('attachments')}>
{t('details.attachments_summary', {
count: effectiveAttachments.length,
size: formatFileSize(totalAttachmentSize),
})}
</Row>
)}
{email.accountLabel && (
<Row label={t('details.account')}>{email.accountLabel}</Row>
)}
</dl>
</section>
{hasListInfo && (
<section className="lg:col-span-2">
<SectionHeader>{t('details.mailing_list')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
{listHeaders?.listId && (
<Row label={t('details.list_id')} mono>{listHeaders.listId}</Row>
)}
{listHeaders?.listUnsubscribe?.preferred && (
<Row label={t('details.list_unsubscribe')}>
<span className="break-all">
{listHeaders.listUnsubscribe.preferred === 'http'
? listHeaders.listUnsubscribe.http
: listHeaders.listUnsubscribe.mailto}
</span>
</Row>
)}
{listHeaders?.listHelp && (
<Row label={t('details.list_help')}><span className="break-all">{listHeaders.listHelp}</span></Row>
)}
{listHeaders?.listPost && (
<Row label={t('details.list_post')}><span className="break-all">{listHeaders.listPost}</span></Row>
)}
</dl>
</section>
)}
</div>
);
})()}
</div>
{/* Attachments on the right (beside-sender mode) */}
@@ -4597,12 +4308,16 @@ export function EmailViewer({
<div className="flex-1 min-w-0">
{/* Row 1: Sender name + badges */}
<div className="flex items-center gap-1.5 flex-wrap">
<button
onClick={() => sender?.email && handleViewContactSidebar(null, sender.email)}
className="text-sm font-semibold text-foreground hover:text-primary hover:underline transition-colors cursor-pointer text-left"
>
{sender?.name || sender?.email || t('unknown_sender')}
</button>
{sender?.email ? (
<RecipientPopover
name={sender?.name}
email={sender.email}
onViewContact={handleViewContactSidebar}
className="text-sm font-semibold text-left"
/>
) : (
<span className="text-sm font-semibold text-foreground">{t('unknown_sender')}</span>
)}
<EmailIdentityBadge email={email} identities={identities} />
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
<UnsubscribeBanner
@@ -4639,6 +4354,22 @@ export function EmailViewer({
)}
</>
)}
<button
onClick={() => setShowFullHeaders(!showFullHeaders)}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-0.5 transition-colors ml-1"
>
{showFullHeaders ? (
<>
<ChevronUp className="w-3 h-3" />
{t('hide_details')}
</>
) : (
<>
<ChevronDown className="w-3 h-3" />
{t('show_details')}
</>
)}
</button>
</div>
</div>
{/* Date/time + size on the right (mobile) */}
@@ -4655,6 +4386,313 @@ export function EmailViewer({
</div>
</div>
{/* Expandable Details (shared across mobile/tablet/desktop) */}
{showFullHeaders && (() => {
const translateAuthResult = (result?: string) => {
const r = (result || '').toLowerCase();
switch (r) {
case 'pass': return t('authentication.result.pass');
case 'fail': return t('authentication.result.fail');
case 'softfail': return t('authentication.result.softfail');
case 'neutral': return t('authentication.result.neutral');
case 'permerror': return t('authentication.result.permerror');
case 'temperror': return t('authentication.result.temperror');
case 'none': return t('authentication.result.none');
default: return result || '';
}
};
const replyToDifferent = !!email.replyTo?.length &&
(!email.from || email.replyTo[0].email !== email.from[0]?.email);
const deliveryDeltaMs = email.sentAt && email.receivedAt
? Math.abs(new Date(email.receivedAt).getTime() - new Date(email.sentAt).getTime())
: 0;
const formatDelta = (diff: number) => {
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const dayUnit = days > 1 ? t('time.days') : t('time.day');
const hourUnit = (hours % 24) > 1 ? t('time.hours') : t('time.hour');
const minuteUnit = (minutes % 60) > 1 ? t('time.minutes') : t('time.minute');
const minuteUnitSingle = minutes > 1 ? t('time.minutes') : t('time.minute');
if (days > 0) return `${days} ${dayUnit} ${hours % 24} ${hourUnit}`;
if (hours > 0) return `${hours} ${hourUnit} ${minutes % 60} ${minuteUnit}`;
return `${minutes} ${minuteUnitSingle}`;
};
const fullDate = (iso?: string) => iso
? formatDateTime(iso, timeFormat, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', second: '2-digit', timeZoneName: 'short' })
: '-';
const auth = email.authenticationResults;
const totalAttachmentSize = effectiveAttachments.reduce((s, a) => s + (a.size || 0), 0);
const topMimeType = email.bodyStructure?.type;
const SectionHeader = ({ children }: { children: React.ReactNode }) => (
<div className="text-[10px] font-semibold tracking-wider text-muted-foreground uppercase mb-1.5">
{children}
</div>
);
const Row = ({ label, children, mono }: { label: string; children: React.ReactNode; mono?: boolean }) => (
<>
<dt className="text-muted-foreground text-xs pt-1">{label}</dt>
<dd className={cn(
"text-sm text-foreground min-w-0 break-words",
mono && "font-mono text-xs",
)}>{children}</dd>
</>
);
const AuthChip = ({ name, result, extra, tooltip }: { name: string; result?: string; extra?: React.ReactNode; tooltip?: string }) => {
if (!result) return null;
const status = getSecurityStatus(result);
const Icon = status.icon === 'check' ? Check
: status.icon === 'x' ? X
: status.icon === 'alert' ? AlertTriangle
: Minus;
return (
<span
className={cn(
"inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-xs",
tooltip && "cursor-help",
status.icon === 'check' && "bg-green-500/[0.07] border-green-500/30",
status.icon === 'x' && "bg-red-500/[0.07] border-red-500/30",
status.icon === 'alert' && "bg-amber-500/[0.07] border-amber-500/30",
status.icon === 'minus' && "bg-muted/40 border-border",
)}
title={tooltip}
>
<Icon className={cn("w-3.5 h-3.5 flex-shrink-0", status.color)} />
<span className="font-medium text-foreground">{name}</span>
<span className={cn("text-[10px] uppercase tracking-wider", status.color)}>
{translateAuthResult(result)}
</span>
{extra && (
<>
<span className="text-muted-foreground/50">·</span>
<span className="text-muted-foreground">{extra}</span>
</>
)}
</span>
);
};
const hasIdentifiers = !!(email.messageId || email.inReplyTo?.length || email.references?.length || email.threadId);
const hasListInfo = !!(listHeaders?.listId || listHeaders?.listUnsubscribe || listHeaders?.listHelp || listHeaders?.listPost);
const hasAuthSection = !!(auth?.spf || auth?.dkim || auth?.dmarc || auth?.iprev || email.spamScore !== undefined || email.spamLLM);
return (
<div className="bg-background border-b border-border px-4 lg:px-6" style={{ paddingBlock: 'var(--density-header-py)' }}>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-x-10 gap-y-5">
<section className="min-w-0">
<SectionHeader>{t('details.recipients_routing')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
<Row label={t('from')}>
<div className="flex flex-wrap items-center gap-1">
<RecipientPopover
name={sender?.name}
email={sender?.email || ''}
displayLabel={sender?.name && sender?.email ? `${sender.name} <${sender.email}>` : undefined}
onViewContact={handleViewContactSidebar}
className="text-sm text-left"
/>
</div>
</Row>
{replyToDifferent && (
<Row label={t('reply_to_label').replace(':', '')}>
<div className="flex flex-wrap items-center gap-1">
{email.replyTo!.map((r, i) => (
<RecipientPopover key={r.email + i} name={r.name} email={r.email} onViewContact={handleViewContactSidebar} className="text-sm" />
))}
</div>
</Row>
)}
{email.to && email.to.length > 0 && (
<Row label={t('to')}>
<div className="flex flex-wrap items-center gap-1">
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar, 100)}
</div>
</Row>
)}
{email.cc && email.cc.length > 0 && (
<Row label={t('cc')}>
<div className="flex flex-wrap items-center gap-1">
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar, 100)}
</div>
</Row>
)}
{email.bcc && email.bcc.length > 0 && (
<Row label={t('bcc')}>
<div className="flex flex-wrap items-center gap-1">
{renderClickableRecipients(email.bcc, currentUserEmail, t, handleViewContactSidebar, 100)}
</div>
</Row>
)}
{email.sentAt && (
<Row label={t('details.sent')}>{fullDate(email.sentAt)}</Row>
)}
<Row label={t('details.received')}>
{fullDate(email.receivedAt)}
{deliveryDeltaMs > 60000 && (
<span className="text-muted-foreground"> · {formatDelta(deliveryDeltaMs)} {t('details.delivery_time').toLowerCase()}</span>
)}
</Row>
</dl>
</section>
{hasAuthSection && (
<section className="min-w-0">
<SectionHeader>{t('details.authentication_security')}</SectionHeader>
<div className="flex flex-wrap gap-1.5">
{auth?.spf && (
<AuthChip name="SPF" result={auth.spf.result} extra={auth.spf.domain} tooltip={t('authentication.tooltip_spf')} />
)}
{auth?.dkim && (
<AuthChip name="DKIM" result={auth.dkim.result} extra={auth.dkim.domain} tooltip={t('authentication.tooltip_dkim')} />
)}
{auth?.dmarc && (
<AuthChip name="DMARC" result={auth.dmarc.result} extra={auth.dmarc.policy ? `${t('authentication.policy').toLowerCase()}: ${auth.dmarc.policy}` : undefined} tooltip={t('authentication.tooltip_dmarc')} />
)}
{auth?.iprev && (
<AuthChip name={t('details.iprev')} result={auth.iprev.result} extra={auth.iprev.ip} />
)}
{email.spamScore !== undefined && (
<span className={cn(
"inline-flex items-center gap-1.5 px-2 py-1 rounded-md border text-xs",
email.spamScore > 5 ? "bg-red-500/[0.07] border-red-500/30" :
email.spamScore > 2 ? "bg-amber-500/[0.07] border-amber-500/30" :
"bg-green-500/[0.07] border-green-500/30",
)}>
<Shield className={cn(
"w-3.5 h-3.5",
email.spamScore > 5 ? "text-red-700 dark:text-red-400" :
email.spamScore > 2 ? "text-amber-700 dark:text-amber-400" :
"text-green-700 dark:text-green-400",
)} />
<span className="font-medium text-foreground">{t('authentication.spam_score')}</span>
<span className={cn(
"text-[10px] uppercase tracking-wider",
email.spamScore > 5 ? "text-red-700 dark:text-red-400" :
email.spamScore > 2 ? "text-amber-700 dark:text-amber-400" :
"text-green-700 dark:text-green-400",
)}>
{email.spamScore.toFixed(1)}
</span>
{email.spamStatus && (
<>
<span className="text-muted-foreground/50">·</span>
<span className="text-muted-foreground">{email.spamStatus}</span>
</>
)}
</span>
)}
</div>
{email.spamLLM && (
<div className="mt-2 flex items-start gap-2 text-sm">
{email.spamLLM.verdict === 'LEGITIMATE' ? <Brain className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-700 dark:text-green-400" /> :
email.spamLLM.verdict === 'SPAM' ? <ShieldAlert className="w-4 h-4 mt-0.5 flex-shrink-0 text-red-700 dark:text-red-400" /> :
<AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-700 dark:text-amber-400" />}
<div className="min-w-0">
<span className={cn(
"font-medium",
email.spamLLM.verdict === 'LEGITIMATE' ? "text-green-700 dark:text-green-400" :
email.spamLLM.verdict === 'SPAM' ? "text-red-700 dark:text-red-400" :
"text-amber-700 dark:text-amber-400",
)}>
{email.spamLLM.verdict}
</span>
<span className="text-muted-foreground"> · {email.spamLLM.explanation}</span>
</div>
</div>
)}
</section>
)}
{hasIdentifiers && (
<section className="min-w-0">
<SectionHeader>{t('details.identifiers_threading')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
{email.messageId && (
<Row label={t('headers.message_id')} mono>{email.messageId}</Row>
)}
{email.inReplyTo && email.inReplyTo.length > 0 && (
<Row label={t('details.in_reply_to')} mono>
<div className="space-y-0.5">
{email.inReplyTo.map((id, i) => <div key={i} className="break-all">{id}</div>)}
</div>
</Row>
)}
{email.references && email.references.length > 0 && (
<Row label={t('details.references')}>
<details className="group">
<summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground transition-colors list-none flex items-center gap-1">
<ChevronDown className="w-3 h-3 group-open:rotate-180 transition-transform" />
{t(email.references.length === 1 ? 'previous_messages' : 'previous_messages_plural', { count: email.references.length })}
</summary>
<div className="mt-1 space-y-0.5 font-mono text-xs">
{email.references.map((id, i) => <div key={i} className="break-all">{id}</div>)}
</div>
</details>
</Row>
)}
{email.threadId && (
<Row label={t('details.thread_id')} mono>{email.threadId}</Row>
)}
</dl>
</section>
)}
<section className="min-w-0">
<SectionHeader>{t('details.message_properties')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
{email.subject !== undefined && (
<Row label={t('subject')}>{email.subject || <span className="italic text-muted-foreground">{t('details.no_subject')}</span>}</Row>
)}
<Row label={t('details.size')}>
{formatFileSize(email.size)}
{topMimeType && (
<span className="text-muted-foreground"> · <span className="font-mono text-xs">{topMimeType}</span></span>
)}
</Row>
{effectiveAttachments.length > 0 && (
<Row label={t('attachments')}>
{t('details.attachments_summary', {
count: effectiveAttachments.length,
size: formatFileSize(totalAttachmentSize),
})}
</Row>
)}
{email.accountLabel && (
<Row label={t('details.account')}>{email.accountLabel}</Row>
)}
</dl>
</section>
{hasListInfo && (
<section className="lg:col-span-2 min-w-0">
<SectionHeader>{t('details.mailing_list')}</SectionHeader>
<dl className="grid grid-cols-[7rem_1fr] gap-x-4 gap-y-1.5">
{listHeaders?.listId && (
<Row label={t('details.list_id')} mono>{listHeaders.listId}</Row>
)}
{listHeaders?.listUnsubscribe?.preferred && (
<Row label={t('details.list_unsubscribe')}>
<span className="break-all">
{listHeaders.listUnsubscribe.preferred === 'http'
? listHeaders.listUnsubscribe.http
: listHeaders.listUnsubscribe.mailto}
</span>
</Row>
)}
{listHeaders?.listHelp && (
<Row label={t('details.list_help')}><span className="break-all">{listHeaders.listHelp}</span></Row>
)}
{listHeaders?.listPost && (
<Row label={t('details.list_post')}><span className="break-all">{listHeaders.listPost}</span></Row>
)}
</dl>
</section>
)}
</div>
</div>
);
})()}
{/* S/MIME Status Banner */}
{smimeStatus && (
<div className="border-b border-border bg-muted/30">
@@ -5091,13 +5129,14 @@ export function EmailViewer({
</div>
)}
<div>
<div className="grow shrink-0 flex flex-col">
{/* Email Body */}
<div className={cn(
"email-content-wrapper overflow-x-auto",
!isDark && resolvedTheme === 'dark' ? "bg-white email-content-light" : "bg-background"
)}>
)}
style={isDark ? { backgroundColor: '#121212' } : undefined}>
{isBodyLoading ? (
<div
className="space-y-3 px-6 py-4 animate-pulse"
@@ -5137,7 +5176,7 @@ export function EmailViewer({
<PluginSlot name="email-footer" />
{/* Quick Reply Section - hidden for drafts and while loading a new email */}
{!isDraft && !isBodyLoading && (effectiveEmailContent.isHtml ? iframeReady : true) && (<div className="bg-background border-t border-border px-6" style={{ paddingBlock: 'var(--density-header-py)' }}>
{!isDraft && !isBodyLoading && (effectiveEmailContent.isHtml ? iframeReady : true) && (<div className="bg-background border-t border-border px-6 mt-auto" style={{ paddingBlock: 'var(--density-header-py)' }}>
<div className="flex items-start" style={{ gap: 'var(--density-item-gap)' }}>
<div className="flex-shrink-0">
<Avatar
@@ -5232,6 +5271,7 @@ export function EmailViewer({
</div>)}
</div>
</div>
</div>
{/* Email Source Modal */}
{showSourceModal && email && (
@@ -5283,7 +5323,7 @@ export function EmailViewer({
{/* Mobile bottom action bar */}
{isMobile && (
<nav className="fixed bottom-0 left-0 right-0 z-[50] bg-background border-t border-border sm:hidden overflow-hidden">
<nav className="fixed bottom-0 left-0 right-0 z-50 bg-background border-t border-border sm:hidden overflow-hidden pb-[calc(env(safe-area-inset-bottom)/2)]">
<div className="flex items-center overflow-x-auto mobile-scroll-hidden">
<button
onClick={onNavigatePrev}
@@ -5433,4 +5473,4 @@ export function EmailViewer({
</div>
);
}
}
+1 -1
View File
@@ -127,7 +127,7 @@ export function RecipientPopover({ name, email, displayLabel, onViewContact, cla
ref={triggerRef}
onClick={handleOpen}
className={cn(
"text-foreground hover:text-primary hover:underline cursor-pointer transition-colors",
"text-foreground hover:text-primary hover:underline cursor-pointer transition-colors min-w-0 break-words",
className
)}
>
+69 -14
View File
@@ -1,6 +1,6 @@
"use client";
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import DOMPurify from "dompurify";
import { Email, ThreadGroup } from "@/lib/jmap/types";
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers, plainTextToSafeHtml } from "@/lib/email-sanitization";
@@ -440,6 +440,49 @@ function EmailCard({
return { html: "", isHtml: false };
}, [email, allowExternal, resolvedTheme, emailAlwaysLightMode, cidBlobUrls]);
// Render the sanitized HTML body inside a sandboxed iframe so a malicious
// (or accidentally-bypassed) email cannot inject styles/scripts/forms into
// the host page. CSP <meta> is defense-in-depth in case the sanitizer ever
// emits a <script> tag through a parser quirk.
const iframeRef = useRef<HTMLIFrameElement>(null);
const emailIframeSrcDoc = useMemo(() => {
if (!emailContent.isHtml || !emailContent.html) return '';
const csp = "default-src 'none'; img-src data: blob: http: https:; style-src 'unsafe-inline'; font-src data: http: https:; media-src data: blob: http: https:; base-uri 'none'; form-action 'none'; frame-src 'none'";
return `<!DOCTYPE html><html><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="${csp}">
<style>
body { margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.6; color: #1a1a1a; background: #ffffff; word-wrap: break-word; overflow-wrap: break-word; }
img { max-width: 100% !important; height: auto !important; }
a { color: #1a73e8; }
table { max-width: 100% !important; table-layout: auto; overflow-wrap: break-word; }
td, th { word-break: break-word; padding: 0.5rem; }
pre { white-space: pre-wrap; word-wrap: break-word; }
</style></head><body>${emailContent.html}</body></html>`;
}, [emailContent.isHtml, emailContent.html]);
const handleIframeLoad = useCallback(() => {
const iframe = iframeRef.current;
if (!iframe) return;
try {
const doc = iframe.contentDocument;
if (!doc?.body) return;
const resize = () => {
iframe.style.height = doc.documentElement.scrollHeight + 'px';
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(doc.body);
doc.querySelectorAll('a').forEach((a) => {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
});
} catch {
// contentDocument may be inaccessible under stricter sandboxes; ignore.
}
}, []);
return (
<div className={cn(
"rounded-lg border border-border overflow-hidden transition-all duration-200",
@@ -483,7 +526,7 @@ function EmailCard({
</div>
{!isExpanded && density !== 'extra-compact' && (
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">
{email.preview || "No preview available"}
{email.preview || t('email_viewer.no_preview_available')}
</p>
)}
</div>
@@ -534,18 +577,30 @@ function EmailCard({
{/* Email Body */}
<div style={{ padding: 'var(--density-card-p)' }}>
<div
className={cn(
"prose prose-sm max-w-none",
!emailAlwaysLightMode && "dark:prose-invert",
"prose-p:my-2 prose-headings:my-3",
"prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
"[&_table]:border-collapse [&_td]:p-2 [&_th]:p-2",
"[&_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 }}
/>
{emailContent.isHtml ? (
<iframe
ref={iframeRef}
srcDoc={emailIframeSrcDoc}
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
title="Email content"
className="w-full border-0 block"
style={{ minHeight: '60px' }}
onLoad={handleIframeLoad}
/>
) : (
<div
className={cn(
"prose prose-sm max-w-none",
!emailAlwaysLightMode && "dark:prose-invert",
"prose-p:my-2 prose-headings:my-3",
"prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
"[&_table]:border-collapse [&_td]:p-2 [&_th]:p-2",
"[&_img]:max-w-full [&_img]:h-auto"
)}
style={{ whiteSpace: 'pre-wrap', fontFamily: 'ui-monospace, "SF Mono", Consolas, monospace', fontSize: '13px' }}
dangerouslySetInnerHTML={{ __html: emailContent.html }}
/>
)}
</div>
{/* Attachments */}
+3 -1
View File
@@ -1,6 +1,7 @@
"use client";
import { useCallback } from "react";
import { useTranslations } from "next-intl";
import { formatDate } from "@/lib/utils";
import { Email } from "@/lib/jmap/types";
import { cn } from "@/lib/utils";
@@ -27,6 +28,7 @@ export function ThreadEmailItem({
onClick,
onContextMenu,
}: ThreadEmailItemProps) {
const t = useTranslations('email_viewer');
const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged;
const isAnswered = email.keywords?.$answered;
@@ -177,7 +179,7 @@ export function ThreadEmailItem({
? "text-muted-foreground"
: "text-muted-foreground/70"
)}>
{email.preview || "No preview"}
{email.preview || t('no_preview_available')}
</span>
{/* Date */}
+4 -2
View File
@@ -52,6 +52,7 @@ interface SingleEmailItemProps {
const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
function SingleEmailItem({ email, selected, onClick, onContextMenu, showPreview, colorTag, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetColorTag, onMarkAsSpam }, ref) {
const t = useTranslations('email_viewer');
const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged;
const isAnswered = email.keywords?.$answered;
@@ -317,7 +318,7 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
? "text-muted-foreground"
: "text-muted-foreground/80"
)}>
{trimmedPreview || "No preview available"}
{trimmedPreview || t('no_preview_available')}
</p>
)}
</>
@@ -360,6 +361,7 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
onMarkAsSpam,
}, ref) {
const t = useTranslations('threads');
const tEmailViewer = useTranslations('email_viewer');
const showPreview = useSettingsStore((state) => state.showPreview);
const density = useSettingsStore((state) => state.density);
const mailLayout = useSettingsStore((state) => state.mailLayout);
@@ -724,7 +726,7 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
? "text-muted-foreground"
: "text-muted-foreground/80"
)}>
{trimmedPreview || "No preview available"}
{trimmedPreview || tEmailViewer('no_preview_available')}
</p>
)}
</>
+19 -5
View File
@@ -182,7 +182,7 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }:
</div>
</div>
<div className="flex-1 flex items-center justify-center overflow-auto p-4" onClick={(e) => e.stopPropagation()}>
<div className="flex-1 flex items-center justify-center overflow-auto p-4">
{loading && (
<div className="flex flex-col items-center gap-2 text-muted-foreground">
<Loader2 className="w-8 h-8 animate-spin" />
@@ -194,13 +194,19 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }:
)}
{!loading && !error && (fileType === "text") && content !== null && (
<pre className="bg-background rounded-lg p-6 max-w-4xl w-full max-h-full overflow-auto text-sm font-mono whitespace-pre-wrap break-words">
<pre
className="bg-background rounded-lg p-6 max-w-4xl w-full max-h-full overflow-auto text-sm font-mono whitespace-pre-wrap break-words"
onClick={(e) => e.stopPropagation()}
>
{content}
</pre>
)}
{!loading && !error && fileType === "markdown" && content !== null && (
<div className="bg-background rounded-lg p-6 max-w-4xl w-full max-h-full overflow-auto text-sm">
<div
className="bg-background rounded-lg p-6 max-w-4xl w-full max-h-full overflow-auto text-sm"
onClick={(e) => e.stopPropagation()}
>
<SimpleMarkdown content={content} />
</div>
)}
@@ -211,6 +217,7 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }:
alt={name}
className="max-w-full max-h-full object-contain rounded-lg bg-background"
draggable={false}
onClick={(e) => e.stopPropagation()}
/>
)}
@@ -220,6 +227,7 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }:
sandbox=""
className="w-full max-w-5xl h-full rounded-lg bg-white"
title={name}
onClick={(e) => e.stopPropagation()}
/>
)}
@@ -229,6 +237,7 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }:
type="application/pdf"
className="w-full max-w-5xl h-full rounded-lg bg-white"
aria-label={name}
onClick={(e) => e.stopPropagation()}
>
<Button onClick={() => void onDownload()}>
<Download className="w-4 h-4 mr-2" />
@@ -238,14 +247,19 @@ export function FilePreviewModal({ name, onClose, onDownload, getFileContent }:
)}
{!loading && !error && fileType === "audio" && objectUrl && (
<div className="bg-background rounded-lg p-8 max-w-lg w-full">
<div className="bg-background rounded-lg p-8 max-w-lg w-full" onClick={(e) => e.stopPropagation()}>
<p className="text-sm font-medium mb-4 text-center">{name}</p>
<audio controls className="w-full" src={objectUrl} />
</div>
)}
{!loading && !error && fileType === "video" && objectUrl && (
<video controls className="max-w-4xl max-h-full rounded-lg" src={objectUrl} />
<video
controls
className="max-w-4xl max-h-full rounded-lg"
src={objectUrl}
onClick={(e) => e.stopPropagation()}
/>
)}
</div>
</div>
+1 -1
View File
@@ -263,7 +263,7 @@ export function IdentityForm({ identity, onSave, onCancel }: IdentityFormProps)
</label>
<textarea
id="identity-html-sig"
maxLength={5000}
maxLength={50000}
value={formData.htmlSignature}
onChange={(e) => setFormData({ ...formData, htmlSignature: e.target.value })}
rows={5}
+1 -1
View File
@@ -273,7 +273,7 @@ export function NavigationRail({
if (orientation === "horizontal") {
return (
<nav
className={cn("flex items-center bg-background border-t border-border shrink-0 overflow-x-auto mobile-scroll-hidden", className)}
className={cn("flex items-center bg-background border-t border-border shrink-0 overflow-x-auto mobile-scroll-hidden pb-[calc(env(safe-area-inset-bottom)/2)]", className)}
role="navigation"
aria-label={t("nav_label")}
>
+20
View File
@@ -20,6 +20,7 @@ import {
Folder,
FolderOpen,
User,
Users,
Palmtree,
Settings,
X,
@@ -28,6 +29,10 @@ import {
FlaskConical,
PlayCircle,
Loader2,
AlertTriangle,
NotebookPen,
CalendarClock,
BellOff,
} from "lucide-react";
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
import { Mailbox } from "@/lib/jmap/types";
@@ -88,6 +93,11 @@ const getIconForMailbox = (role?: string, name?: string, hasChildren?: boolean,
if (role === "trash" || lowerName.includes("trash") || lowerName.includes("deleted")) return Trash2;
if (role === "junk" || role === "spam" || lowerName.includes("junk") || lowerName.includes("spam")) return Ban;
if (role === "archive" || lowerName.includes("archive")) return Archive;
if (role === "shared" || lowerName.includes("shared")) return Users;
if (role === "important" || lowerName.includes("important")) return AlertTriangle;
if (role === "memos" || lowerName.includes("memo")) return NotebookPen;
if (role === "scheduled" || lowerName.includes("scheduled")) return CalendarClock;
if (role === "snoozed" || lowerName.includes("snoozed")) return BellOff;
if (lowerName.includes("star") || lowerName.includes("flag")) return Star;
if (hasChildren) {
@@ -104,6 +114,11 @@ const ROLE_ICON_COLOR: Record<string, string> = {
trash: "text-muted-foreground",
junk: "text-red-600/80 dark:text-red-400/80",
archive: "text-amber-600/80 dark:text-amber-400/80",
shared: "text-cyan-600/80 dark:text-cyan-400/80",
important: "text-orange-600/80 dark:text-orange-400/80",
memos: "text-yellow-600/80 dark:text-yellow-400/80",
scheduled: "text-sky-600/80 dark:text-sky-400/80",
snoozed: "text-slate-500/80 dark:text-slate-400/80",
};
function resolveRoleKey(role?: string, name?: string): string | undefined {
@@ -114,6 +129,11 @@ function resolveRoleKey(role?: string, name?: string): string | undefined {
if (role === "trash" || lowerName.includes("trash") || lowerName.includes("deleted")) return "trash";
if (role === "junk" || role === "spam" || lowerName.includes("junk") || lowerName.includes("spam")) return "junk";
if (role === "archive" || lowerName.includes("archive")) return "archive";
if (role === "shared" || lowerName.includes("shared")) return "shared";
if (role === "important" || lowerName.includes("important")) return "important";
if (role === "memos" || lowerName.includes("memo")) return "memos";
if (role === "scheduled" || lowerName.includes("scheduled")) return "scheduled";
if (role === "snoozed" || lowerName.includes("snoozed")) return "snoozed";
return undefined;
}
@@ -0,0 +1,16 @@
'use client';
import { PluginSlot } from '@/components/plugins/plugin-slot';
import { useAuthStore } from '@/stores/auth-store';
/**
* Mounts the `app-top-banner` plugin slot with the current session
* username + serverUrl as extraProps. Drop this at the top of every
* authenticated page so plugins like impersonation-notice render
* everywhere, not just on the mail page.
*/
export function AppTopBannerSlot() {
const username = useAuthStore((s) => s.username);
const serverUrl = useAuthStore((s) => s.serverUrl);
return <PluginSlot name="app-top-banner" extraProps={{ username, serverUrl }} />;
}
+8 -6
View File
@@ -4,13 +4,14 @@ import { useEffect, useState } from 'react';
import { NextIntlClientProvider } from 'next-intl';
import { useLocaleStore } from '@/stores/locale-store';
import csMessages from '@/locales/cs/common.json';
import daMessages from '@/locales/da/common.json';
import deMessages from '@/locales/de/common.json';
import enMessages from '@/locales/en/common.json';
import esMessages from '@/locales/es/common.json';
import frMessages from '@/locales/fr/common.json';
import itMessages from '@/locales/it/common.json';
import jaMessages from '@/locales/ja/common.json';
import koMessages from '@/locales/ko/common.json';
import esMessages from '@/locales/es/common.json';
import itMessages from '@/locales/it/common.json';
import deMessages from '@/locales/de/common.json';
import lvMessages from '@/locales/lv/common.json';
import nlMessages from '@/locales/nl/common.json';
import plMessages from '@/locales/pl/common.json';
@@ -23,13 +24,14 @@ import zhMessages from '@/locales/zh/common.json';
// Pre-loaded translations (loaded at build time, not runtime)
const ALL_MESSAGES = {
cs: csMessages,
da: daMessages,
de: deMessages,
en: enMessages,
es: esMessages,
fr: frMessages,
it: itMessages,
ja: jaMessages,
ko: koMessages,
es: esMessages,
it: itMessages,
de: deMessages,
lv: lvMessages,
nl: nlMessages,
pl: plMessages,
+15
View File
@@ -10,5 +10,20 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
initializeTheme();
}, [initializeTheme]);
useEffect(() => {
if (process.env.NODE_ENV === 'production') return;
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'l') {
e.preventDefault();
const { resolvedTheme, setTheme } = useThemeStore.getState();
setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
return <>{children}</>;
}
+8 -1
View File
@@ -67,7 +67,7 @@ export function AppearanceSettings() {
const tAdvanced = useTranslations('settings.advanced');
const tTour = useTranslations('tour');
const { theme, setTheme } = useThemeStore();
const { fontSize, density, animationsEnabled, senderFavicons, showAvatarsInJunk, updateSetting } = useSettingsStore();
const { fontSize, density, animationsEnabled, senderFavicons, showAvatarsInJunk, showOnboardingOnNewDevices, updateSetting } = useSettingsStore();
const { startTour, resetTourCompletion } = useTour();
const { isSettingLocked, isSettingHidden } = usePolicyStore();
@@ -145,6 +145,13 @@ export function AppearanceSettings() {
{tTour('restart_button')}
</Button>
</SettingItem>
<SettingItem label={tTour('show_on_new_devices_title')} description={tTour('show_on_new_devices_desc')}>
<ToggleSwitch
checked={showOnboardingOnNewDevices}
onChange={(checked) => updateSetting('showOnboardingOnNewDevices', checked)}
/>
</SettingItem>
</SettingsSection>
);
}
+6
View File
@@ -13,6 +13,7 @@ import {
Inbox, Send, FileText, Trash, ShieldAlert, Archive,
Star, Heart, Bookmark, Tag, Flag, Briefcase, Users,
Bell, Zap, Globe, Lock, Eye, MessageSquare, Mail,
AlertTriangle, NotebookPen, CalendarClock, BellOff,
type LucideIcon,
} from 'lucide-react';
import { cn, buildMailboxTree, type MailboxNode } from '@/lib/utils';
@@ -27,6 +28,11 @@ const ROLE_ICONS: Record<string, LucideIcon> = {
trash: Trash,
junk: ShieldAlert,
archive: Archive,
shared: Users,
important: AlertTriangle,
memos: NotebookPen,
scheduled: CalendarClock,
snoozed: BellOff,
};
const ICON_CHOICES: { name: string; icon: LucideIcon }[] = [
@@ -52,11 +52,14 @@ export function NotificationSettings() {
useEffect(() => {
if (!supported) return;
if (!client) return;
const accountId = client.getAccountId();
if (!accountId) return;
void (async () => {
const enabled = await isWebPushEnabled();
if (enabled) setPushStatus({ kind: 'enabled' });
const enabled = await isWebPushEnabled(accountId);
setPushStatus(enabled ? { kind: 'enabled' } : { kind: 'idle' });
})();
}, [supported]);
}, [supported, client]);
const trimmedRelay = relayUrl.trim().replace(/\/+$/, '');
const isValidRelay = /^https?:\/\/.+/i.test(trimmedRelay);
+29 -4
View File
@@ -5,6 +5,7 @@ import { useRouter, usePathname } from "@/i18n/navigation";
import { useAuthStore } from "@/stores/auth-store";
import { useCalendarStore } from "@/stores/calendar-store";
import { useWebDAVStore } from "@/stores/webdav-store";
import { useSettingsStore } from "@/stores/settings-store";
import { getTourSteps, type TourStep } from "./tour-steps";
import { TourOverlay } from "./tour-overlay";
@@ -38,6 +39,9 @@ export function TourProvider({ children }: { children: ReactNode }) {
const { isDemoMode } = useAuthStore();
const { supportsCalendar } = useCalendarStore();
const { supportsWebDAV } = useWebDAVStore();
const tourCompleted = useSettingsStore((s) => s.tourCompleted);
const showOnboardingOnNewDevices = useSettingsStore((s) => s.showOnboardingOnNewDevices);
const updateSetting = useSettingsStore((s) => s.updateSetting);
const [isActive, setIsActive] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
@@ -46,10 +50,29 @@ export function TourProvider({ children }: { children: ReactNode }) {
const steps = getTourSteps({ isDemoMode, supportsCalendar, supportsWebDAV: supportsWebDAV !== false });
useEffect(() => {
// One-time migration: if the legacy per-device flag is set but the synced
// setting isn't yet, mirror it into synced state.
try {
setHasCompletedTour(localStorage.getItem(TOUR_COMPLETED_KEY) === "true");
const legacy = localStorage.getItem(TOUR_COMPLETED_KEY) === "true";
if (legacy && !tourCompleted) {
updateSetting("tourCompleted", true);
}
} catch { /* */ }
}, []);
}, [tourCompleted, updateSetting]);
useEffect(() => {
if (!tourCompleted) {
setHasCompletedTour(false);
return;
}
if (showOnboardingOnNewDevices) {
try {
setHasCompletedTour(localStorage.getItem(TOUR_COMPLETED_KEY) === "true");
return;
} catch { /* */ }
}
setHasCompletedTour(true);
}, [tourCompleted, showOnboardingOnNewDevices]);
const startTour = useCallback(() => {
let resumeStep = 0;
@@ -85,11 +108,12 @@ export function TourProvider({ children }: { children: ReactNode }) {
const completeTour = useCallback(() => {
setIsActive(false);
setHasCompletedTour(true);
updateSetting("tourCompleted", true);
try {
localStorage.setItem(TOUR_COMPLETED_KEY, "true");
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
} catch { /* */ }
}, []);
}, [updateSetting]);
const nextStep = useCallback(() => {
if (currentStep >= steps.length - 1) {
@@ -131,11 +155,12 @@ export function TourProvider({ children }: { children: ReactNode }) {
const resetTourCompletion = useCallback(() => {
setHasCompletedTour(false);
updateSetting("tourCompleted", false);
try {
localStorage.removeItem(TOUR_COMPLETED_KEY);
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
} catch { /* */ }
}, []);
}, [updateSetting]);
const value: TourContextValue = {
isActive,
+15 -4
View File
@@ -201,15 +201,27 @@ export function FlagCS(props: FlagProps) {
);
}
/** Denmark Red with a white Nordic cross */
export function FlagDK(props: FlagProps) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 37 28" width={W} height={H} className={flagClass} {...props}>
<path fill="#C8102E" d="M0,0H37V28H0Z" />
<path stroke="#fff" strokeWidth="4" d="M0,14h37M14,0v28" />
</svg>
);
}
/** Map locale codes to flag components */
export const flagComponents: Record<string, (props: FlagProps) => ReactElement> = {
cs: FlagCS,
da: FlagDK,
de: FlagDE,
en: FlagGB,
es: FlagES,
fr: FlagFR,
it: FlagIT,
ja: FlagJP,
ko: FlagKR,
es: FlagES,
it: FlagIT,
de: FlagDE,
lv: FlagLV,
nl: FlagNL,
pl: FlagPL,
@@ -218,5 +230,4 @@ export const flagComponents: Record<string, (props: FlagProps) => ReactElement>
tr: FlagTR,
uk: FlagUA,
zh: FlagCN,
cs: FlagCS,
};
+8 -7
View File
@@ -9,20 +9,21 @@ import { flagComponents } from './flag-icons';
const languages = [
{ value: 'cs', label: 'Česky' },
{ value: 'en', label: 'English' },
{ value: 'fr', label: 'Français' },
{ value: 'ja', label: '日本語' },
{ value: 'ko', label: '한국어' },
{ value: 'es', label: 'Español' },
{ value: 'it', label: 'Italiano' },
{ value: 'da', label: 'Dansk' },
{ value: 'de', label: 'Deutsch' },
{ value: 'en', label: 'English' },
{ value: 'es', label: 'Español' },
{ value: 'fr', label: 'Français' },
{ value: 'it', label: 'Italiano' },
{ value: 'lv', label: 'Latviešu' },
{ value: 'nl', label: 'Nederlands' },
{ value: 'pl', label: 'Polski' },
{ value: 'pt', label: 'Português' },
{ value: 'ru', label: 'Русский' },
{ value: 'tr', label: 'Türkçe' },
{ value: 'ru', label: 'Русский' },
{ value: 'uk', label: 'Українська' },
{ value: 'ko', label: '한국어' },
{ value: 'ja', label: '日本語' },
{ value: 'zh', label: '简体中文' },
];
+29 -4
View File
@@ -6,6 +6,7 @@ import { X, Lightbulb, Settings, PlayCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useRouter } from "@/i18n/navigation";
import { useTour } from "@/components/tour/tour-provider";
import { useSettingsStore } from "@/stores/settings-store";
const ONBOARDING_KEY = "onboarding_completed";
@@ -13,23 +14,47 @@ export function WelcomeBanner() {
const t = useTranslations("welcome");
const router = useRouter();
const { startTour } = useTour();
const onboardingCompleted = useSettingsStore((s) => s.onboardingCompleted);
const showOnboardingOnNewDevices = useSettingsStore((s) => s.showOnboardingOnNewDevices);
const updateSetting = useSettingsStore((s) => s.updateSetting);
const [visible, setVisible] = useState(false);
const [dismissed, setDismissed] = useState(false);
useEffect(() => {
// One-time migration: if the legacy per-device flag is set but the synced
// setting isn't yet, mirror it into synced state so the user isn't shown
// the banner again on this device after the upgrade.
try {
if (!localStorage.getItem(ONBOARDING_KEY)) {
setVisible(true);
const legacy = localStorage.getItem(ONBOARDING_KEY) === "true";
if (legacy && !onboardingCompleted) {
updateSetting("onboardingCompleted", true);
}
} catch { /* localStorage unavailable */ }
}, []);
}, [onboardingCompleted, updateSetting]);
useEffect(() => {
if (!onboardingCompleted) {
setVisible(true);
return;
}
if (showOnboardingOnNewDevices) {
try {
if (localStorage.getItem(ONBOARDING_KEY) !== "true") {
setVisible(true);
return;
}
} catch { /* localStorage unavailable */ }
}
setVisible(false);
}, [onboardingCompleted, showOnboardingOnNewDevices]);
const dismiss = useCallback(() => {
setDismissed(true);
updateSetting("onboardingCompleted", true);
try {
localStorage.setItem(ONBOARDING_KEY, "true");
} catch { /* localStorage unavailable */ }
}, []);
}, [updateSetting]);
useEffect(() => {
if (!visible) return;
+2 -2
View File
@@ -66,7 +66,7 @@ export function useAttachmentDrag(
urlRef.current = url;
// Mark as owned so we revoke on unmount. Callers that hand back a
// shared URL (e.g. a cached thumbnail blob URL) can return the same
// string each time we still revoke once on unmount.
// string each time - we still revoke once on unmount.
ownedRef.current = true;
}
return url;
@@ -101,7 +101,7 @@ export function useAttachmentDrag(
);
const handleDragEnd = useCallback(() => {
// Keep the blob URL around briefly Chromium asynchronously fetches the
// Keep the blob URL around briefly - Chromium asynchronously fetches the
// blob: URL after dragend fires, so revoking immediately races the OS.
if (urlRef.current && ownedRef.current) {
const url = urlRef.current;
+4
View File
@@ -12,6 +12,7 @@ interface ConfigData {
oauthOnly: boolean;
oauthClientId: string;
oauthIssuerUrl: string;
oauthScopes: string;
rememberMeEnabled: boolean;
settingsSyncEnabled: boolean;
stalwartFeaturesEnabled: boolean;
@@ -90,6 +91,7 @@ export function useConfig(): AppConfig {
oauthOnly: configCache?.oauthOnly || false,
oauthClientId: configCache?.oauthClientId || '',
oauthIssuerUrl: configCache?.oauthIssuerUrl || '',
oauthScopes: configCache?.oauthScopes || '',
rememberMeEnabled: configCache?.rememberMeEnabled || false,
settingsSyncEnabled: configCache?.settingsSyncEnabled || false,
stalwartFeaturesEnabled: configCache?.stalwartFeaturesEnabled ?? true,
@@ -124,6 +126,7 @@ export function useConfig(): AppConfig {
oauthOnly: configCache.oauthOnly,
oauthClientId: configCache.oauthClientId,
oauthIssuerUrl: configCache.oauthIssuerUrl,
oauthScopes: configCache.oauthScopes,
rememberMeEnabled: configCache.rememberMeEnabled,
settingsSyncEnabled: configCache.settingsSyncEnabled,
stalwartFeaturesEnabled: configCache.stalwartFeaturesEnabled,
@@ -159,6 +162,7 @@ export function useConfig(): AppConfig {
oauthOnly: data.oauthOnly,
oauthClientId: data.oauthClientId,
oauthIssuerUrl: data.oauthIssuerUrl,
oauthScopes: data.oauthScopes,
rememberMeEnabled: data.rememberMeEnabled,
settingsSyncEnabled: data.settingsSyncEnabled,
stalwartFeaturesEnabled: data.stalwartFeaturesEnabled,
+5 -2
View File
@@ -14,8 +14,8 @@ export default getRequestConfig(async ({ requestLocale }) => {
case 'cs':
messages = (await import('../locales/cs/common.json')).default;
break;
case 'fr':
messages = (await import('../locales/fr/common.json')).default;
case 'da':
messages = (await import('../locales/da/common.json')).default;
break;
case 'de':
messages = (await import('../locales/de/common.json')).default;
@@ -23,6 +23,9 @@ export default getRequestConfig(async ({ requestLocale }) => {
case 'es':
messages = (await import('../locales/es/common.json')).default;
break;
case 'fr':
messages = (await import('../locales/fr/common.json')).default;
break;
case 'it':
messages = (await import('../locales/it/common.json')).default;
break;
+1 -1
View File
@@ -13,7 +13,7 @@ const localePrefix = (process.env.NEXT_PUBLIC_LOCALE_PREFIX ?? 'never') as
| 'as-needed';
export const routing = defineRouting({
locales: ['cs', 'en', 'fr', 'de', 'es', 'it', 'ja', 'ko', 'lv', 'nl', 'pl', 'pt', 'ru', 'tr', 'uk', 'zh'],
locales: ['cs', 'da', 'de', 'en', 'es', 'fr', 'it', 'ja', 'ko', 'lv', 'nl', 'pl', 'pt', 'ru', 'tr', 'uk', 'zh'],
defaultLocale: 'en',
localePrefix
});
+65 -8
View File
@@ -78,11 +78,67 @@ describe('email-sanitization', () => {
expect(clean).toContain('John Doe');
});
it('should remove images from signatures', () => {
const signature = '<p>John</p><img src="logo.png" alt="Logo">';
it('should allow img with https src', () => {
const signature = '<p>John</p><img src="https://cdn.example.com/logo.png" alt="Logo" width="120" height="40">';
const clean = sanitizeSignatureHtml(signature);
expect(clean).toContain('<img');
expect(clean).toContain('src="https://cdn.example.com/logo.png"');
expect(clean).toContain('alt="Logo"');
expect(clean).toContain('width="120"');
expect(clean).toContain('height="40"');
});
it('should allow img with data:image/png;base64 src', () => {
const dataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/AAAZ4gk3AAAAAXRSTlPM0jRW/QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAA1JREFUCNdjYGBgAAAABAABc7Rs9wAAAABJRU5ErkJggg==';
const signature = `<img src="${dataUri}" alt="Logo">`;
const clean = sanitizeSignatureHtml(signature);
expect(clean).toContain('<img');
expect(clean).toContain('data:image/png;base64,');
});
it('should allow img with data:image/jpeg, gif, webp', () => {
const cases = ['data:image/jpeg;base64,AAA', 'data:image/jpg;base64,AAA', 'data:image/gif;base64,AAA', 'data:image/webp;base64,AAA'];
for (const src of cases) {
const clean = sanitizeSignatureHtml(`<img src="${src}" alt="x">`);
expect(clean).toContain('<img');
expect(clean).toContain(src);
}
});
it('should strip img with http: src (https only)', () => {
const signature = '<img src="http://insecure.example.com/logo.png" alt="Logo">';
const clean = sanitizeSignatureHtml(signature);
expect(clean).not.toContain('http://insecure.example.com');
expect(clean).not.toContain('<img');
expect(clean).toContain('John');
});
it('should strip img with javascript: src', () => {
const signature = '<img src="javascript:alert(1)" alt="x">';
const clean = sanitizeSignatureHtml(signature);
expect(clean).not.toContain('javascript:');
expect(clean).not.toContain('<img');
});
it('should strip img with data:image/svg+xml src (SVG forbidden)', () => {
const signature = '<img src="data:image/svg+xml;base64,PHN2Zy8+" alt="x">';
const clean = sanitizeSignatureHtml(signature);
expect(clean).not.toContain('data:image/svg');
expect(clean).not.toContain('<img');
});
it('should strip img with non-image data: URI', () => {
const signature = '<img src="data:text/html;base64,PHA+aGk8L3A+" alt="x">';
const clean = sanitizeSignatureHtml(signature);
expect(clean).not.toContain('data:text/html');
expect(clean).not.toContain('<img');
});
it('should strip event handlers on img', () => {
const signature = '<img src="https://cdn.example.com/logo.png" alt="x" onerror="alert(1)" onload="alert(2)">';
const clean = sanitizeSignatureHtml(signature);
expect(clean).not.toContain('onerror');
expect(clean).not.toContain('onload');
expect(clean).toContain('https://cdn.example.com/logo.png');
});
it('should remove video and audio tags', () => {
@@ -113,16 +169,17 @@ describe('email-sanitization', () => {
});
it('should be stricter than email sanitization', () => {
const html = '<p>Text</p><img src="pic.jpg"><table><tr><td>Data</td></tr></table>';
const html = '<p>Text</p><table><tr><td>Data</td></tr></table><video src="v.mp4"></video>';
const emailClean = sanitizeEmailHtml(html);
const signatureClean = sanitizeSignatureHtml(html);
// Email allows img and table
expect(emailClean).toContain('<img');
// Email allows table
expect(emailClean).toContain('<table>');
// Signature blocks img but may allow some tables (verify in implementation)
expect(signatureClean).not.toContain('<img');
// Signature blocks table and video
expect(signatureClean).not.toContain('<table');
expect(signatureClean).not.toContain('<video');
expect(signatureClean).toContain('Text');
});
});
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it, beforeEach } from 'vitest';
import { createHmac } from 'node:crypto';
import {
ImpersonationJwtError,
verifyImpersonationJwt,
impersonationReplayCache,
} from '@/lib/impersonation/jwt';
const SECRET = 'a'.repeat(64);
const ISSUER = 'platform-api/webmail';
function base64Url(input: Buffer | string): string {
return Buffer.from(input)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
function sign(payload: Record<string, unknown>, secret: string = SECRET, header: Record<string, unknown> = { alg: 'HS256', typ: 'JWT' }): string {
const h = base64Url(JSON.stringify(header));
const p = base64Url(JSON.stringify(payload));
const sig = createHmac('sha256', secret).update(`${h}.${p}`).digest();
return `${h}.${p}.${base64Url(sig)}`;
}
function basePayload(overrides: Partial<Record<string, unknown>> = {}): Record<string, unknown> {
const now = Math.floor(Date.now() / 1000);
return {
iss: ISSUER,
iat: now,
exp: now + 120,
jti: 'jti-' + Math.random().toString(36).slice(2),
mailbox: 'alice@example.test',
...overrides,
};
}
describe('verifyImpersonationJwt', () => {
beforeEach(() => {
impersonationReplayCache.clear();
});
it('accepts a valid HS256 token', () => {
const token = sign(basePayload());
const claims = verifyImpersonationJwt(token, SECRET, { expectedIssuer: ISSUER });
expect(claims.mailbox).toBe('alice@example.test');
});
it('rejects non-HS256 algorithms', () => {
const header = { alg: 'none', typ: 'JWT' };
const h = base64Url(JSON.stringify(header));
const p = base64Url(JSON.stringify(basePayload()));
const token = `${h}.${p}.`;
expect(() => verifyImpersonationJwt(token, SECRET)).toThrow(ImpersonationJwtError);
});
it('rejects tokens with a forged signature', () => {
const token = sign(basePayload(), 'a-different-secret-that-is-also-long-enough-32');
expect(() => verifyImpersonationJwt(token, SECRET)).toThrowError(/signature/i);
});
it('rejects when secret is too short', () => {
const token = sign(basePayload());
expect(() => verifyImpersonationJwt(token, 'short')).toThrowError(/32 characters/);
});
it('rejects expired tokens', () => {
const now = Math.floor(Date.now() / 1000);
const token = sign(basePayload({ iat: now - 600, exp: now - 300 }));
expect(() => verifyImpersonationJwt(token, SECRET)).toThrowError(/expired/i);
});
it('rejects tokens with lifetime over the 300s ceiling', () => {
const now = Math.floor(Date.now() / 1000);
const token = sign(basePayload({ iat: now, exp: now + 3600 }));
expect(() => verifyImpersonationJwt(token, SECRET)).toThrowError(/lifetime/i);
});
it('rejects tokens with iss mismatch when expectedIssuer is set', () => {
const token = sign(basePayload({ iss: 'someone-else' }));
expect(() =>
verifyImpersonationJwt(token, SECRET, { expectedIssuer: ISSUER }),
).toThrowError(/issuer/i);
});
it("rejects mailbox containing '%'", () => {
const token = sign(basePayload({ mailbox: 'a%b@example.test' }));
expect(() => verifyImpersonationJwt(token, SECRET)).toThrowError(/'%'/);
});
it("rejects mailbox containing ':'", () => {
const token = sign(basePayload({ mailbox: 'a:b@example.test' }));
expect(() => verifyImpersonationJwt(token, SECRET)).toThrowError(/':'/);
});
it('rejects malformed tokens', () => {
expect(() => verifyImpersonationJwt('not.a.jwt.extra', SECRET)).toThrow();
expect(() => verifyImpersonationJwt('', SECRET)).toThrow();
});
it('honours nbf with skew', () => {
const now = Math.floor(Date.now() / 1000);
const token = sign(basePayload({ nbf: now + 600 }));
expect(() => verifyImpersonationJwt(token, SECRET)).toThrowError(/not yet valid/i);
});
});
describe('impersonationReplayCache', () => {
beforeEach(() => {
impersonationReplayCache.clear();
});
it('accepts a jti once and rejects it on second use', () => {
const now = Math.floor(Date.now() / 1000);
expect(impersonationReplayCache.consume('jti-1', now + 60, now)).toBe(true);
expect(impersonationReplayCache.consume('jti-1', now + 60, now)).toBe(false);
});
it('prunes expired jtis on next consume', () => {
const now = Math.floor(Date.now() / 1000);
impersonationReplayCache.consume('jti-old', now - 600, now - 600);
// Far in the future — pruning should clear the old entry.
expect(impersonationReplayCache.consume('jti-new', now + 60, now + 1000)).toBe(true);
// Re-using the old jti is allowed after pruning (security irrelevant since
// the token would fail signature/exp validation upstream).
expect(impersonationReplayCache.consume('jti-old', now + 60, now + 1000)).toBe(true);
});
});
+1
View File
@@ -44,6 +44,7 @@ function resetStore() {
plugins: [],
slots: {
'toolbar-actions': [],
'app-top-banner': [],
'email-banner': [],
'email-footer': [],
'composer-toolbar': [],
+252
View File
@@ -481,6 +481,258 @@ describe("round-trip: parse → generate → parse", () => {
});
});
describe("vCard 4.0 parsing (issue #289)", () => {
it("strips group prefix from property names (item1.EMAIL)", () => {
// Evolution / Apple Contacts emit grouped properties so an X-ABLABEL line
// can attach a label. We must still parse the EMAIL itself.
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Ada Lovelace",
"item1.EMAIL:ada@example.com",
"item1.X-ABLABEL:Personal",
"item2.TEL:tel:+1-555-0100",
"item2.X-ABLABEL:Mobile",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(result).toHaveLength(1);
const card = result[0];
expect(card.emails?.e0?.address).toBe("ada@example.com");
expect(card.phones?.p0?.number).toBe("+1-555-0100");
});
it("strips tel:/mailto: URI scheme from TEL/EMAIL values", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Alan Turing",
"EMAIL:mailto:alan@example.com",
"TEL;VALUE=uri:tel:+44-20-1234-5678",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(result[0].emails?.e0?.address).toBe("alan@example.com");
expect(result[0].phones?.p0?.number).toBe("+44-20-1234-5678");
});
it("maps PREF=n parameter to pref field", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Grace Hopper",
"EMAIL;PREF=1:grace@home.example",
"EMAIL;PREF=2:grace@work.example",
"TEL;PREF=1:+1-555-9999",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(result[0].emails?.e0?.pref).toBe(1);
expect(result[0].emails?.e1?.pref).toBe(2);
expect(result[0].phones?.p0?.pref).toBe(1);
});
it("decodes RFC 6868 caret-encoded parameter values", () => {
// ^n → LF, ^^ → ^, ^' → DQUOTE
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Test",
'ADR;LABEL="Line 1^nLine 2";TYPE=HOME:;;Sub St;Town;;;US',
"EMAIL:t@example.com",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(result[0].addresses?.a0?.fullAddress).toBe("Line 1\nLine 2");
expect(result[0].addresses?.a0?.contexts).toEqual({ private: true });
});
it("survives quoted parameter values containing semicolons", () => {
// Without quote-aware param splitting, the ; inside LABEL would shred
// the param list and the ADR would lose its TYPE.
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Lev",
'ADR;LABEL="Building A; Suite 12";TYPE=WORK:;;1 Plaza;NYC;NY;10001;US',
"EMAIL:lev@example.com",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(result[0].addresses?.a0?.fullAddress).toBe("Building A; Suite 12");
expect(result[0].addresses?.a0?.contexts).toEqual({ work: true });
expect(result[0].addresses?.a0?.locality).toBe("NYC");
});
it("parses BIRTHPLACE and DEATHPLACE (RFC 6474)", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Marie Curie",
"BDAY:18671107",
"BIRTHPLACE:Warsaw\\, Poland",
"DEATHDATE:19340704",
"DEATHPLACE:Passy\\, France",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
const annivs = Object.values(result[0].anniversaries || {});
const birth = annivs.find((a) => a.kind === "birth");
const death = annivs.find((a) => a.kind === "death");
expect(birth?.place?.fullAddress).toBe("Warsaw, Poland");
expect(death?.place?.fullAddress).toBe("Passy, France");
});
it("parses EXPERTISE / HOBBY / INTEREST with LEVEL (RFC 6715)", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Polymath",
"EXPERTISE;LEVEL=expert:cryptography",
"EXPERTISE;LEVEL=beginner:welding",
"HOBBY;LEVEL=high:gardening",
"INTEREST;LEVEL=medium:opera",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
const info = Object.values(result[0].personalInfo || {});
expect(info).toEqual(expect.arrayContaining([
{ kind: "expertise", value: "cryptography", level: "high" },
{ kind: "expertise", value: "welding", level: "low" },
{ kind: "hobby", value: "gardening", level: "high" },
{ kind: "interest", value: "opera", level: "medium" },
]));
});
it("parses ORG-DIRECTORY (RFC 6715) and CONTACT-URI (RFC 8605)", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Corp Person",
"ORG-DIRECTORY:https://example.com/staff/",
"CONTACT-URI;PREF=1:https://example.com/contact",
"EMAIL:c@example.com",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(Object.values(result[0].directories || {})[0]).toMatchObject({
uri: "https://example.com/staff/",
kind: "directory",
});
const links = Object.values(result[0].links || {});
expect(links[0]).toMatchObject({
uri: "https://example.com/contact",
kind: "contact",
pref: 1,
});
});
it("parses RFC 9554 CREATED, GRAMGENDER, PRONOUNS", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Modern Person",
"CREATED:20250101T120000Z",
"GRAMGENDER:neuter",
"PRONOUNS:they/them",
"PRONOUNS;PREF=2:ze/zir",
"EMAIL:m@example.com",
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
expect(result[0].created).toBe("20250101T120000Z");
expect(result[0].speakToAs?.grammaticalGender).toBe("neuter");
const pronouns = Object.values(result[0].speakToAs?.pronouns || {});
expect(pronouns).toEqual(expect.arrayContaining([
expect.objectContaining({ pronouns: "they/them" }),
expect.objectContaining({ pronouns: "ze/zir", pref: 2 }),
]));
});
it("accepts vCard 4.0 KIND values (location, device, application)", () => {
for (const k of ["location", "device", "application"] as const) {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
`KIND:${k}`,
"FN:Thing",
"END:VCARD",
].join("\r\n");
expect(parseVCard(vcf)[0].kind).toBe(k);
}
});
it("handles ADR with LABEL/GEO/TZ/CC parameters (RFC 9554)", () => {
const vcf = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:GeoPerson",
'ADR;CC=DE;GEO="geo:52.5,13.4";TZ=Europe/Berlin;LABEL="Unter den Linden 1\\nBerlin":;;Unter den Linden 1;Berlin;;10117;Germany',
"END:VCARD",
].join("\r\n");
const result = parseVCard(vcf);
const addr = result[0].addresses?.a0;
expect(addr?.countryCode).toBe("DE");
expect(addr?.coordinates).toBe("52.5,13.4");
expect(addr?.timeZone).toBe("Europe/Berlin");
expect(addr?.fullAddress).toContain("Unter den Linden 1");
expect(addr?.locality).toBe("Berlin");
});
it("unfolds LF-only continuation lines (no CR)", () => {
// Unix exporters often use LF only; we must still unfold.
const vcf = "BEGIN:VCARD\nVERSION:4.0\nFN:John\n Doe\nEMAIL:j@d.com\nEND:VCARD";
const result = parseVCard(vcf);
expect(result[0].name?.components).toEqual(
expect.arrayContaining([{ kind: "given", value: "JohnDoe" }])
);
});
it("round-trips vCard 4.0-only properties through generateVCard", () => {
const original = [
"BEGIN:VCARD",
"VERSION:4.0",
"FN:Round Trip",
"EMAIL;PREF=1:rt@example.com",
"BDAY:19700101",
"BIRTHPLACE:Somewhere",
"EXPERTISE;LEVEL=expert:vCard",
"HOBBY;LEVEL=medium:reading",
"ORG-DIRECTORY:https://example.com/dir",
"CONTACT-URI:https://example.com/contact",
"CREATED:20240101T000000Z",
"END:VCARD",
].join("\r\n");
const exported = generateVCard(parseVCard(original));
const reparsed = parseVCard(exported)[0];
expect(reparsed.emails?.e0?.pref).toBe(1);
expect(Object.values(reparsed.anniversaries || {}).find(a => a.kind === "birth")?.place?.fullAddress).toBe("Somewhere");
const info = Object.values(reparsed.personalInfo || {});
expect(info).toEqual(expect.arrayContaining([
{ kind: "expertise", value: "vCard", level: "high" },
{ kind: "hobby", value: "reading", level: "medium" },
]));
expect(Object.values(reparsed.directories || {})[0]?.uri).toBe("https://example.com/dir");
expect(Object.values(reparsed.links || {})[0]).toMatchObject({
uri: "https://example.com/contact",
kind: "contact",
});
expect(reparsed.created).toBe("20240101T000000Z");
});
});
describe("detectDuplicates", () => {
it("detects duplicates by matching email (case-insensitive)", () => {
const existing: ContactCard[] = [
+46
View File
@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest';
import { compareVersions, isVersionSatisfied } from '@/lib/version-compare';
describe('compareVersions', () => {
it('orders by major, minor, patch', () => {
expect(compareVersions('1.0.0', '1.0.0')).toBe(0);
expect(compareVersions('1.0.1', '1.0.0')).toBeGreaterThan(0);
expect(compareVersions('1.0.0', '1.0.1')).toBeLessThan(0);
expect(compareVersions('2.0.0', '1.9.9')).toBeGreaterThan(0);
expect(compareVersions('1.10.0', '1.9.0')).toBeGreaterThan(0);
});
it('treats missing segments as 0', () => {
expect(compareVersions('1', '1.0.0')).toBe(0);
expect(compareVersions('1.2', '1.2.0')).toBe(0);
});
it('tolerates a leading v', () => {
expect(compareVersions('v1.6.7', '1.6.7')).toBe(0);
});
it('ignores pre-release / build metadata', () => {
expect(compareVersions('1.6.7-rc.1', '1.6.7')).toBe(0);
expect(compareVersions('1.6.7+build.5', '1.6.7')).toBe(0);
});
});
describe('isVersionSatisfied', () => {
it('returns true when current >= required', () => {
expect(isVersionSatisfied('1.6.7', '1.6.7')).toBe(true);
expect(isVersionSatisfied('1.6.8', '1.6.7')).toBe(true);
expect(isVersionSatisfied('2.0.0', '1.9.9')).toBe(true);
});
it('returns false when current < required', () => {
expect(isVersionSatisfied('1.6.6', '1.6.7')).toBe(false);
expect(isVersionSatisfied('1.5.0', '1.6.0')).toBe(false);
expect(isVersionSatisfied('0.0.0', '1.0.0')).toBe(false);
});
it('treats empty / null / undefined required as no requirement', () => {
expect(isVersionSatisfied('1.0.0', '')).toBe(true);
expect(isVersionSatisfied('1.0.0', null)).toBe(true);
expect(isVersionSatisfied('1.0.0', undefined)).toBe(true);
});
});
+13 -3
View File
@@ -189,11 +189,21 @@ export async function changeAdminPassword(currentPassword: string, newPassword:
/**
* Set the admin password without verifying a current one. Used by the setup
* wizard during initial bootstrap. Refuses to overwrite an existing password.
* wizard during initial bootstrap.
*
* Refuses to overwrite an existing password unless `allowOverwrite` is true.
* The wizard's finish route passes `allowOverwrite: true` so a half-completed
* setup (admin.json left behind by an ADMIN_PASSWORD env var or an aborted
* earlier wizard run, while setupComplete is still false) can be recovered
* by simply running the wizard again. Safe because the finish route is
* already gated by the one-time setup token.
*/
export async function setInitialAdminPassword(newPassword: string): Promise<boolean> {
export async function setInitialAdminPassword(
newPassword: string,
options: { allowOverwrite?: boolean } = {},
): Promise<boolean> {
const existing = await readConfigData();
if (existing) return false;
if (existing && !options.allowOverwrite) return false;
const hash = await hashPassword(newPassword);
cachedConfig = { passwordHash: hash };
cachedState = freshState();
+2
View File
@@ -146,6 +146,8 @@ export const CONFIG_ENV_MAP: Record<string, { envVar: string; fileEnvVar?: strin
oauthClientId: { envVar: 'OAUTH_CLIENT_ID', type: 'string', defaultValue: '' },
oauthClientSecret: { envVar: 'OAUTH_CLIENT_SECRET', fileEnvVar: 'OAUTH_CLIENT_SECRET_FILE', type: 'string', defaultValue: '' },
oauthIssuerUrl: { envVar: 'OAUTH_ISSUER_URL', type: 'url', defaultValue: '' },
oauthScopes: { envVar: 'OAUTH_SCOPES', type: 'string', defaultValue: '' },
oauthExtraScopes: { envVar: 'OAUTH_EXTRA_SCOPES', type: 'string', defaultValue: '' },
allowCustomJmapEndpoint: { envVar: 'ALLOW_CUSTOM_JMAP_ENDPOINT', type: 'boolean', defaultValue: false },
jmapServers: { envVar: 'JMAP_SERVERS', type: 'json', defaultValue: [] },
jmapServerAutoPickByDomain: { envVar: 'JMAP_SERVER_AUTO_PICK_BY_DOMAIN', type: 'boolean', defaultValue: false },
+76
View File
@@ -1,5 +1,16 @@
import type { ContactCard, AddressBook } from '@/lib/jmap/types';
// randomuser.me serves stable portrait URLs at
// https://randomuser.me/api/portraits/{men|women}/{0..99}.jpg
// See https://randomuser.me/documentation#howto - we use these directly
// rather than hitting the JSON API so the demo works offline.
const portrait = (gender: 'men' | 'women', n: number): string =>
`https://randomuser.me/api/portraits/${gender}/${n}.jpg`;
const photo = (gender: 'men' | 'women', n: number) => ({
photo1: { kind: 'photo' as const, uri: portrait(gender, n), mediaType: 'image/jpeg' },
});
export function createDemoAddressBooks(): AddressBook[] {
return [
{
@@ -34,6 +45,7 @@ export function createDemoContacts(): ContactCard[] {
organizations: { o1: { name: 'Acme Corp', units: [{ name: 'Engineering' }] } },
titles: { t1: { name: 'Senior Engineer', kind: 'title' } },
anniversaries: { a1: { kind: 'birth', date: { year: 1990, month: 3, day: 15 } } },
media: photo('women', 44),
},
{
id: 'demo-contact-2',
@@ -50,6 +62,7 @@ export function createDemoContacts(): ContactCard[] {
},
organizations: { o1: { name: 'Acme Corp', units: [{ name: 'Backend Team' }] } },
titles: { t1: { name: 'Staff Engineer', kind: 'title' } },
media: photo('men', 32),
},
{
id: 'demo-contact-3',
@@ -60,6 +73,7 @@ export function createDemoContacts(): ContactCard[] {
phones: { p1: { number: '+1-555-0104', features: { voice: true } } },
organizations: { o1: { name: 'DesignCo' } },
titles: { t1: { name: 'UX Designer', kind: 'title' } },
media: photo('women', 68),
},
{
id: 'demo-contact-4',
@@ -69,6 +83,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'carlos.rivera@example.com', pref: 1 } },
phones: { p1: { number: '+1-555-0105', features: { cell: true } } },
notes: { n1: { note: 'Met at the DevConf 2024 conference' } },
media: photo('men', 15),
},
{
id: 'demo-contact-5',
@@ -89,6 +104,7 @@ export function createDemoContacts(): ContactCard[] {
},
},
anniversaries: { a1: { kind: 'birth', date: { month: 7, day: 22 } } },
media: photo('women', 22),
},
{
id: 'demo-contact-6',
@@ -97,6 +113,7 @@ export function createDemoContacts(): ContactCard[] {
name: { components: [{ kind: 'given', value: 'David' }, { kind: 'surname', value: 'Park' }] },
emails: { e1: { address: 'david.park@example.com', pref: 1 } },
phones: { p1: { number: '+82-10-1234-5678', features: { cell: true } } },
media: photo('men', 67),
},
{
id: 'demo-contact-7',
@@ -123,6 +140,58 @@ export function createDemoContacts(): ContactCard[] {
kind: 'individual',
name: { components: [{ kind: 'given', value: 'Lisa' }, { kind: 'surname', value: 'Tanaka' }] },
emails: { e1: { address: 'lisa.tanaka@example.com', pref: 1 } },
media: photo('women', 85),
},
{
id: 'demo-contact-16',
addressBookIds: { 'demo-addressbook-personal': true },
kind: 'individual',
name: { components: [{ kind: 'given', value: 'Sofia' }, { kind: 'surname', value: 'Russo' }] },
emails: { e1: { address: 'sofia.russo@example.com', contexts: { private: true }, pref: 1 } },
phones: { p1: { number: '+39-340-555-0111', features: { cell: true }, contexts: { private: true } } },
notes: { n1: { note: 'Mom' } },
anniversaries: { a1: { kind: 'birth', date: { year: 1962, month: 5, day: 9 } } },
media: photo('women', 3),
},
{
id: 'demo-contact-17',
addressBookIds: { 'demo-addressbook-personal': true },
kind: 'individual',
name: { components: [{ kind: 'given', value: 'Anna' }, { kind: 'surname', value: 'Kowalski' }] },
emails: { e1: { address: 'anna.kowalski@example.com', contexts: { private: true }, pref: 1 } },
phones: { p1: { number: '+48-602-555-0144', features: { cell: true } } },
notes: { n1: { note: 'Sister - lives in Kraków' } },
anniversaries: { a1: { kind: 'birth', date: { month: 11, day: 4 } } },
media: photo('women', 47),
},
{
id: 'demo-contact-18',
addressBookIds: { 'demo-addressbook-personal': true },
kind: 'individual',
name: { components: [{ kind: 'given', value: 'Marcus' }, { kind: 'surname', value: 'Hughes' }] },
emails: { e1: { address: 'marcus.hughes@example.com', pref: 1 } },
notes: { n1: { note: 'College friend - book club organiser' } },
media: photo('men', 96),
},
{
id: 'demo-contact-19',
addressBookIds: { 'demo-addressbook-personal': true },
kind: 'individual',
name: { components: [{ kind: 'given', value: 'Olivia' }, { kind: 'surname', value: 'Bennett' }] },
emails: { e1: { address: 'olivia.bennett@example.com', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Northwind Studio' } },
titles: { t1: { name: 'Product Designer', kind: 'title' } },
media: photo('women', 91),
},
{
id: 'demo-contact-20',
addressBookIds: { 'demo-addressbook-personal': true },
kind: 'individual',
name: { components: [{ kind: 'given', value: 'Daniel' }, { kind: 'surname', value: 'Cooper' }] },
emails: { e1: { address: 'daniel.cooper@example.com', pref: 1 } },
organizations: { o1: { name: 'Freelance' } },
titles: { t1: { name: 'Illustrator', kind: 'title' } },
media: photo('men', 76),
},
// ── Work address book ──────────────────────────────────────
@@ -135,6 +204,7 @@ export function createDemoContacts(): ContactCard[] {
phones: { p1: { number: '+1-555-0301', features: { voice: true }, contexts: { work: true } } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Product' }] } },
titles: { t1: { name: 'Product Manager', kind: 'title' } },
media: photo('men', 41),
},
{
id: 'demo-contact-10',
@@ -144,6 +214,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'rachel.green@company.example', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Marketing' }] } },
titles: { t1: { name: 'Marketing Lead', kind: 'title' } },
media: photo('women', 12),
},
{
id: 'demo-contact-11',
@@ -153,6 +224,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'james.miller@company.example', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Engineering' }] } },
titles: { t1: { name: 'CTO', kind: 'title' } },
media: photo('men', 52),
},
{
id: 'demo-contact-12',
@@ -162,6 +234,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'priya.sharma@company.example', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'QA' }] } },
titles: { t1: { name: 'QA Engineer', kind: 'title' } },
media: photo('women', 77),
},
{
id: 'demo-contact-13',
@@ -171,6 +244,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'ahmed.hassan@company.example', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'DevOps' }] } },
titles: { t1: { name: 'DevOps Engineer', kind: 'title' } },
media: photo('men', 89),
},
{
id: 'demo-contact-14',
@@ -180,6 +254,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'maria.lopez@company.example', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'HR' }] } },
titles: { t1: { name: 'HR Business Partner', kind: 'title' } },
media: photo('women', 55),
},
{
id: 'demo-contact-15',
@@ -189,6 +264,7 @@ export function createDemoContacts(): ContactCard[] {
emails: { e1: { address: 'wei.zhang@company.example', contexts: { work: true }, pref: 1 } },
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Data Science' }] } },
titles: { t1: { name: 'Data Scientist', kind: 'title' } },
media: photo('men', 8),
},
];
}
+590 -110
View File
@@ -1,6 +1,35 @@
import type { Email } from '@/lib/jmap/types';
import { demoDate } from '../demo-utils';
const USER = { name: 'Demo User', email: 'demo@example.com' } as const;
// Helper to keep the fixtures short - auto-assigns a partId/blobId per body.
let bodyCounter = 0;
function body(value: string, type: 'text/plain' | 'text/html' = 'text/plain') {
const partId = String(++bodyCounter);
const blobId = `blob-${partId}`;
return {
part: { partId, blobId, size: value.length, type },
values: { [partId]: { value } },
};
}
/** Build text+html parts in one shot. */
function bodies(text: string, html: string) {
const t = body(text, 'text/plain');
const h = body(html, 'text/html');
return {
textBody: [t.part],
htmlBody: [h.part],
bodyValues: { ...t.values, ...h.values },
};
}
function textOnly(text: string) {
const t = body(text, 'text/plain');
return { textBody: [t.part], bodyValues: t.values };
}
export function createDemoEmails(): Email[] {
return [
// ── Inbox ───────────────────────────────────────────────────
@@ -12,19 +41,61 @@ export function createDemoEmails(): Email[] {
size: 4200,
receivedAt: demoDate(0, -2),
from: [{ name: 'Bulwark Team', email: 'welcome@bulwark.email' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
to: [USER],
subject: 'Welcome to Bulwark Mail!',
sentAt: demoDate(0, -2),
preview: 'Thanks for trying out Bulwark Mail. This is a demo environment where you can explore all features...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-1', size: 350, type: 'text/plain' }],
htmlBody: [{ partId: '2', blobId: 'blob-2', size: 800, type: 'text/html' }],
bodyValues: {
'1': { value: 'Thanks for trying out Bulwark Mail!\n\nThis is a demo environment where you can explore all features without connecting to a real server. All data stays on your device.\n\nFeel free to:\n- Read, compose, and organize emails\n- Manage contacts and calendars\n- Configure filters and settings\n- Try keyboard shortcuts (press ? to see them)\n\nEnjoy exploring!' },
'2': { value: '<div><h2>Welcome to Bulwark Mail!</h2><p>Thanks for trying out Bulwark Mail!</p><p>This is a demo environment where you can explore all features without connecting to a real server. <strong>All data stays on your device.</strong></p><p>Feel free to:</p><ul><li>Read, compose, and organize emails</li><li>Manage contacts and calendars</li><li>Configure filters and settings</li><li>Try keyboard shortcuts (press <kbd>?</kbd> to see them)</li></ul><p>Enjoy exploring!</p></div>' },
},
...bodies(
'Thanks for trying out Bulwark Mail!\n\nThis is a demo environment where you can explore all features without connecting to a real server. All data stays on your device.\n\nFeel free to:\n- Read, compose, and organize emails\n- Manage contacts and calendars\n- Configure filters and settings\n- Try keyboard shortcuts (press ? to see them)\n\nEnjoy exploring!',
'<div><h2>Welcome to Bulwark Mail!</h2><p>Thanks for trying out Bulwark Mail!</p><p>This is a demo environment where you can explore all features without connecting to a real server. <strong>All data stays on your device.</strong></p><p>Feel free to:</p><ul><li>Read, compose, and organize emails</li><li>Manage contacts and calendars</li><li>Configure filters and settings</li><li>Try keyboard shortcuts (press <kbd>?</kbd> to see them)</li></ul><p>Enjoy exploring!</p></div>',
),
messageId: '<welcome@demo.bulwark.email>',
},
// Mom - personal message, unread
{
id: 'demo-email-mom',
threadId: 'demo-thread-mom',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 1900,
receivedAt: demoDate(0, -4, -12),
from: [{ name: 'Sofia Russo', email: 'sofia.russo@example.com' }],
to: [USER],
subject: 'when are you coming home?',
sentAt: demoDate(0, -4, -12),
preview: 'Hi sweetie, your father and I were just talking - we miss you. Any chance you can come down for a weekend...',
hasAttachment: false,
...textOnly(
"Hi sweetie,\n\nYour father and I were just talking - we miss you. Any chance you can come down for a weekend before Christmas?\n\nNo pressure if you're swamped with work. Anna said she might be in town the 22nd, would be nice to all be in one place again.\n\nThe lemon tree finally fruited! Twelve lemons. I'll save you some.\n\nLove,\nMom",
),
messageId: '<5a8c-mom@example.com>',
},
// GitHub - PR review request
{
id: 'demo-email-gh-pr',
threadId: 'demo-thread-gh-pr',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 6400,
receivedAt: demoDate(0, -3, -5),
from: [{ name: 'Alice Johnson (via GitHub)', email: 'notifications@github.com' }],
replyTo: [{ name: 'reply', email: 'reply+abc123@reply.github.com' }],
to: [USER],
subject: '[acme/api-gateway] Add token-bucket rate limiter (#1284)',
sentAt: demoDate(0, -3, -5),
preview: '@demo-user requested your review on this pull request. Replaces the fixed-window limiter with a leaky token-bucket...',
hasAttachment: false,
...bodies(
'@demo-user requested your review on this pull request.\n\nReplaces the fixed-window limiter with a leaky token-bucket so we stop punishing clients at the second-boundary edge. Per-endpoint config lives in rate-limit.toml.\n\nThree files changed, +312 47.\n\nView it on GitHub:\nhttps://github.com/acme/api-gateway/pull/1284\n\n-\nReply to this email directly, or view it on GitHub.',
'<table style="font-family:-apple-system,sans-serif"><tr><td><strong>@demo-user</strong> requested your review on this pull request.</td></tr><tr><td style="padding-top:12px">Replaces the fixed-window limiter with a leaky token-bucket so we stop punishing clients at the second-boundary edge. Per-endpoint config lives in <code>rate-limit.toml</code>.</td></tr><tr><td style="padding-top:12px;color:#666">Three files changed, <span style="color:#16a34a">+312</span> <span style="color:#dc2626">47</span></td></tr><tr><td style="padding-top:16px"><a href="https://github.com/acme/api-gateway/pull/1284" style="background:#1f2328;color:#fff;padding:8px 16px;text-decoration:none;border-radius:6px">View on GitHub</a></td></tr></table>',
),
messageId: '<acme/api-gateway/pull/1284@github.com>',
},
// Hacker Newsletter - newsletter, read
{
id: 'demo-email-2',
threadId: 'demo-thread-2',
@@ -33,20 +104,19 @@ export function createDemoEmails(): Email[] {
size: 18500,
receivedAt: demoDate(-1, -5),
from: [{ name: 'TechDigest Weekly', email: 'newsletter@techdigest.example' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
subject: 'This Week in Tech: AI Developments & Open Source Updates',
to: [USER],
subject: 'Issue #218 - RFC 9844, the second WebAssembly draft, and a quiet announcement from Mozilla',
sentAt: demoDate(-1, -5),
preview: 'Your weekly roundup of the most important technology news and open source developments...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-3', size: 2400, type: 'text/plain' }],
htmlBody: [{ partId: '2', blobId: 'blob-4', size: 5200, type: 'text/html' }],
bodyValues: {
'1': { value: 'This Week in Tech\n\n1. AI-Powered Code Review Tools\nNew tools are making code reviews faster and more thorough...\n\n2. Open Source Licensing Update\nThe OSI has published new guidelines for AI-generated code...\n\n3. WebAssembly 2.0 Draft\nThe W3C has released the first draft of WebAssembly 2.0...\n\nRead more at techdigest.example' },
'2': { value: '<div style="max-width:600px;margin:0 auto;"><h1>This Week in Tech</h1><h3>1. AI-Powered Code Review Tools</h3><p>New tools are making code reviews faster and more thorough, with several open-source options gaining traction.</p><h3>2. Open Source Licensing Update</h3><p>The OSI has published new guidelines for AI-generated code contributions to open source projects.</p><h3>3. WebAssembly 2.0 Draft</h3><p>The W3C has released the first draft of WebAssembly 2.0, promising improved memory management.</p></div>' },
},
messageId: '<weekly-42@techdigest.example>',
...bodies(
'TechDigest #218\n\n- THE WEEK IN STANDARDS -\n\n1. RFC 9844: Per-message TLS extensions are now official. The implications for SMTP delivery reports are surprisingly large - Mike Crispin has a write-up that runs through what changes for transactional senders.\n\n2. WebAssembly 2.0 (second public draft). Tail calls are in. SIMD is in. Component model is *almost* in but punted to a separate spec, which feels like the right call.\n\n3. Mozilla quietly shipped a privacy-preserving telemetry channel to Firefox 132. No, it doesn\'t replace ad tracking. Yes, it\'s a real cryptographic system. Worth reading the post.\n\n- TOOLS -\n\n- Datasette 1.0 is out. Ten years from the first commit.\n- Fly.io published their object store, Tigris-style, written in Go.\n- Linear added an SSO migration tool that actually handles the IdP-initiated case.\n\n- ESSAYS -\n\n* "Postgres is enough" by E. Tan - a long-form rebuttal to the microservices-by-default pattern.\n* "I rewrote my home network in TypeScript so you don\'t have to" - exactly what it sounds like.\n\n- UNSUBSCRIBE -\n\nManage your subscription at techdigest.example/manage.',
'<div style="max-width:560px;margin:0 auto;font-family:-apple-system,sans-serif;line-height:1.5"><div style="border-bottom:2px solid #111;padding-bottom:16px"><div style="font-size:11px;letter-spacing:0.12em;text-transform:uppercase;color:#888">TechDigest · Issue #218</div><h1 style="font-size:22px;margin:4px 0 0">RFC 9844, the second WebAssembly draft, and a quiet announcement from Mozilla</h1></div><h2 style="font-size:14px;text-transform:uppercase;letter-spacing:0.08em;color:#666;margin-top:24px">The week in standards</h2><p><strong>1.</strong> RFC 9844: Per-message TLS extensions are now official. The implications for SMTP delivery reports are surprisingly large - Mike Crispin has a <a href="#" style="color:#db2d54">write-up</a> that runs through what changes for transactional senders.</p><p><strong>2.</strong> WebAssembly 2.0 (second public draft). Tail calls are in. SIMD is in. Component model is <em>almost</em> in but punted to a separate spec, which feels like the right call.</p><p><strong>3.</strong> Mozilla quietly shipped a privacy-preserving telemetry channel to Firefox 132. No, it doesn\'t replace ad tracking. Yes, it\'s a real cryptographic system.</p><h2 style="font-size:14px;text-transform:uppercase;letter-spacing:0.08em;color:#666;margin-top:24px">Tools</h2><ul><li>Datasette 1.0 is out. Ten years from the first commit.</li><li>Fly.io published their object store, Tigris-style, written in Go.</li><li>Linear added an SSO migration tool that actually handles the IdP-initiated case.</li></ul><h2 style="font-size:14px;text-transform:uppercase;letter-spacing:0.08em;color:#666;margin-top:24px">Essays</h2><p style="margin:0 0 6px">"Postgres is enough" by E. Tan - a long-form rebuttal to the microservices-by-default pattern.</p><p style="margin:0">"I rewrote my home network in TypeScript so you don\'t have to" - exactly what it sounds like.</p><div style="margin-top:28px;padding-top:16px;border-top:1px solid #eee;font-size:12px;color:#888">Manage your subscription at <a href="#" style="color:#888">techdigest.example/manage</a></div></div>',
),
messageId: '<weekly-218@techdigest.example>',
},
// Thread: Project discussion (3 emails in same thread)
// Thread: Q4 Project Timeline - Alice → Bob → Alice (4 messages)
{
id: 'demo-email-3a',
threadId: 'demo-thread-3',
@@ -55,17 +125,15 @@ export function createDemoEmails(): Email[] {
size: 3100,
receivedAt: demoDate(-3, -10),
from: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }, { name: 'Bob Chen', email: 'bob.chen@example.com' }],
to: [USER, { name: 'Bob Chen', email: 'bob.chen@example.com' }],
subject: 'Q4 Project Timeline',
sentAt: demoDate(-3, -10),
preview: 'Hi team, I wanted to share the updated timeline for our Q4 deliverables...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-5', size: 450, type: 'text/plain' }],
htmlBody: [{ partId: '2', blobId: 'blob-6', size: 650, type: 'text/html' }],
bodyValues: {
'1': { value: 'Hi team,\n\nI wanted to share the updated timeline for our Q4 deliverables:\n\n- Phase 1: Design review - Oct 15\n- Phase 2: Development - Nov 1-30\n- Phase 3: Testing - Dec 1-15\n- Phase 4: Launch - Dec 20\n\nPlease review and let me know if you see any conflicts.\n\nBest,\nAlice' },
'2': { value: '<p>Hi team,</p><p>I wanted to share the updated timeline for our Q4 deliverables:</p><ul><li>Phase 1: Design review - Oct 15</li><li>Phase 2: Development - Nov 1-30</li><li>Phase 3: Testing - Dec 1-15</li><li>Phase 4: Launch - Dec 20</li></ul><p>Please review and let me know if you see any conflicts.</p><p>Best,<br>Alice</p>' },
},
...bodies(
'Hi team,\n\nI wanted to share the updated timeline for our Q4 deliverables:\n\n- Phase 1: Design review - Oct 15\n- Phase 2: Development - Nov 1-30\n- Phase 3: Testing - Dec 1-15\n- Phase 4: Launch - Dec 20\n\nPlease review and let me know if you see any conflicts.\n\nBest,\nAlice',
'<p>Hi team,</p><p>I wanted to share the updated timeline for our Q4 deliverables:</p><ul><li>Phase 1: Design review - Oct 15</li><li>Phase 2: Development - Nov 1-30</li><li>Phase 3: Testing - Dec 1-15</li><li>Phase 4: Launch - Dec 20</li></ul><p>Please review and let me know if you see any conflicts.</p><p>Best,<br>Alice</p>',
),
messageId: '<q4-timeline-1@example.com>',
},
{
@@ -76,15 +144,14 @@ export function createDemoEmails(): Email[] {
size: 3500,
receivedAt: demoDate(-2, -8),
from: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }],
to: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }, { name: 'Demo User', email: 'demo@example.com' }],
to: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }, USER],
subject: 'Re: Q4 Project Timeline',
sentAt: demoDate(-2, -8),
preview: 'Looks good to me! One concern: the testing window might be tight given the holidays...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-7', size: 520, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Looks good to me! One concern: the testing window might be tight given the holidays. Could we start testing a few days earlier?\n\nAlso, should we set up a shared doc for tracking blockers?\n\n- Bob' },
},
...textOnly(
"Looks good to me! One concern: the testing window might be tight given the holidays. Could we start testing a few days earlier?\n\nAlso, should we set up a shared doc for tracking blockers?\n\n- Bob",
),
messageId: '<q4-timeline-2@example.com>',
inReplyTo: ['<q4-timeline-1@example.com>'],
references: ['<q4-timeline-1@example.com>'],
@@ -97,20 +164,41 @@ export function createDemoEmails(): Email[] {
size: 3800,
receivedAt: demoDate(-1, -3),
from: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
to: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }, { name: 'Demo User', email: 'demo@example.com' }],
to: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }, USER],
subject: 'Re: Q4 Project Timeline',
sentAt: demoDate(-1, -3),
preview: 'Great point Bob. Let\'s move testing to Nov 28. I\'ll create the shared doc today...',
preview: "Great point Bob. Let's move testing to Nov 28. I'll create the shared doc today...",
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-8', size: 400, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Great point Bob. Let\'s move testing to Nov 28. I\'ll create the shared doc today and share the link.\n\nUpdated timeline:\n- Design review: Oct 15\n- Development: Nov 1-27\n- Testing: Nov 28 - Dec 15\n- Launch: Dec 20\n\n- Alice' },
},
...textOnly(
"Great point Bob. Let's move testing to Nov 28. I'll create the shared doc today and share the link.\n\nUpdated timeline:\n- Design review: Oct 15\n- Development: Nov 1-27\n- Testing: Nov 28 - Dec 15\n- Launch: Dec 20\n\n- Alice",
),
messageId: '<q4-timeline-3@example.com>',
inReplyTo: ['<q4-timeline-2@example.com>'],
references: ['<q4-timeline-1@example.com>', '<q4-timeline-2@example.com>'],
},
// Email with attachments
// Stripe receipt
{
id: 'demo-email-stripe',
threadId: 'demo-thread-stripe',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 11200,
receivedAt: demoDate(-1, -1, -22),
from: [{ name: 'Stripe', email: 'receipts@stripe.com' }],
to: [USER],
subject: 'Your receipt from Linear Inc. [#2451-9928]',
sentAt: demoDate(-1, -1, -22),
preview: 'Receipt from Linear Inc. for $16.00. Thanks for your business.',
hasAttachment: false,
...bodies(
'Receipt from Linear Inc.\nAmount paid: $16.00\nDate paid: yesterday\nPayment method: Visa •••• 4242\n\nDescription: Linear Standard (monthly)\n\nReceipt #2451-9928\n\nThis charge will appear on your statement as LINEAR INC.\n\nQuestions? Contact support@linear.app.',
'<div style="max-width:560px;margin:0 auto;font-family:-apple-system,sans-serif"><div style="text-align:center;padding:24px 0"><div style="font-size:11px;letter-spacing:0.12em;color:#888;text-transform:uppercase">Receipt</div><div style="font-size:32px;font-weight:700;margin-top:4px">$16.00</div><div style="color:#666;margin-top:4px">Linear Inc.</div></div><table style="width:100%;border-top:1px solid #eee;border-bottom:1px solid #eee"><tr><td style="padding:10px 0;color:#666">Amount</td><td style="padding:10px 0;text-align:right">$16.00</td></tr><tr><td style="padding:10px 0;color:#666;border-top:1px solid #f4f4f4">Payment method</td><td style="padding:10px 0;text-align:right;border-top:1px solid #f4f4f4">Visa •••• 4242</td></tr><tr><td style="padding:10px 0;color:#666;border-top:1px solid #f4f4f4">Receipt number</td><td style="padding:10px 0;text-align:right;border-top:1px solid #f4f4f4;font-family:monospace">2451-9928</td></tr></table><p style="color:#666;font-size:13px;margin-top:24px">Description: Linear Standard (monthly). This charge will appear on your statement as LINEAR INC.</p></div>',
),
messageId: '<receipt-2451-9928@stripe.com>',
},
// Email with attachments - invoice
{
id: 'demo-email-4',
threadId: 'demo-thread-4',
@@ -119,22 +207,22 @@ export function createDemoEmails(): Email[] {
size: 245000,
receivedAt: demoDate(0, -6),
from: [{ name: 'Sarah Kim', email: 'sarah.kim@example.com' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
subject: 'Invoice #2024-089 & Project Screenshot',
to: [USER],
subject: 'Invoice #2024-089 & landing-page prototype v3',
sentAt: demoDate(0, -6),
preview: 'Hi, please find attached the invoice for October and a screenshot of the latest prototype...',
preview: "Hi, please find attached the invoice for October and a screenshot of the latest prototype...",
hasAttachment: true,
textBody: [{ partId: '1', blobId: 'blob-9', size: 280, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Hi,\n\nPlease find attached the invoice for October and a screenshot of the latest prototype.\n\nLet me know if you have any questions.\n\nBest regards,\nSarah' },
},
...textOnly(
"Hi,\n\nPlease find attached the invoice for October and a screenshot of the latest prototype. I went with Option B for the hero (the one with the asymmetric grid) since you mentioned the symmetrical version felt too flat in our last call.\n\nIf the invoice line items look off, ping me - I had to back out the November pre-payment.\n\nBest regards,\nSarah",
),
attachments: [
{ partId: 'att-1', blobId: 'demo-blob-att-1', size: 145000, name: 'Invoice-2024-089.pdf', type: 'application/pdf' },
{ partId: 'att-2', blobId: 'demo-blob-att-2', size: 89000, name: 'prototype-v3.png', type: 'image/png' },
],
messageId: '<invoice-089@example.com>',
},
// Starred email
// Carlos - starred, social
{
id: 'demo-email-5',
threadId: 'demo-thread-5',
@@ -143,18 +231,286 @@ export function createDemoEmails(): Email[] {
size: 2800,
receivedAt: demoDate(-2, -1),
from: [{ name: 'Carlos Rivera', email: 'carlos.rivera@example.com' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
subject: 'Reminder: Team Dinner Friday',
to: [USER],
subject: 'Friday dinner - moved to 7:30 (sorry!)',
sentAt: demoDate(-2, -1),
preview: 'Hey! Just a reminder about our team dinner this Friday at 7 PM at The Garden Bistro...',
preview: 'Quick heads up - had to push the dinner back half an hour. Bistro could only do the late seating...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-10', size: 320, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Hey!\n\nJust a reminder about our team dinner this Friday at 7 PM at The Garden Bistro. I\'ve made a reservation for 8 people.\n\nAddress: 123 Oak Street\n\nLet me know if you can make it!\n\nCheers,\nCarlos' },
},
...textOnly(
"Quick heads up - had to push the dinner back half an hour. Bistro could only do the late seating.\n\nNew time: Friday, 7:30 PM\nThe Garden Bistro, 123 Oak Street\n\nReservation under my name, 8 people. Let me know if that doesn't work for you and I can try to wrangle something.\n\nCheers,\nCarlos",
),
messageId: '<dinner-reminder@example.com>',
},
// Linear - issue assigned
{
id: 'demo-email-linear',
threadId: 'demo-thread-linear',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 5400,
receivedAt: demoDate(0, -7, -15),
from: [{ name: 'Linear', email: 'notifications@linear.app' }],
to: [USER],
subject: 'BUL-2031 was assigned to you - "Compose: drag-and-drop attachments duplicated on slow networks"',
sentAt: demoDate(0, -7, -15),
preview: 'Priya Sharma assigned this issue to you. Repro on a throttled connection (Slow 3G): drop a file twice and...',
hasAttachment: false,
...bodies(
"Priya Sharma assigned BUL-2031 to you.\n\nTitle: Compose: drag-and-drop attachments duplicated on slow networks\nPriority: Medium\n\nRepro on a throttled connection (Slow 3G): drop a file twice in quick succession into the compose drop zone. The first upload doesn't get debounced and both attempts complete, so the attachment shows up twice in the draft.\n\nOpen in Linear: https://linear.app/bulwark/issue/BUL-2031",
'<table style="font-family:-apple-system,sans-serif;max-width:520px"><tr><td><div style="font-size:11px;color:#888;letter-spacing:0.08em;text-transform:uppercase">Linear · BUL-2031</div><div style="font-size:18px;font-weight:600;margin-top:6px">Compose: drag-and-drop attachments duplicated on slow networks</div><div style="margin-top:8px;color:#666"><strong>Priya Sharma</strong> assigned this issue to you · Priority Medium</div></td></tr><tr><td style="padding-top:16px;color:#444">Repro on a throttled connection (Slow 3G): drop a file twice in quick succession into the compose drop zone. The first upload doesn\'t get debounced and both attempts complete, so the attachment shows up twice in the draft.</td></tr><tr><td style="padding-top:16px"><a href="https://linear.app/bulwark/issue/BUL-2031" style="background:#5e6ad2;color:#fff;padding:8px 16px;text-decoration:none;border-radius:6px;font-size:13px">Open in Linear</a></td></tr></table>',
),
messageId: '<BUL-2031-assign@linear.app>',
},
// Anna - sister, photos
{
id: 'demo-email-anna',
threadId: 'demo-thread-anna',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 4800000,
receivedAt: demoDate(-1, -19),
from: [{ name: 'Anna Kowalski', email: 'anna.kowalski@example.com' }],
to: [USER],
subject: 'photos from the wedding',
sentAt: demoDate(-1, -19),
preview: "finally got around to going through these. there are like 600 more on the drive but here's the highlights...",
hasAttachment: true,
...textOnly(
"ok finally got around to going through these. there are like 600 more on the drive but here's the highlights - the ones I'd actually want to print.\n\nmom looked SO happy. dad cried during the speech btw, did you see?\n\nlet me know which ones you want full-res of\n\na",
),
attachments: [
{ partId: 'att-3', blobId: 'demo-blob-att-3', size: 1800000, name: 'wedding-001.jpg', type: 'image/jpeg' },
{ partId: 'att-4', blobId: 'demo-blob-att-4', size: 1600000, name: 'wedding-014-mom-dad.jpg', type: 'image/jpeg' },
{ partId: 'att-5', blobId: 'demo-blob-att-5', size: 1400000, name: 'wedding-038-the-toast.jpg', type: 'image/jpeg' },
],
messageId: '<wedding-photos@example.com>',
},
// AWS billing
{
id: 'demo-email-aws',
threadId: 'demo-thread-aws',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 9100,
receivedAt: demoDate(-2, -3, -45),
from: [{ name: 'AWS Billing', email: 'no-reply-aws@amazon.com' }],
to: [USER],
subject: 'Your AWS bill is available - $127.43',
sentAt: demoDate(-2, -3, -45),
preview: 'Your bill for the previous billing period is now available. Total this period: $127.43 (down $4.12)...',
hasAttachment: false,
...textOnly(
"Your bill for the previous billing period is now available.\n\nTotal this period: $127.43 (down $4.12 from last period)\n\nTop services:\n EC2 - $61.20\n S3 - $28.94\n Route 53 - $14.50\n CloudFront - $11.02\n Other - $11.77\n\nView the full invoice in the Billing Console.",
),
messageId: '<aws-bill-2024-11@amazon.com>',
},
// 2FA code - system, unread
{
id: 'demo-email-2fa',
threadId: 'demo-thread-2fa',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 1700,
receivedAt: demoDate(0, -1, -8),
from: [{ name: '1Password', email: 'noreply@1password.com' }],
to: [USER],
subject: 'Your one-time verification code is 814-302',
sentAt: demoDate(0, -1, -8),
preview: "Use this code within 10 minutes to sign in. If you didn't request it, ignore this email.",
hasAttachment: false,
...textOnly(
"Your verification code: 814-302\n\nUse this code within 10 minutes to sign in. If you didn't request it, you can safely ignore this email - your account remains secure.",
),
messageId: '<otp-814302@1password.com>',
},
// LinkedIn - cold-ish
{
id: 'demo-email-linkedin',
threadId: 'demo-thread-linkedin',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 8200,
receivedAt: demoDate(-3, -11),
from: [{ name: 'LinkedIn', email: 'jobs-noreply@linkedin.com' }],
to: [USER],
subject: '5 jobs matching "staff engineer · remote · eu" - including one at Datadog',
sentAt: demoDate(-3, -11),
preview: "We thought you'd be interested in these jobs based on your profile and search history.",
hasAttachment: false,
...textOnly(
'Based on your saved search "staff engineer · remote · eu":\n\n1. Staff Software Engineer - Datadog (Remote, EU)\n2. Principal Engineer, Platform - Sentry (Remote, EU)\n3. Staff Backend Engineer - Linear (Remote)\n4. Tech Lead, Infrastructure - Tailscale (Remote, EU)\n5. Staff Engineer, Mobile - Notion (Remote, EU)\n\nManage job alerts at linkedin.com/jobs/preferences.',
),
messageId: '<jobs-1107@linkedin.com>',
},
// Book club - Marcus
{
id: 'demo-email-bookclub',
threadId: 'demo-thread-bookclub',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 2400,
receivedAt: demoDate(-1, -14),
from: [{ name: 'Marcus Hughes', email: 'marcus.hughes@example.com' }],
to: [USER, { name: 'Emma Wilson', email: 'emma.wilson@example.com' }, { name: 'David Park', email: 'david.park@example.com' }],
subject: 'book club thursday - picking the next one',
sentAt: demoDate(-1, -14),
preview: 'Reminder: 7pm at mine. We finish off Le Guin and pick the next read. My vote is the Calvino but I know Emma...',
hasAttachment: false,
...textOnly(
"Reminder: 7pm at mine. We finish off Le Guin and pick the next read.\n\nMy vote is the Calvino but I know Emma's been pushing for the Knausgaard. I'll bring wine, can someone else handle snacks?\n\nm",
),
messageId: '<bookclub-nov@example.com>',
},
// DHL package
{
id: 'demo-email-dhl',
threadId: 'demo-thread-dhl',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 5600,
receivedAt: demoDate(0, -9, -30),
from: [{ name: 'DHL Express', email: 'noreply@dhl.com' }],
to: [USER],
subject: 'Your package is out for delivery - arriving today',
sentAt: demoDate(0, -9, -30),
preview: 'Tracking 1Z 999 AA1 0123 4567 84 · Estimated delivery: today between 14:00 and 18:00.',
hasAttachment: false,
...textOnly(
'Your package is on the truck.\n\nTracking: 1Z 999 AA1 0123 4567 84\nEstimated delivery window: today, 14:0018:00\n\nIf no one is home, the driver will attempt redelivery tomorrow or leave it at the nearest pickup point.\n\nTrack live at dhl.com/track.',
),
messageId: '<delivery-1Z999AA1@dhl.com>',
},
// Notion
{
id: 'demo-email-notion',
threadId: 'demo-thread-notion',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 4100,
receivedAt: demoDate(-2, -16),
from: [{ name: 'Olivia Bennett (via Notion)', email: 'team@mail.notion.so' }],
to: [USER],
subject: 'Olivia shared "Q1 2026 - design north star" with you',
sentAt: demoDate(-2, -16),
preview: 'Olivia Bennett shared a page with you in the Northwind workspace. Open in Notion to view.',
hasAttachment: false,
...textOnly(
'Olivia Bennett shared a page with you in the Northwind workspace.\n\n"Q1 2026 - design north star"\n\nOpen in Notion: https://notion.so/northwind/q1-design-north-star',
),
messageId: '<share-northwind-q1@mail.notion.so>',
},
// Spotify wrap
{
id: 'demo-email-spotify',
threadId: 'demo-thread-spotify',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 7400,
receivedAt: demoDate(-4, -8),
from: [{ name: 'Spotify', email: 'no-reply@spotify.com' }],
to: [USER],
subject: 'Your year in music is ready',
sentAt: demoDate(-4, -8),
preview: 'You spent 38,420 minutes listening this year. Your top artist was Big Thief, and your top genre was indie folk.',
hasAttachment: false,
...textOnly(
'Your year, in music.\n\n38,420 minutes listened\nTop artist: Big Thief\nTop song: "Vampire Empire"\nTop genre: indie folk\nDiscover Weekly hit rate: 41%\n\nOpen Spotify to see your full Wrapped.',
),
messageId: '<wrapped-2025@spotify.com>',
},
// Booking.com confirmation
{
id: 'demo-email-booking',
threadId: 'demo-thread-booking',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 32100,
receivedAt: demoDate(-5, -10),
from: [{ name: 'Booking.com', email: 'no-reply@booking.com' }],
to: [USER],
subject: 'Confirmation 4892-7714-3320 - Hotel Lago, Lake Como (Dec 2225)',
sentAt: demoDate(-5, -10),
preview: 'Your booking is confirmed. Check-in: Dec 22, after 15:00. Check-out: Dec 25, before 11:00.',
hasAttachment: true,
...textOnly(
'Your booking is confirmed.\n\nHotel Lago, Lake Como (Italy)\nCheck-in: Dec 22, after 15:00\nCheck-out: Dec 25, before 11:00\n\nRoom: Lake-view double, breakfast included\nTotal: €612 (paid)\n\nConfirmation number: 4892-7714-3320\n\nYour voucher is attached. Show it at reception.',
),
attachments: [
{ partId: 'att-6', blobId: 'demo-blob-att-6', size: 31000, name: 'booking-voucher-4892-7714-3320.pdf', type: 'application/pdf' },
],
messageId: '<conf-4892-7714-3320@booking.com>',
},
// Substack post
{
id: 'demo-email-substack',
threadId: 'demo-thread-substack',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: { $seen: true },
size: 22400,
receivedAt: demoDate(-1, -12),
from: [{ name: 'Robin Sloan', email: 'robin@substack.com' }],
to: [USER],
subject: 'a small newsletter about a small forge',
sentAt: demoDate(-1, -12),
preview: 'I have been spending the slow weeks of November in the workshop, slowly forging a knife from a piece of...',
hasAttachment: false,
...textOnly(
"Hello, friends.\n\nI have been spending the slow weeks of November in the workshop, slowly forging a knife from a piece of railway track. It is going badly, in the way that is good for one's soul.\n\nWhat I'm reading: Annie Dillard, again. \"The Writing Life\". Specifically the chapter about her cabin, which I read every year around this time and which always makes me want to throw my laptop into the sea.\n\nWhat I'm watching: very little. There is something about December that makes television feel like an admission of defeat.\n\nUntil next month -\nR.",
),
messageId: '<nov-2025@robin.substack.com>',
},
// Recruiter cold outreach
{
id: 'demo-email-recruiter',
threadId: 'demo-thread-recruiter',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 3200,
receivedAt: demoDate(0, -10),
from: [{ name: 'Jennifer Hayes', email: 'jennifer@talent-partners.example' }],
to: [USER],
subject: 'Senior role - Distributed Systems - €180-220k + equity',
sentAt: demoDate(0, -10),
preview: "Hi, I came across your profile and thought you'd be a great fit for a senior position with one of our clients...",
hasAttachment: false,
...textOnly(
"Hi,\n\nI came across your profile and thought you'd be a great fit for a senior position with one of our clients - a well-funded Series B (real-time data infrastructure, 60-person eng team, fully remote within EU).\n\nThe core stack: Rust + Postgres + a non-trivial amount of Go. Hiring level is roughly equivalent to Staff at FAANG.\n\nWould you be open to a 15-minute call this week or next?\n\nBest,\nJennifer Hayes\nTalent Partners",
),
messageId: '<outreach-jh-2025-11@talent-partners.example>',
},
// Dentist reminder
{
id: 'demo-email-dentist',
threadId: 'demo-thread-dentist',
mailboxIds: { 'demo-mailbox-inbox': true },
keywords: {},
size: 2200,
receivedAt: demoDate(-1, -2),
from: [{ name: "Dr. Smith's Office", email: 'appointments@drsmith.example' }],
to: [USER],
subject: 'Appointment reminder - Tuesday at 10:00',
sentAt: demoDate(-1, -2),
preview: 'This is a friendly reminder of your upcoming cleaning appointment on Tuesday at 10:00 AM.',
hasAttachment: false,
...textOnly(
"Hello,\n\nThis is a friendly reminder of your upcoming cleaning appointment on Tuesday at 10:00 AM with Dr. Smith.\n\nLocation: 123 Medical Plaza, Suite 4\n\nNeed to reschedule? Reply to this email or call (555) 010-7878.\n\nSee you Tuesday!\nDr. Smith's office",
),
messageId: '<appt-reminder-dr-smith@drsmith.example>',
},
// ── Sent ────────────────────────────────────────────────────
{
id: 'demo-email-6',
@@ -163,16 +519,15 @@ export function createDemoEmails(): Email[] {
keywords: { $seen: true },
size: 2100,
receivedAt: demoDate(-1, -4),
from: [{ name: 'Demo User', email: 'demo@example.com' }],
from: [USER],
to: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
subject: 'Updated Requirements Document',
sentAt: demoDate(-1, -4),
preview: 'Hi Alice, I\'ve updated the requirements document with the changes we discussed...',
preview: "Hi Alice, I've updated the requirements document with the changes we discussed...",
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-11', size: 290, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Hi Alice,\n\nI\'ve updated the requirements document with the changes we discussed in yesterday\'s meeting. The main updates are in sections 3 and 5.\n\nLet me know if you have any questions.\n\nBest,\nDemo User' },
},
...textOnly(
"Hi Alice,\n\nI've updated the requirements document with the changes we discussed in yesterday's meeting. The main updates are in sections 3 and 5.\n\nLet me know if you have any questions.\n\nBest,\nDemo User",
),
messageId: '<sent-1@example.com>',
},
{
@@ -182,18 +537,37 @@ export function createDemoEmails(): Email[] {
keywords: { $seen: true },
size: 1800,
receivedAt: demoDate(-4, -2),
from: [{ name: 'Demo User', email: 'demo@example.com' }],
from: [USER],
to: [{ name: 'Sarah Kim', email: 'sarah.kim@example.com' }],
subject: 'Re: Design Feedback',
sentAt: demoDate(-4, -2),
preview: 'Thanks Sarah! The new color scheme looks great. I especially like the contrast improvements...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-12', size: 250, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Thanks Sarah! The new color scheme looks great. I especially like the contrast improvements for accessibility.\n\nLet\'s go with Option B for the navigation.\n\nBest,\nDemo User' },
},
...textOnly(
"Thanks Sarah! The new color scheme looks great. I especially like the contrast improvements for accessibility.\n\nLet's go with Option B for the navigation.\n\nBest,\nDemo User",
),
messageId: '<sent-2@example.com>',
},
{
id: 'demo-email-sent-mom',
threadId: 'demo-thread-mom',
mailboxIds: { 'demo-mailbox-sent': true },
keywords: { $seen: true },
size: 1400,
receivedAt: demoDate(0, -2, -10),
from: [USER],
to: [{ name: 'Sofia Russo', email: 'sofia.russo@example.com' }],
subject: 'Re: when are you coming home?',
sentAt: demoDate(0, -2, -10),
preview: "Mom - I miss you too. Let me check the calendar tonight and I'll get back to you tomorrow about the weekend...",
hasAttachment: false,
...textOnly(
"Mom - I miss you too. Let me check the calendar tonight and I'll get back to you tomorrow about the weekend. Lemons sound like a bribe and I will not pretend otherwise.\n\nLove you both.",
),
messageId: '<re-mom-1@example.com>',
inReplyTo: ['<5a8c-mom@example.com>'],
references: ['<5a8c-mom@example.com>'],
},
// ── Drafts ──────────────────────────────────────────────────
{
@@ -203,18 +577,35 @@ export function createDemoEmails(): Email[] {
keywords: { $seen: true, $draft: true },
size: 900,
receivedAt: demoDate(0, -1),
from: [{ name: 'Demo User', email: 'demo@example.com' }],
from: [USER],
to: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }],
subject: 'Meeting Notes - Draft',
sentAt: demoDate(0, -1),
preview: 'Here are the notes from today\'s standup...',
preview: "Here are the notes from today's standup...",
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-13', size: 180, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Here are the notes from today\'s standup:\n\n- API integration on track\n- Need to resolve the caching issue\n- ' },
},
...textOnly(
"Here are the notes from today's standup:\n\n- API integration on track\n- Need to resolve the caching issue\n- ",
),
messageId: '<draft-1@example.com>',
},
{
id: 'demo-email-draft-recruiter',
threadId: 'demo-thread-draft-recruiter',
mailboxIds: { 'demo-mailbox-drafts': true },
keywords: { $seen: true, $draft: true },
size: 720,
receivedAt: demoDate(0, -8),
from: [USER],
to: [{ name: 'Jennifer Hayes', email: 'jennifer@talent-partners.example' }],
subject: 'Re: Senior role - Distributed Systems',
sentAt: demoDate(0, -8),
preview: "Hi Jennifer, thanks for reaching out. I'm not actively looking, but the role sounds interesting enough that...",
hasAttachment: false,
...textOnly(
"Hi Jennifer,\n\nThanks for reaching out. I'm not actively looking, but the role sounds interesting enough that I'd be open to a quick call. A few questions before we set something up:\n\n- ",
),
messageId: '<draft-recruiter@example.com>',
},
// ── Trash ───────────────────────────────────────────────────
{
@@ -225,15 +616,14 @@ export function createDemoEmails(): Email[] {
size: 15200,
receivedAt: demoDate(-5, -3),
from: [{ name: 'Promo Store', email: 'deals@promostore.example' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
to: [USER],
subject: '🎉 Flash Sale: 50% Off Everything!',
sentAt: demoDate(-5, -3),
preview: 'Limited time offer! Get 50% off all items in our store...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-14', size: 400, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Limited time offer! Get 50% off all items in our store. Use code FLASH50 at checkout.' },
},
...textOnly(
'Limited time offer! Get 50% off all items in our store. Use code FLASH50 at checkout.',
),
messageId: '<promo-1@promostore.example>',
},
{
@@ -244,15 +634,14 @@ export function createDemoEmails(): Email[] {
size: 2300,
receivedAt: demoDate(-7, 0),
from: [{ name: 'System Notification', email: 'noreply@service.example' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
to: [USER],
subject: 'Your password was changed',
sentAt: demoDate(-7, 0),
preview: 'Your account password was successfully changed on...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-15', size: 200, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Your account password was successfully changed. If you did not make this change, please contact support immediately.' },
},
...textOnly(
'Your account password was successfully changed. If you did not make this change, please contact support immediately.',
),
messageId: '<notification-1@service.example>',
},
@@ -265,15 +654,14 @@ export function createDemoEmails(): Email[] {
size: 4500,
receivedAt: demoDate(-2, -7),
from: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
to: [USER],
subject: '[Project] Sprint Planning Agenda',
sentAt: demoDate(-2, -7),
preview: 'Here\'s the agenda for next week\'s sprint planning session...',
preview: "Here's the agenda for next week's sprint planning session...",
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-16', size: 600, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Hi team,\n\nHere\'s the agenda for next week\'s sprint planning:\n\n1. Review previous sprint velocity\n2. Discuss tech debt items\n3. Prioritize backlog\n4. Assign story points\n5. Capacity planning\n\nPlease come prepared with your updates.\n\nThanks,\nAlice' },
},
...textOnly(
"Hi team,\n\nHere's the agenda for next week's sprint planning:\n\n1. Review previous sprint velocity\n2. Discuss tech debt items\n3. Prioritize backlog\n4. Assign story points\n5. Capacity planning\n\nPlease come prepared with your updates.\n\nThanks,\nAlice",
),
messageId: '<project-1@example.com>',
},
{
@@ -284,17 +672,37 @@ export function createDemoEmails(): Email[] {
size: 3200,
receivedAt: demoDate(0, -8),
from: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
to: [USER],
subject: '[Project] API Rate Limiting Discussion',
sentAt: demoDate(0, -8),
preview: 'I\'ve been thinking about our rate limiting approach and wanted to propose a few changes...',
preview: "I've been thinking about our rate limiting approach and wanted to propose a few changes...",
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-17', size: 480, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Hey,\n\nI\'ve been thinking about our rate limiting approach and wanted to propose:\n\n1. Token bucket algorithm instead of fixed window\n2. Per-endpoint limits rather than global\n3. Graduated response (warn → throttle → block)\n\nThoughts? I can put together a more detailed RFC if we agree on the direction.\n\n- Bob' },
},
...textOnly(
"Hey,\n\nI've been thinking about our rate limiting approach and wanted to propose:\n\n1. Token bucket algorithm instead of fixed window\n2. Per-endpoint limits rather than global\n3. Graduated response (warn → throttle → block)\n\nThoughts? I can put together a more detailed RFC if we agree on the direction.\n\n- Bob",
),
messageId: '<project-2@example.com>',
},
{
id: 'demo-email-roadmap',
threadId: 'demo-thread-roadmap',
mailboxIds: { 'demo-mailbox-projects': true },
keywords: {},
size: 4900,
receivedAt: demoDate(-1, -15),
from: [{ name: 'Michael Torres', email: 'michael.torres@company.example' }],
to: [USER, { name: 'Alice Johnson', email: 'alice.johnson@example.com' }, { name: 'James Miller', email: 'james.miller@company.example' }],
subject: '[Project] Q1 2026 roadmap - first cut',
sentAt: demoDate(-1, -15),
preview: 'Attached is the first cut of the Q1 roadmap. Three themes: reliability, mobile, and the long-promised...',
hasAttachment: true,
...textOnly(
"Team,\n\nAttached is the first cut of the Q1 roadmap. Three themes:\n\n1. Reliability (Alice's team)\n2. Mobile parity (cross-functional)\n3. The long-promised search rework (James, this is mostly on you)\n\nLet's leave comments in the doc rather than do a meeting - I'd rather have the meeting be the *decisions*, not the discussion. Closing comments end-of-week.\n\nM",
),
attachments: [
{ partId: 'att-7', blobId: 'demo-blob-att-7', size: 84000, name: 'Q1-2026-roadmap-v0.pdf', type: 'application/pdf' },
],
messageId: '<roadmap-q1-2026@company.example>',
},
// ── Archive ─────────────────────────────────────────────────
{
@@ -304,18 +712,35 @@ export function createDemoEmails(): Email[] {
keywords: { $seen: true },
size: 2600,
receivedAt: demoDate(-14, -6),
from: [{ name: 'HR Department', email: 'hr@company.example' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
from: [{ name: 'Maria Lopez', email: 'maria.lopez@company.example' }],
to: [USER],
subject: 'Updated PTO Policy - Effective January 1',
sentAt: demoDate(-14, -6),
preview: 'Please review the updated PTO policy that takes effect January 1st...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-18', size: 380, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Dear team,\n\nPlease review the updated PTO policy effective January 1st. Key changes include:\n\n- Increased annual allowance from 20 to 25 days\n- Flexible half-day options\n- Rollover limit increased to 10 days\n\nPlease acknowledge receipt.\n\nBest,\nHR Department' },
},
...textOnly(
'Dear team,\n\nPlease review the updated PTO policy effective January 1st. Key changes include:\n\n- Increased annual allowance from 20 to 25 days\n- Flexible half-day options\n- Rollover limit increased to 10 days\n\nPlease acknowledge receipt.\n\nBest,\nMaria - People Ops',
),
messageId: '<hr-policy-1@company.example>',
},
{
id: 'demo-email-archive-support',
threadId: 'demo-thread-archive-support',
mailboxIds: { 'demo-mailbox-archive': true },
keywords: { $seen: true },
size: 3400,
receivedAt: demoDate(-21, -4),
from: [{ name: 'Fastmail Support', email: 'support@fastmail.com' }],
to: [USER],
subject: 'Re: Ticket #438201 - DKIM signing fails on cross-account aliases',
sentAt: demoDate(-21, -4),
preview: "Thanks for the additional logs. We were able to reproduce on our side - the issue was indeed the alias resolution...",
hasAttachment: false,
...textOnly(
"Hi,\n\nThanks for the additional logs. We were able to reproduce on our side - the issue was indeed the alias resolution path skipping the DKIM signer step. Fix has been deployed to the AU and SY clusters; EU rolls out tomorrow.\n\nResolved on our end. Please reopen if you see anything related.\n\nBest,\nClaire - Fastmail Support",
),
messageId: '<ticket-438201-resolved@fastmail.com>',
},
// ── Receipts ────────────────────────────────────────────────
{
@@ -325,17 +750,37 @@ export function createDemoEmails(): Email[] {
keywords: { $seen: true },
size: 5200,
receivedAt: demoDate(-3, -12),
from: [{ name: 'Cloud Services', email: 'billing@cloudprovider.example' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
subject: 'Payment Receipt - Invoice #INV-2024-1042',
from: [{ name: 'Hetzner', email: 'billing@hetzner.com' }],
to: [USER],
subject: 'Invoice #INV-2024-1042 - €49.99 (paid)',
sentAt: demoDate(-3, -12),
preview: 'Your payment of $49.99 has been processed successfully...',
preview: 'Your payment of 49.99 has been processed successfully...',
hasAttachment: true,
...textOnly(
'Payment Confirmation\n\nAmount: €49.99\nDate: 3 days ago\nInvoice: INV-2024-1042\nService: CX22 dedicated (Helsinki, monthly)\n\nThank you for your payment.',
),
attachments: [
{ partId: 'att-8', blobId: 'demo-blob-att-8', size: 28000, name: 'INV-2024-1042.pdf', type: 'application/pdf' },
],
messageId: '<receipt-1@hetzner.com>',
},
{
id: 'demo-email-receipts-domain',
threadId: 'demo-thread-receipts-domain',
mailboxIds: { 'demo-mailbox-receipts': true },
keywords: { $seen: true },
size: 3100,
receivedAt: demoDate(-9, -8),
from: [{ name: 'Porkbun', email: 'support@porkbun.com' }],
to: [USER],
subject: 'Renewal confirmation - example.com (1 year)',
sentAt: demoDate(-9, -8),
preview: 'Your domain example.com has been renewed for 1 year. Next renewal: 11 months from today.',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-19', size: 350, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Payment Confirmation\n\nAmount: $49.99\nDate: Processing date\nInvoice: INV-2024-1042\nService: Cloud Hosting (Standard Plan)\n\nThank you for your payment.' },
},
messageId: '<receipt-1@cloudprovider.example>',
...textOnly(
"Hi,\n\nYour domain example.com has been renewed for 1 year.\n\nAmount: $11.06\nNext renewal: 11 months from today\nAutorenew: on\n\nReply to this email if you need a tax-receipt-style invoice.\n\n- Porkbun",
),
messageId: '<renewal-example.com@porkbun.com>',
},
// ── Spam ────────────────────────────────────────────────────
@@ -347,16 +792,51 @@ export function createDemoEmails(): Email[] {
size: 8900,
receivedAt: demoDate(-1, -9),
from: [{ name: 'Prize Center', email: 'winner@totallylegit.example' }],
to: [{ name: 'Demo User', email: 'demo@example.com' }],
to: [USER],
subject: 'Congratulations! You Won $1,000,000!!!',
sentAt: demoDate(-1, -9),
preview: 'Dear lucky winner, you have been selected to receive one million dollars...',
hasAttachment: false,
textBody: [{ partId: '1', blobId: 'blob-20', size: 500, type: 'text/plain' }],
bodyValues: {
'1': { value: 'Dear lucky winner,\n\nYou have been selected to receive ONE MILLION DOLLARS! Click below to claim your prize immediately.\n\n[This is a demo spam email]' },
},
...textOnly(
'Dear lucky winner,\n\nYou have been selected to receive ONE MILLION DOLLARS! Click below to claim your prize immediately.\n\n[This is a demo spam email]',
),
messageId: '<spam-1@totallylegit.example>',
},
{
id: 'demo-email-spam-phish',
threadId: 'demo-thread-spam-phish',
mailboxIds: { 'demo-mailbox-junk': true },
keywords: {},
size: 4600,
receivedAt: demoDate(-2, -3),
from: [{ name: 'Secure Banking', email: 'security-alert@secur1ty-bank.example' }],
to: [USER],
subject: 'URGENT: Unusual activity on your account - verify within 24 hours',
sentAt: demoDate(-2, -3),
preview: "We've detected suspicious activity. Click below to verify your identity or your account will be suspended...",
hasAttachment: false,
...textOnly(
"We've detected suspicious activity on your account. To prevent suspension, please verify your details within 24 hours by clicking the link below.\n\n[Phishing demo - never click links like this in real life.]",
),
messageId: '<phish-1@secur1ty-bank.example>',
},
{
id: 'demo-email-spam-crypto',
threadId: 'demo-thread-spam-crypto',
mailboxIds: { 'demo-mailbox-junk': true },
keywords: {},
size: 6800,
receivedAt: demoDate(-3, -19),
from: [{ name: 'CryptoGrowth Daily', email: 'invest@cryptogrowth.example' }],
to: [USER],
subject: '🚀 The coin Elon won\'t tell you about - 1000x potential',
sentAt: demoDate(-3, -19),
preview: 'Three early backers turned $500 into $5M in 90 days. Today, you have a chance to get in even earlier...',
hasAttachment: false,
...textOnly(
'Three early backers turned $500 into $5M in 90 days. Today, you have a chance to get in even earlier. Limited spots. No experience needed.\n\n[Demo spam.]',
),
messageId: '<spam-crypto@cryptogrowth.example>',
},
];
}
+8 -7
View File
@@ -3,15 +3,16 @@ import type { Mailbox } from '@/lib/jmap/types';
const RIGHTS_SYSTEM = { mayReadItems: true, mayAddItems: true, mayRemoveItems: true, maySetSeen: true, maySetKeywords: true, mayCreateChild: true, mayRename: false, mayDelete: false, maySubmit: true };
const RIGHTS_CUSTOM = { ...RIGHTS_SYSTEM, mayRename: true, mayDelete: true };
// Counts must stay in sync with createDemoEmails() in fixtures/emails.ts.
export function createDemoMailboxes(): Mailbox[] {
return [
{ id: 'demo-mailbox-inbox', name: 'Inbox', role: 'inbox', sortOrder: 1, totalEmails: 12, unreadEmails: 5, totalThreads: 10, unreadThreads: 4, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-sent', name: 'Sent', role: 'sent', sortOrder: 2, totalEmails: 8, unreadEmails: 0, totalThreads: 8, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-drafts', name: 'Drafts', role: 'drafts', sortOrder: 3, totalEmails: 1, unreadEmails: 0, totalThreads: 1, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-inbox', name: 'Inbox', role: 'inbox', sortOrder: 1, totalEmails: 22, unreadEmails: 13, totalThreads: 20, unreadThreads: 12, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-sent', name: 'Sent', role: 'sent', sortOrder: 2, totalEmails: 3, unreadEmails: 0, totalThreads: 3, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-drafts', name: 'Drafts', role: 'drafts', sortOrder: 3, totalEmails: 2, unreadEmails: 0, totalThreads: 2, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-trash', name: 'Trash', role: 'trash', sortOrder: 5, totalEmails: 2, unreadEmails: 0, totalThreads: 2, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-archive', name: 'Archive', role: 'archive', sortOrder: 4, totalEmails: 4, unreadEmails: 0, totalThreads: 4, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-junk', name: 'Spam', role: 'junk', sortOrder: 6, totalEmails: 3, unreadEmails: 1, totalThreads: 3, unreadThreads: 1, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-projects', name: 'Projects', sortOrder: 10, totalEmails: 5, unreadEmails: 2, totalThreads: 5, unreadThreads: 2, myRights: RIGHTS_CUSTOM, isSubscribed: true },
{ id: 'demo-mailbox-receipts', name: 'Receipts', sortOrder: 11, totalEmails: 3, unreadEmails: 0, totalThreads: 3, unreadThreads: 0, myRights: RIGHTS_CUSTOM, isSubscribed: true },
{ id: 'demo-mailbox-archive', name: 'Archive', role: 'archive', sortOrder: 4, totalEmails: 2, unreadEmails: 0, totalThreads: 2, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-junk', name: 'Spam', role: 'junk', sortOrder: 6, totalEmails: 3, unreadEmails: 3, totalThreads: 3, unreadThreads: 3, myRights: RIGHTS_SYSTEM, isSubscribed: true },
{ id: 'demo-mailbox-projects', name: 'Projects', sortOrder: 10, totalEmails: 3, unreadEmails: 2, totalThreads: 3, unreadThreads: 2, myRights: RIGHTS_CUSTOM, isSubscribed: true },
{ id: 'demo-mailbox-receipts', name: 'Receipts', sortOrder: 11, totalEmails: 2, unreadEmails: 0, totalThreads: 2, unreadThreads: 0, myRights: RIGHTS_CUSTOM, isSubscribed: true },
];
}
+21 -6
View File
@@ -58,24 +58,39 @@ export function sanitizeEmailHtmlForIframe(html: string): string {
/**
* Sanitize HTML signature with stricter rules
* Only allows basic formatting, no external resources
* Allows basic formatting plus <img> for company logos
*/
export const SIGNATURE_SANITIZE_CONFIG = {
ALLOWED_TAGS: ['p', 'br', 'b', 'strong', 'i', 'em', 'u', 'a', 'span', 'div'],
ALLOWED_ATTR: ['href', 'style', 'class'],
ALLOWED_TAGS: ['p', 'br', 'b', 'strong', 'i', 'em', 'u', 'a', 'span', 'div', 'img'],
ALLOWED_ATTR: ['href', 'style', 'class', 'src', 'alt', 'width', 'height', 'title'],
ALLOW_DATA_ATTR: false,
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'img', 'video', 'audio'],
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'video', 'audio'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover'],
};
/**
* Sanitize HTML signature for storage and display
* Sanitize HTML signature for storage and display.
* img src is restricted to https: or base64-embedded raster data: URIs
* (png/jpeg/gif/webp). SVG is excluded because DOMPurify cannot inspect
* bytes inside a data: URI. Images with a disallowed src are removed
* entirely so they don't render as broken-image icons.
* @param html - User-provided HTML signature
* @returns Sanitized signature (no scripts, no external resources)
*/
export function sanitizeSignatureHtml(html: string): string {
if (!html?.trim()) return '';
return DOMPurify.sanitize(html, SIGNATURE_SANITIZE_CONFIG);
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName !== 'IMG') return;
const src = node.getAttribute('src');
if (!src || !/^(?:https:\/\/|data:image\/(?:png|jpe?g|gif|webp);base64,)/i.test(src)) {
node.remove();
}
});
try {
return DOMPurify.sanitize(html, SIGNATURE_SANITIZE_CONFIG);
} finally {
DOMPurify.removeAllHooks();
}
}
/**
+189
View File
@@ -0,0 +1,189 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
export class ImpersonationJwtError extends Error {
status: number;
code: string;
constructor(code: string, message: string, status: number = 401) {
super(message);
this.name = 'ImpersonationJwtError';
this.code = code;
this.status = status;
}
}
export interface ImpersonationClaims {
iss: string;
iat: number;
exp: number;
nbf?: number;
jti: string;
mailbox: string;
tenant_id?: string;
actor_user_id?: string;
}
const MAX_TOKEN_LIFETIME_SEC = 300;
const CLOCK_SKEW_SEC = 60;
const MIN_SECRET_LENGTH = 32;
function base64UrlDecode(input: string): Buffer {
const pad = input.length % 4 === 0 ? 0 : 4 - (input.length % 4);
const b64 = input.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat(pad);
return Buffer.from(b64, 'base64');
}
function parseSegment(segment: string): unknown {
try {
return JSON.parse(base64UrlDecode(segment).toString('utf8'));
} catch {
throw new ImpersonationJwtError('malformed', 'Malformed JWT segment', 400);
}
}
function assertString(value: unknown, field: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new ImpersonationJwtError('claims', `Missing or invalid '${field}' claim`);
}
return value;
}
function assertNumber(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new ImpersonationJwtError('claims', `Missing or invalid '${field}' claim`);
}
return value;
}
/**
* Verify an HS256 JWT for master-user impersonation. Returns the validated
* claims on success; throws ImpersonationJwtError otherwise.
*
* Caller must perform replay-protection (jti tracking) on the returned claims.
*/
export function verifyImpersonationJwt(
token: string,
secret: string,
options: { expectedIssuer?: string; now?: number } = {},
): ImpersonationClaims {
if (typeof token !== 'string' || token.length === 0) {
throw new ImpersonationJwtError('malformed', 'Missing token', 400);
}
if (typeof secret !== 'string' || secret.length < MIN_SECRET_LENGTH) {
throw new ImpersonationJwtError(
'config',
`BULWARK_JWT_AUTH_SECRET must be at least ${MIN_SECRET_LENGTH} characters`,
500,
);
}
const parts = token.split('.');
if (parts.length !== 3) {
throw new ImpersonationJwtError('malformed', 'Token must have 3 segments', 400);
}
const [headerB64, payloadB64, sigB64] = parts;
// Header — reject anything but HS256 BEFORE attempting signature verification.
const header = parseSegment(headerB64) as Record<string, unknown>;
if (header.alg !== 'HS256') {
throw new ImpersonationJwtError('alg', `Unsupported alg '${String(header.alg)}'`);
}
if (header.typ !== undefined && header.typ !== 'JWT') {
throw new ImpersonationJwtError('alg', `Unsupported typ '${String(header.typ)}'`);
}
// Signature — constant-time compare.
const expected = createHmac('sha256', secret).update(`${headerB64}.${payloadB64}`).digest();
const provided = base64UrlDecode(sigB64);
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
throw new ImpersonationJwtError('signature', 'Invalid signature');
}
// Claims.
const payload = parseSegment(payloadB64) as Record<string, unknown>;
const iss = assertString(payload.iss, 'iss');
if (options.expectedIssuer && iss !== options.expectedIssuer) {
throw new ImpersonationJwtError('iss', `Unexpected issuer '${iss}'`);
}
const iat = assertNumber(payload.iat, 'iat');
const exp = assertNumber(payload.exp, 'exp');
const jti = assertString(payload.jti, 'jti');
const mailbox = assertString(payload.mailbox, 'mailbox');
// Mailbox MUST NOT contain '%' or ':' — those would inject into the
// master-user auth header.
if (mailbox.includes('%') || mailbox.includes(':')) {
throw new ImpersonationJwtError('mailbox', "mailbox must not contain '%' or ':'");
}
const nowSec = options.now ?? Math.floor(Date.now() / 1000);
if (typeof payload.nbf === 'number' && nowSec + CLOCK_SKEW_SEC < payload.nbf) {
throw new ImpersonationJwtError('nbf', 'Token not yet valid');
}
if (nowSec - CLOCK_SKEW_SEC > exp) {
throw new ImpersonationJwtError('exp', 'Token expired');
}
if (iat - CLOCK_SKEW_SEC > nowSec) {
throw new ImpersonationJwtError('iat', 'Token issued in the future');
}
// Hard ceiling on lifetime — refuse long-lived handoff tokens even if the
// signer asked for one.
if (exp - iat > MAX_TOKEN_LIFETIME_SEC) {
throw new ImpersonationJwtError('lifetime', `Token lifetime exceeds ${MAX_TOKEN_LIFETIME_SEC}s ceiling`);
}
const claims: ImpersonationClaims = { iss, iat, exp, jti, mailbox };
if (typeof payload.nbf === 'number') claims.nbf = payload.nbf;
if (typeof payload.tenant_id === 'string') claims.tenant_id = payload.tenant_id;
if (typeof payload.actor_user_id === 'string') claims.actor_user_id = payload.actor_user_id;
return claims;
}
// ─── Replay protection ──────────────────────────────────────────
// In-memory LRU keyed by jti. Entries expire automatically once their
// underlying JWT could no longer be replayed (exp + skew). On a multi-pod
// deployment each pod has its own cache; that's acceptable because a token
// stolen mid-flight could only be replayed against the pod that already
// consumed it (and that pod will reject it). For stronger guarantees,
// platforms can issue per-pod-routed tokens or front Bulwark with a
// single-leader load balancer for the impersonate route.
const REPLAY_CACHE_MAX = 4096;
class ReplayCache {
private entries = new Map<string, number>(); // jti -> exp epoch seconds
/** Returns true if jti was not previously seen and has been recorded. */
consume(jti: string, exp: number, now: number = Math.floor(Date.now() / 1000)): boolean {
this.prune(now);
if (this.entries.has(jti)) return false;
if (this.entries.size >= REPLAY_CACHE_MAX) {
// Evict the oldest entry — Map preserves insertion order.
const first = this.entries.keys().next().value;
if (first !== undefined) this.entries.delete(first);
}
this.entries.set(jti, exp);
return true;
}
private prune(now: number): void {
for (const [jti, exp] of this.entries) {
if (exp + CLOCK_SKEW_SEC < now) {
this.entries.delete(jti);
} else {
// Insertion order means later entries are no older than this one — but
// exp isn't strictly monotonic with insertion, so we can't break here.
}
}
}
get size(): number {
return this.entries.size;
}
clear(): void {
this.entries.clear();
}
}
export const impersonationReplayCache = new ReplayCache();
+51
View File
@@ -0,0 +1,51 @@
import { configManager } from '@/lib/admin/config-manager';
export interface ImpersonationConfig {
jwtSecret: string;
masterUser: string;
masterPassword: string;
expectedIssuer: string;
}
/**
* Returns null when impersonation is not configured the route MUST surface
* that as a 404 so an unconfigured deployment doesn't expose the endpoint.
*
* Required env:
* BULWARK_JWT_AUTH_SECRET (>= 32 chars)
* BULWARK_STALWART_MASTER_USER master account address (e.g. master@example.com)
* BULWARK_STALWART_MASTER_PASSWORD
*
* Optional env:
* BULWARK_JWT_AUTH_ISSUER (default: "platform-api/webmail")
*/
export function readImpersonationConfig(): ImpersonationConfig | null {
const jwtSecret = process.env.BULWARK_JWT_AUTH_SECRET ?? '';
const masterUser = process.env.BULWARK_STALWART_MASTER_USER ?? '';
const masterPassword = process.env.BULWARK_STALWART_MASTER_PASSWORD ?? '';
if (!jwtSecret || !masterUser || !masterPassword) return null;
return {
jwtSecret,
masterUser,
masterPassword,
expectedIssuer: process.env.BULWARK_JWT_AUTH_ISSUER ?? 'platform-api/webmail',
};
}
/**
* Resolves the upstream JMAP server URL the same way /api/auth/session does
* for trusted entries: the global `jmapServerUrl` admin setting, then the
* legacy env fallbacks. Returns null if none is configured.
*
* The impersonation flow is server-to-server (no user input), so we never
* accept a custom endpoint only admin-configured URLs.
*/
export async function resolveImpersonationServerUrl(): Promise<string | null> {
await configManager.ensureLoaded();
const url =
configManager.get<string>('jmapServerUrl', '') ||
process.env.JMAP_SERVER_URL ||
process.env.NEXT_PUBLIC_JMAP_SERVER_URL ||
'';
return url || null;
}
+9 -6
View File
@@ -1,13 +1,16 @@
const COOKIE_SAME_SITE = (process.env.COOKIE_SAME_SITE || 'lax') as 'lax' | 'none' | 'strict';
const COOKIE_SECURE = process.env.COOKIE_SECURE !== undefined
? process.env.COOKIE_SECURE === 'true'
: (COOKIE_SAME_SITE === 'none' || process.env.NODE_ENV === 'production');
import { configManager } from '@/lib/admin/config-manager';
type SameSite = 'lax' | 'none' | 'strict';
export function getCookieOptions() {
const sameSite = configManager.get<SameSite>('cookieSameSite', 'lax');
const secure = process.env.COOKIE_SECURE !== undefined
? process.env.COOKIE_SECURE === 'true'
: (sameSite === 'none' || process.env.NODE_ENV === 'production');
return {
httpOnly: true,
secure: COOKIE_SECURE,
sameSite: COOKIE_SAME_SITE,
secure,
sameSite,
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
+16 -2
View File
@@ -1,6 +1,20 @@
import { configManager } from '@/lib/admin/config-manager';
const DEFAULT_SCOPES = 'openid email profile';
const EXTRA_SCOPES = process.env.OAUTH_EXTRA_SCOPES || '';
export const OAUTH_SCOPES = process.env.OAUTH_SCOPES || (EXTRA_SCOPES ? `${DEFAULT_SCOPES} ${EXTRA_SCOPES}`.trim() : DEFAULT_SCOPES);
/**
* Resolve the OAuth scopes to request at authorize time.
*
* Reads admin override / OAUTH_SCOPES / OAUTH_EXTRA_SCOPES at call time so
* runtime env vars (and admin dashboard changes) take effect without a rebuild.
* Server-only: callers in the browser must read `oauthScopes` from /api/config.
*/
export function getOauthScopes(): string {
const explicit = configManager.get<string>('oauthScopes', '');
if (explicit) return explicit;
const extra = configManager.get<string>('oauthExtraScopes', '');
return extra ? `${DEFAULT_SCOPES} ${extra}`.trim() : DEFAULT_SCOPES;
}
export const REFRESH_TOKEN_COOKIE = 'jmap_rt';
export const REFRESH_TOKEN_SERVER_COOKIE = 'jmap_rts';
+14
View File
@@ -185,6 +185,15 @@ export interface PluginAPI {
i18n: PluginI18n;
ui: {
registerToolbarAction: (action: ToolbarAction) => Disposable;
/**
* Register a banner that renders at the very top of the authenticated app
* shell above the navigation rail, sidebar and content panes. Used for
* persistent global notices (impersonation, maintenance, etc.). The
* component receives `{ username, serverUrl }` as props.
*
* Requires the `ui:app-top-banner` permission.
*/
registerAppTopBanner: (component: React.ComponentType<Record<string, unknown>>) => Disposable;
registerEmailBanner: (factory: BannerFactory) => Disposable;
registerEmailFooter: (component: React.ComponentType) => Disposable;
registerSettingsSection: (section: SettingsSection) => Disposable;
@@ -710,6 +719,11 @@ export function createPluginAPI(plugin: InstalledPlugin): PluginAPI {
return registerSlot(plugin.id, 'email-banner', factory.render as unknown as React.ComponentType<Record<string, unknown>>, 100);
},
registerAppTopBanner: (component: React.ComponentType<Record<string, unknown>>) => {
requirePermission(plugin, 'ui:app-top-banner');
return registerSlot(plugin.id, 'app-top-banner', component, 100);
},
registerEmailFooter: (component: React.ComponentType) => {
requirePermission(plugin, 'ui:email-footer');
return registerSlot(plugin.id, 'email-footer', component as React.ComponentType<Record<string, unknown>>, 100);
+2 -1
View File
@@ -230,6 +230,7 @@ export interface InstalledPlugin {
export type SlotName =
| 'toolbar-actions'
| 'app-top-banner'
| 'email-banner'
| 'email-footer'
| 'composer-toolbar'
@@ -778,7 +779,7 @@ export const ALL_PERMISSIONS = [
'security:read',
'auth:observe',
'http:post', 'http:fetch',
'ui:observe', 'ui:toolbar', 'ui:email-banner', 'ui:email-footer',
'ui:observe', 'ui:toolbar', 'ui:app-top-banner', 'ui:email-banner', 'ui:email-footer',
'ui:composer-toolbar', 'ui:composer-sidebar',
'ui:sidebar-widget', 'ui:settings-section',
'ui:context-menu', 'ui:navigation-rail', 'ui:keyboard',
+1 -1
View File
@@ -73,7 +73,7 @@ export interface ReplyFromResolution {
/**
* Override for the outgoing `From:` header. Populated when the incoming
* message was delivered to an address on a domain the user owns (by
* identity) but that isn't itself a configured identity typical
* identity) but that isn't itself a configured identity - typical
* domain-catch-all deployments. When set, the composer should put this
* address (and `overrideName`) in the message's From header while sending
* through the chosen identity.
+364 -37
View File
@@ -48,7 +48,96 @@ function grammaticalGenderToVcardSex(gender: string): string {
}
function unfoldLines(vcf: string): string {
return vcf.replace(/\r\n[ \t]/g, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
// Normalize line endings first, then unfold continuation lines (RFC 6350 §3.2).
// Continuation lines start with a single SPACE or TAB; we must handle both
// CRLF (RFC-canonical) and LF-only files (common from Unix exporters).
return vcf
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
.replace(/\n[ \t]/g, "");
}
// RFC 6868 parameter value encoding — used inside parameter values only.
// Caret-encoded sequences: ^n → LF, ^^ → ^, ^' → DQUOTE.
function decodeParamValue(s: string): string {
let out = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === "^" && i + 1 < s.length) {
const next = s[i + 1];
if (next === "n") { out += "\n"; i++; continue; }
if (next === "^") { out += "^"; i++; continue; }
if (next === "'") { out += '"'; i++; continue; }
}
out += s[i];
}
return out;
}
// Split on delim, respecting DQUOTE-quoted spans (RFC 6350 §3.3 / §5).
function splitRespectingQuotes(s: string, delim: string): string[] {
const out: string[] = [];
let buf = "";
let inQuote = false;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch === '"') {
inQuote = !inQuote;
buf += ch;
continue;
}
if (ch === delim && !inQuote) {
out.push(buf);
buf = "";
continue;
}
buf += ch;
}
out.push(buf);
return out;
}
// Find the first ":" outside of a DQUOTE-quoted parameter value.
// Returns -1 when none. Needed because property params may carry quoted
// values that contain colons (e.g. ADR;LABEL="Suite 100:..." or X- params).
function findValueColon(line: string): number {
let inQuote = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (ch === '"') { inQuote = !inQuote; continue; }
if (ch === ":" && !inQuote) return i;
}
return -1;
}
// vCard properties may carry a group prefix: "item1.EMAIL:foo@bar".
// Strip the prefix and return the bare property name + params component.
function stripGroupPrefix(keyPart: string): string {
const dot = keyPart.indexOf(".");
if (dot < 0) return keyPart;
const before = keyPart.substring(0, dot);
// Only treat as group if the segment before the dot has no ";" (which would
// indicate it's actually a param boundary) and matches the RFC 6350 group
// grammar (ALPHA / DIGIT / "-").
if (before.includes(";")) return keyPart;
if (!/^[A-Za-z0-9-]+$/.test(before)) return keyPart;
return keyPart.substring(dot + 1);
}
// Strip URI scheme prefix from a value (e.g. "tel:+1-555" → "+1-555").
function stripUriScheme(val: string, scheme: string): string {
const prefix = `${scheme}:`;
if (val.toLowerCase().startsWith(prefix)) return val.substring(prefix.length);
return val;
}
function parsePrefParam(params: Record<string, string>): number | undefined {
if (params.PREF) {
const n = parseInt(params.PREF, 10);
if (!Number.isNaN(n)) return n;
}
// vCard 3.0 style: TYPE=PREF (no numeric value)
if (params.TYPE && /\bPREF\b/i.test(params.TYPE)) return 1;
return undefined;
}
// vCard 2.1 quoted-printable soft line breaks: a line ending in `=` continues
@@ -117,11 +206,18 @@ function encodeValue(val: string): string {
function parseParams(paramStr: string): Record<string, string> {
const params: Record<string, string> = {};
if (!paramStr) return params;
const parts = paramStr.split(";");
const parts = splitRespectingQuotes(paramStr, ";");
for (const part of parts) {
if (!part) continue;
const eq = part.indexOf("=");
if (eq > 0) {
params[part.substring(0, eq).toUpperCase()] = part.substring(eq + 1).replace(/"/g, "");
const name = part.substring(0, eq).toUpperCase();
// Strip surrounding quotes then RFC 6868 caret-decode.
// Strip surrounding DQUOTE if present (RFC 6350 §3.3). Pre-decode there
// are no literal LFs in a parameter value (those arrive as "^n" via
// RFC 6868), so we don't need the dotAll flag.
const rawVal = part.substring(eq + 1).replace(/^"(.*)"$/, "$1");
params[name] = decodeParamValue(rawVal);
} else {
const upper = part.toUpperCase();
if (upper === "QUOTED-PRINTABLE" || upper === "BASE64") {
@@ -190,9 +286,9 @@ export function parseVCard(vcfString: string): ContactCard[] {
}
if (current) {
const colonIdx = trimmed.indexOf(":");
const colonIdx = findValueColon(trimmed);
if (colonIdx < 1) continue;
const keyPart = trimmed.substring(0, colonIdx);
const keyPart = stripGroupPrefix(trimmed.substring(0, colonIdx));
const value = trimmed.substring(colonIdx + 1);
if (!current[keyPart]) current[keyPart] = [];
current[keyPart].push(value);
@@ -205,12 +301,18 @@ export function parseVCard(vcfString: string): ContactCard[] {
function buildContact(raw: Record<string, string[]>): ContactCard | null {
const id = `import-${generateUUID()}`;
const card: ContactCard = { id, addressBookIds: {} };
// Deferred BIRTHPLACE/DEATHPLACE values — attach to anniversary at end,
// because the BDAY/DEATHDATE entry may appear in any order.
let birthPlace: string | undefined;
let deathPlace: string | undefined;
for (const [fullKey, values] of Object.entries(raw)) {
const semiIdx = fullKey.indexOf(";");
const propName = (semiIdx > 0 ? fullKey.substring(0, semiIdx) : fullKey).toUpperCase();
const paramStr = semiIdx > 0 ? fullKey.substring(semiIdx + 1) : "";
// splitRespectingQuotes so a quoted param value containing ";" survives.
const segments = splitRespectingQuotes(fullKey, ";");
const propName = (segments.shift() || "").toUpperCase();
const paramStr = segments.join(";");
const params = parseParams(paramStr);
const pref = parsePrefParam(params);
const isQuotedPrintable = params.ENCODING?.toUpperCase() === "QUOTED-PRINTABLE";
@@ -257,8 +359,10 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
if (!card.emails) card.emails = {};
const idx = Object.keys(card.emails).length;
card.emails[`e${idx}`] = {
address: val,
address: stripUriScheme(val, "mailto"),
contexts: typeToContext(params.TYPE),
label: params["X-ABLABEL"] || undefined,
pref,
};
break;
}
@@ -267,9 +371,13 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
if (!card.phones) card.phones = {};
const idx = Object.keys(card.phones).length;
card.phones[`p${idx}`] = {
number: val,
// vCard 4.0 TEL is a URI value (RFC 6350 §6.4.1); strip the
// "tel:" scheme for storage as a bare number.
number: stripUriScheme(val, "tel"),
contexts: typeToContext(params.TYPE),
features: typeToPhoneFeatures(params.TYPE),
label: params["X-ABLABEL"] || undefined,
pref,
};
break;
}
@@ -295,7 +403,15 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
region: adrParts[4] || undefined,
postcode: adrParts[5] || undefined,
country: adrParts[6] || undefined,
// vCard 4.0 (RFC 9554 §3.2): CC param carries ISO country code,
// and LABEL/GEO/TZ params attach directly to the ADR.
countryCode: params.CC || undefined,
fullAddress: params.LABEL || undefined,
coordinates: params.GEO ? stripUriScheme(params.GEO, "geo") : undefined,
timeZone: params.TZ || undefined,
contexts: typeToContext(params.TYPE),
label: params["X-ABLABEL"] || undefined,
pref,
};
break;
}
@@ -318,8 +434,10 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
break;
case "KIND": {
// RFC 6350 §6.1.4 plus RFC 6473 (application).
const k = val.toLowerCase();
if (k === "group" || k === "individual" || k === "org") {
if (k === "group" || k === "individual" || k === "org" ||
k === "location" || k === "device" || k === "application") {
card.kind = k;
}
break;
@@ -336,7 +454,8 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
if (!card.media) card.media = {};
const idx = Object.keys(card.media).length;
const encoding = params.ENCODING?.toUpperCase();
const mediaType = params.TYPE || params.MEDIATYPE || "";
// vCard 4.0 uses MEDIATYPE; 3.0 reuses TYPE for the image kind.
const mediaType = params.MEDIATYPE || (params.TYPE && params.TYPE.includes("/") ? params.TYPE : (params.TYPE && /^(JPEG|JPG|PNG|GIF|WEBP|HEIC|BMP|SVG)$/i.test(params.TYPE) ? params.TYPE : "")) || "";
if (encoding === "B" || encoding === "BASE64") {
// Inline base64 photo - construct a data URI
const mime = mediaType.includes("/") ? mediaType : mediaType ? `image/${mediaType.toLowerCase()}` : "image/jpeg";
@@ -346,7 +465,7 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
mediaType: mime,
};
} else if (val.startsWith("data:") || val.startsWith("http://") || val.startsWith("https://")) {
// URI value (data URI or URL)
// vCard 4.0 URI value (data URI or URL) — no ENCODING param.
card.media[`m${idx}`] = {
kind: "photo",
uri: val,
@@ -376,28 +495,36 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
card.onlineServices[`u${idx}`] = {
uri: val,
contexts: typeToContext(params.TYPE),
label: params.TYPE?.toLowerCase() === "home" || params.TYPE?.toLowerCase() === "work" ? undefined : params.TYPE,
label: params["X-ABLABEL"] ||
(params.TYPE?.toLowerCase() === "home" || params.TYPE?.toLowerCase() === "work" ? undefined : params.TYPE),
pref,
};
break;
}
case "IMPP":
case "X-SOCIALPROFILE": {
case "X-SOCIALPROFILE":
case "SOCIALPROFILE": {
// RFC 9554 §3.7 introduces SOCIALPROFILE; treat the same as IMPP/X-SOCIALPROFILE.
if (!card.onlineServices) card.onlineServices = {};
const idx = Object.keys(card.onlineServices).length;
const svc: ContactOnlineService = {
uri: val,
contexts: typeToContext(params.TYPE),
pref,
};
if (params["X-SERVICE-TYPE"]) {
svc.service = params["X-SERVICE-TYPE"];
} else if (propName === "X-SOCIALPROFILE" && params.TYPE) {
} else if (params.SERVICE) {
svc.service = params.SERVICE;
} else if ((propName === "X-SOCIALPROFILE" || propName === "SOCIALPROFILE") && params.TYPE) {
const typeVal = params.TYPE.toLowerCase();
if (typeVal !== "work" && typeVal !== "home") {
svc.service = params.TYPE;
}
}
if (params["X-USER"]) svc.user = params["X-USER"];
if (params["X-ABLABEL"]) svc.label = params["X-ABLABEL"];
card.onlineServices[`u${idx}`] = svc;
break;
}
@@ -408,6 +535,14 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
break;
}
case "BIRTHPLACE": {
// RFC 6474 §2.1. Stash the location and attach to the birth
// anniversary at the end of buildContact, since BDAY may appear
// either before or after BIRTHPLACE in the vCard.
birthPlace = val;
break;
}
case "ANNIVERSARY":
case "X-ANNIVERSARY": {
if (!card.anniversaries) card.anniversaries = {};
@@ -424,6 +559,12 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
break;
}
case "DEATHPLACE": {
// RFC 6474 §2.2.
deathPlace = val;
break;
}
case "CATEGORIES": {
if (!card.keywords) card.keywords = {};
const cats = val.split(",").map(c => c.trim()).filter(Boolean);
@@ -438,6 +579,7 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
const idx = Object.keys(card.cryptoKeys).length;
card.cryptoKeys[`k${idx}`] = {
uri: val,
mediaType: params.MEDIATYPE || (params.TYPE && params.TYPE.includes("/") ? params.TYPE : undefined),
contexts: typeToContext(params.TYPE),
};
break;
@@ -445,9 +587,15 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
case "RELATED": {
if (!card.relatedTo) card.relatedTo = {};
const relType = params.TYPE?.toLowerCase();
// RFC 6350 §6.6.6: TYPE may be a comma-separated list (or
// multi-valued via repeated params); convert to relation map.
const relation: Record<string, boolean> = {};
if (relType) relation[relType] = true;
if (params.TYPE) {
for (const t of params.TYPE.split(",")) {
const norm = t.trim().toLowerCase();
if (norm) relation[norm] = true;
}
}
card.relatedTo[val] = { relation: Object.keys(relation).length > 0 ? relation : undefined };
break;
}
@@ -458,6 +606,7 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
card.preferredLanguages[`l${idx}`] = {
language: val,
contexts: typeToContext(params.TYPE),
pref,
};
break;
}
@@ -494,16 +643,22 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
}
case "GENDER": {
// vCard 4.0 §6.2.7: sex-component[;identity-component]. We map the
// sex letter to JSContact's grammaticalGender and stuff the free-
// form identity into pronouns (a coarse approximation; RFC 9554's
// PRONOUNS / GRAMGENDER, handled below, are preferred when present).
const gParts = val.split(";");
const sexCode = gParts[0]?.toUpperCase();
const identityText = gParts[1];
if (sexCode || identityText) {
card.speakToAs = {};
if (!card.speakToAs) card.speakToAs = {};
if (sexCode) {
card.speakToAs.grammaticalGender = vcardSexToGrammaticalGender(sexCode);
}
if (identityText) {
card.speakToAs.pronouns = { p0: { pronouns: identityText } };
if (!card.speakToAs.pronouns) card.speakToAs.pronouns = {};
const pkey = `p${Object.keys(card.speakToAs.pronouns).length}`;
card.speakToAs.pronouns[pkey] = { pronouns: identityText };
}
}
break;
@@ -513,7 +668,9 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
if (!card.media) card.media = {};
const idx = Object.keys(card.media).length;
const encoding = params.ENCODING?.toUpperCase();
const mediaType = params.TYPE || params.MEDIATYPE || "";
// Prefer MEDIATYPE (vCard 4.0); fall back to TYPE only when it's a
// MIME type or a known image format token (vCard 3.0 idiom).
const mediaType = params.MEDIATYPE || (params.TYPE && (params.TYPE.includes("/") || /^(JPEG|JPG|PNG|GIF|WEBP|SVG)$/i.test(params.TYPE)) ? params.TYPE : "");
if (encoding === "B" || encoding === "BASE64") {
const mime = mediaType.includes("/") ? mediaType : mediaType ? `image/${mediaType.toLowerCase()}` : "image/png";
card.media[`m${idx}`] = {
@@ -535,7 +692,7 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
if (!card.media) card.media = {};
const idx = Object.keys(card.media).length;
const encoding = params.ENCODING?.toUpperCase();
const mediaType = params.TYPE || params.MEDIATYPE || "";
const mediaType = params.MEDIATYPE || (params.TYPE && (params.TYPE.includes("/") || /^(OGG|MP3|WAV|AAC|FLAC)$/i.test(params.TYPE)) ? params.TYPE : "");
if (encoding === "B" || encoding === "BASE64") {
const mime = mediaType.includes("/") ? mediaType : mediaType ? `audio/${mediaType.toLowerCase()}` : "audio/ogg";
card.media[`m${idx}`] = {
@@ -581,10 +738,110 @@ function buildContact(raw: Record<string, string[]>): ContactCard | null {
case "SOURCE":
card.source = val;
break;
// ---- RFC 6715 (EXPERTISE / HOBBY / INTEREST / ORG-DIRECTORY) ----
case "EXPERTISE":
case "HOBBY":
case "INTEREST": {
if (!card.personalInfo) card.personalInfo = {};
const idx = Object.keys(card.personalInfo).length;
const kind = propName.toLowerCase() as "expertise" | "hobby" | "interest";
const rawLevel = params.LEVEL?.toLowerCase();
// RFC 6715 levels: expertise uses beginner/average/expert; hobby/
// interest use high/medium/low. Normalize all into JSContact's
// high/medium/low triplet.
const levelMap: Record<string, "high" | "medium" | "low"> = {
beginner: "low", average: "medium", expert: "high",
low: "low", medium: "medium", high: "high",
};
const level = rawLevel ? levelMap[rawLevel] : undefined;
card.personalInfo[`i${idx}`] = { kind, value: val, level };
break;
}
case "ORG-DIRECTORY": {
// RFC 6715 §2.4 — directory URI for the contact's organization.
if (!card.directories) card.directories = {};
const idx = Object.keys(card.directories).length;
card.directories[`d${idx}`] = {
uri: val,
kind: "directory",
mediaType: params.MEDIATYPE || undefined,
};
break;
}
// ---- RFC 8605 (CONTACT-URI) ----
case "CONTACT-URI": {
if (!card.links) card.links = {};
const idx = Object.keys(card.links).length;
card.links[`l${idx}`] = {
uri: val,
kind: "contact",
pref,
};
break;
}
// ---- RFC 9554 vCard 4.0 extensions ----
case "CREATED":
card.created = val;
break;
case "GRAMGENDER": {
// RFC 9554 §3.4 — grammatical gender (animate/common/feminine/masculine/neuter).
if (!card.speakToAs) card.speakToAs = {};
card.speakToAs.grammaticalGender = val.toLowerCase();
break;
}
case "PRONOUNS": {
// RFC 9554 §3.5 — free-form pronouns. May appear multiple times.
if (!card.speakToAs) card.speakToAs = {};
if (!card.speakToAs.pronouns) card.speakToAs.pronouns = {};
const pkey = `p${Object.keys(card.speakToAs.pronouns).length}`;
card.speakToAs.pronouns[pkey] = {
pronouns: val,
pref,
contexts: typeToContext(params.TYPE),
};
break;
}
// Silently swallow purely structural / sync metadata properties so
// they don't appear in any catch-all default.
case "VERSION":
case "XML":
case "CLIENTPIDMAP":
case "X-ABLABEL":
break;
}
}
}
// Attach BIRTHPLACE/DEATHPLACE to the matching anniversary, creating an
// anniversary entry if no BDAY/DEATHDATE was present.
if (birthPlace || deathPlace) {
if (!card.anniversaries) card.anniversaries = {};
if (birthPlace) {
let birth = Object.values(card.anniversaries).find(a => a.kind === "birth");
if (!birth) {
card.anniversaries.a0 = { kind: "birth", date: "" };
birth = card.anniversaries.a0;
}
birth.place = { fullAddress: birthPlace };
}
if (deathPlace) {
let death = Object.values(card.anniversaries).find(a => a.kind === "death");
if (!death) {
const key = `a${Object.keys(card.anniversaries).length}`;
card.anniversaries[key] = { kind: "death", date: "" };
death = card.anniversaries[key];
}
death.place = { fullAddress: deathPlace };
}
}
const hasName = card.name && (card.name.components?.length ?? 0) > 0 || !!card.name?.full;
const hasEmail = card.emails && Object.keys(card.emails).length > 0;
if (!hasName && !hasEmail && card.kind !== "group") return null;
@@ -640,8 +897,11 @@ function generateSingleVCard(contact: ContactCard): string {
if (contact.emails) {
for (const email of Object.values(contact.emails)) {
const type = contextToType(email.contexts);
const typeParam = type ? `;TYPE=${type}` : "";
lines.push(`EMAIL${typeParam}:${email.address}`);
const params: string[] = [];
if (type) params.push(`TYPE=${type}`);
if (email.pref) params.push(`PREF=${email.pref}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
lines.push(`EMAIL${paramStr}:${email.address}`);
}
}
@@ -655,8 +915,11 @@ function generateSingleVCard(contact: ContactCard): string {
if (phone.features[feat]) typeParts.push(feat.toUpperCase());
}
}
const typeParam = typeParts.length > 0 ? `;TYPE=${typeParts.join(",")}` : "";
lines.push(`TEL${typeParam}:${phone.number}`);
const params: string[] = [];
if (typeParts.length > 0) params.push(`TYPE=${typeParts.join(",")}`);
if (phone.pref) params.push(`PREF=${phone.pref}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
lines.push(`TEL${paramStr}:${phone.number}`);
}
}
@@ -681,7 +944,11 @@ function generateSingleVCard(contact: ContactCard): string {
if (contact.addresses) {
for (const addr of Object.values(contact.addresses)) {
const type = contextToType(addr.contexts);
const typeParam = type ? `;TYPE=${type}` : "";
const adrParams: string[] = [];
if (type) adrParams.push(`TYPE=${type}`);
if (addr.countryCode) adrParams.push(`CC=${addr.countryCode}`);
if (addr.pref) adrParams.push(`PREF=${addr.pref}`);
const paramStr = adrParams.length > 0 ? `;${adrParams.join(";")}` : "";
let street = addr.street || "";
let locality = addr.locality || "";
let region = addr.region || "";
@@ -707,7 +974,7 @@ function generateSingleVCard(contact: ContactCard): string {
postcode,
country,
];
lines.push(`ADR${typeParam}:${parts.map(encodeValue).join(";")}`);
lines.push(`ADR${paramStr}:${parts.map(encodeValue).join(";")}`);
}
}
@@ -715,11 +982,17 @@ function generateSingleVCard(contact: ContactCard): string {
for (const ann of Object.values(contact.anniversaries)) {
const dateStr = anniversaryDateToVcardString(ann.date);
if (ann.kind === "birth") {
lines.push(`BDAY:${dateStr}`);
if (dateStr) lines.push(`BDAY:${dateStr}`);
if (ann.place?.fullAddress) {
lines.push(`BIRTHPLACE:${encodeValue(ann.place.fullAddress)}`);
}
} else if (ann.kind === "wedding") {
lines.push(`ANNIVERSARY:${dateStr}`);
if (dateStr) lines.push(`ANNIVERSARY:${dateStr}`);
} else if (ann.kind === "death") {
lines.push(`DEATHDATE:${dateStr}`);
if (dateStr) lines.push(`DEATHDATE:${dateStr}`);
if (ann.place?.fullAddress) {
lines.push(`DEATHPLACE:${encodeValue(ann.place.fullAddress)}`);
}
}
}
}
@@ -732,13 +1005,17 @@ function generateSingleVCard(contact: ContactCard): string {
if (svc.service) params.push(`X-SERVICE-TYPE=${svc.service}`);
const ctxType = contextToType(svc.contexts);
if (ctxType) params.push(`TYPE=${ctxType}`);
if (svc.pref) params.push(`PREF=${svc.pref}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
lines.push(`IMPP${paramStr}:${svc.uri}`);
} else {
// Output as URL for plain web links
const type = contextToType(svc.contexts);
const typeParam = type ? `;TYPE=${type}` : "";
lines.push(`URL${typeParam}:${svc.uri}`);
const params: string[] = [];
if (type) params.push(`TYPE=${type}`);
if (svc.pref) params.push(`PREF=${svc.pref}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
lines.push(`URL${paramStr}:${svc.uri}`);
}
}
}
@@ -753,8 +1030,11 @@ function generateSingleVCard(contact: ContactCard): string {
if (contact.preferredLanguages) {
for (const lang of Object.values(contact.preferredLanguages)) {
const type = contextToType(lang.contexts);
const typeParam = type ? `;TYPE=${type}` : "";
lines.push(`LANG${typeParam}:${lang.language}`);
const params: string[] = [];
if (type) params.push(`TYPE=${type}`);
if (lang.pref) params.push(`PREF=${lang.pref}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
lines.push(`LANG${paramStr}:${lang.language}`);
}
}
@@ -769,8 +1049,50 @@ function generateSingleVCard(contact: ContactCard): string {
if (contact.cryptoKeys) {
for (const key of Object.values(contact.cryptoKeys)) {
const type = contextToType(key.contexts);
const typeParam = type ? `;TYPE=${type}` : "";
lines.push(`KEY${typeParam}:${key.uri}`);
const params: string[] = [];
if (type) params.push(`TYPE=${type}`);
if (key.mediaType) params.push(`MEDIATYPE=${key.mediaType}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
lines.push(`KEY${paramStr}:${key.uri}`);
}
}
if (contact.personalInfo) {
// RFC 6715 — emit EXPERTISE / HOBBY / INTEREST with LEVEL.
const levelOut: Record<string, Record<string, string>> = {
expertise: { high: "expert", medium: "average", low: "beginner" },
hobby: { high: "high", medium: "medium", low: "low" },
interest: { high: "high", medium: "medium", low: "low" },
};
for (const info of Object.values(contact.personalInfo)) {
const propMap: Record<string, string> = {
expertise: "EXPERTISE", hobby: "HOBBY", interest: "INTEREST",
};
const prop = propMap[info.kind];
if (!prop) continue;
const levelParam = info.level && levelOut[info.kind]?.[info.level]
? `;LEVEL=${levelOut[info.kind][info.level]}` : "";
lines.push(`${prop}${levelParam}:${encodeValue(info.value)}`);
}
}
if (contact.directories) {
for (const dir of Object.values(contact.directories)) {
const mt = dir.mediaType ? `;MEDIATYPE=${dir.mediaType}` : "";
lines.push(`ORG-DIRECTORY${mt}:${dir.uri}`);
}
}
if (contact.links) {
// RFC 8605 CONTACT-URI for kind=contact; everything else falls back to URL.
for (const link of Object.values(contact.links)) {
const params: string[] = [];
const type = contextToType(link.contexts);
if (type) params.push(`TYPE=${type}`);
if (link.pref) params.push(`PREF=${link.pref}`);
const paramStr = params.length > 0 ? `;${params.join(";")}` : "";
const prop = link.kind === "contact" ? "CONTACT-URI" : "URL";
lines.push(`${prop}${paramStr}:${link.uri}`);
}
}
@@ -844,6 +1166,11 @@ function generateSingleVCard(contact: ContactCard): string {
lines.push(`SOURCE:${contact.source}`);
}
if (contact.created) {
// RFC 9554 §3.1 — CREATED is a timestamp; emit as-is for round-trip.
lines.push(`CREATED:${contact.created}`);
}
lines.push("END:VCARD");
return lines.join("\r\n");
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Lenient semver comparison for the marketplace's `minAppVersion` gate.
*
* Parses "major.minor.patch" (any segment may be missing treated as 0)
* and ignores pre-release / build metadata. Returns negative, zero or
* positive in the same shape as Array.prototype.sort comparators.
*
* We intentionally do NOT pull in a full semver dependency: plugins
* declare minimum app versions as simple "X.Y.Z" strings and we only
* need a >= check.
*/
export function compareVersions(a: string, b: string): number {
const pa = parseVersion(a);
const pb = parseVersion(b);
for (let i = 0; i < 3; i++) {
if (pa[i] !== pb[i]) return pa[i] - pb[i];
}
return 0;
}
function parseVersion(v: string): [number, number, number] {
const cleaned = String(v || '').trim().replace(/^v/i, '');
// Drop pre-release / build metadata.
const core = cleaned.split(/[-+]/)[0];
const parts = core.split('.').map((p) => {
const n = parseInt(p, 10);
return Number.isFinite(n) ? n : 0;
});
return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];
}
/**
* True when `current` satisfies `required` (i.e. current >= required).
* Empty / null / undefined `required` is treated as no requirement.
*/
export function isVersionSatisfied(current: string, required: string | null | undefined): boolean {
if (!required) return true;
return compareVersions(current, required) >= 0;
}
+55 -17
View File
@@ -6,8 +6,21 @@
import type { IJMAPClient } from '@/lib/jmap/client-interface';
const DEVICE_CLIENT_ID_KEY = 'bulwark.push.deviceClientId.v1';
const SUBSCRIPTION_ID_KEY = 'bulwark.push.subscriptionId.v1';
// Per-account keys: a single browser may be signed in to multiple accounts,
// each with its own JMAP PushSubscription and its own relay record. Scoping
// the deviceClientId per account is what makes per-account notifications work
// at all - the relay keys subscriptions on subscriptionId (= deviceClientId),
// so a globally-shared key meant re-registering account B overwrote A.
const DEVICE_CLIENT_ID_PREFIX = 'bulwark.push.deviceClientId.v1.';
const SUBSCRIPTION_ID_PREFIX = 'bulwark.push.subscriptionId.v1.';
function deviceClientIdKey(accountId: string): string {
return DEVICE_CLIENT_ID_PREFIX + accountId;
}
function subscriptionIdKey(accountId: string): string {
return SUBSCRIPTION_ID_PREFIX + accountId;
}
const BASE_PATH = (process.env.NEXT_PUBLIC_BASE_PATH ?? '').replace(/\/+$/, '');
const SW_SCOPE = `${BASE_PATH}/`;
@@ -79,14 +92,24 @@ function randomDeviceClientId(): string {
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
function getOrCreateDeviceClientId(): string {
const existing = localStorage.getItem(DEVICE_CLIENT_ID_KEY);
function getOrCreateDeviceClientId(accountId: string): string {
const key = deviceClientIdKey(accountId);
const existing = localStorage.getItem(key);
if (existing) return existing;
const next = randomDeviceClientId();
localStorage.setItem(DEVICE_CLIENT_ID_KEY, next);
localStorage.setItem(key, next);
return next;
}
function anyOtherAccountHasSubscription(accountId: string): boolean {
const skip = subscriptionIdKey(accountId);
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && k !== skip && k.startsWith(SUBSCRIPTION_ID_PREFIX)) return true;
}
return false;
}
// PushManager.subscribe wants the VAPID public key as a BufferSource.
// Returning a Uint8Array<ArrayBuffer> (not the wider ArrayBufferLike that
// includes SharedArrayBuffer) keeps strict TS happy on lib.dom 2024+.
@@ -260,7 +283,8 @@ export async function enableWebPush(
});
}
const deviceClientId = getOrCreateDeviceClientId();
const accountId = params.client.getAccountId();
const deviceClientId = getOrCreateDeviceClientId(accountId);
await registerWithRelay({
relayBaseUrl,
@@ -278,7 +302,8 @@ export async function enableWebPush(
// Reuse the JMAP-side PushSubscription if the server still has it, just
// refreshing the expiry so it doesn't time out between sessions.
const existingSubs = await params.client.listPushSubscriptions().catch(() => []);
const storedServerId = localStorage.getItem(SUBSCRIPTION_ID_KEY);
const subIdKey = subscriptionIdKey(accountId);
const storedServerId = localStorage.getItem(subIdKey);
if (storedServerId) {
const match = existingSubs.find((s) => s.id === storedServerId);
if (match) {
@@ -286,7 +311,7 @@ export async function enableWebPush(
if (refreshed) return { subscriptionId: storedServerId };
await params.client.destroyPushSubscription(storedServerId).catch(() => undefined);
}
localStorage.removeItem(SUBSCRIPTION_ID_KEY);
localStorage.removeItem(subIdKey);
}
// Reap any leftover subscriptions still bound to this device. These pile
@@ -309,7 +334,7 @@ export async function enableWebPush(
const verificationCode = await pollVerificationCode(relayBaseUrl, deviceClientId);
await params.client.verifyPushSubscription(serverAssignedId, verificationCode);
localStorage.setItem(SUBSCRIPTION_ID_KEY, serverAssignedId);
localStorage.setItem(subIdKey, serverAssignedId);
return { subscriptionId: serverAssignedId };
}
@@ -320,37 +345,50 @@ export interface DisableWebPushParams {
}
// Best-effort teardown: clear the JMAP subscription, the relay mapping, and
// the browser PushSubscription. Any single failure is swallowed so the user
// always ends up in a "disabled" state locally.
// (only when no other accounts still need it) the browser-wide
// PushSubscription. Any single failure is swallowed so the user always ends
// up in a "disabled" state locally.
export async function disableWebPush(params: DisableWebPushParams): Promise<void> {
const relayBaseUrl = (params.relayBaseUrl ?? DEFAULT_RELAY_BASE_URL).replace(/\/+$/, '');
const accountId = params.client.getAccountId();
const storedServerId = localStorage.getItem(SUBSCRIPTION_ID_KEY);
const subIdKey = subscriptionIdKey(accountId);
const devIdKey = deviceClientIdKey(accountId);
const storedServerId = localStorage.getItem(subIdKey);
if (storedServerId) {
await params.client.destroyPushSubscription(storedServerId).catch(() => undefined);
localStorage.removeItem(SUBSCRIPTION_ID_KEY);
localStorage.removeItem(subIdKey);
}
const deviceClientId = localStorage.getItem(DEVICE_CLIENT_ID_KEY);
const deviceClientId = localStorage.getItem(devIdKey);
if (deviceClientId && relayBaseUrl) {
await fetch(
buildRelayUrl(relayBaseUrl, `/api/push/register/${encodeURIComponent(deviceClientId)}`),
{ method: 'DELETE' },
).catch(() => undefined);
}
// Keep the deviceClientId around so a later re-enable for this account
// reuses the same relay subscriptionId rather than scattering orphans.
if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
// The browser-wide PushSubscription is shared by every account on this
// origin, so only tear it down if no other account is still using it.
if (
!anyOtherAccountHasSubscription(accountId)
&& typeof navigator !== 'undefined'
&& 'serviceWorker' in navigator
) {
const registration = await navigator.serviceWorker.getRegistration(SW_SCOPE);
const sub = await registration?.pushManager.getSubscription();
if (sub) await sub.unsubscribe().catch(() => undefined);
}
}
export async function isWebPushEnabled(): Promise<boolean> {
export async function isWebPushEnabled(accountId: string): Promise<boolean> {
if (!isWebPushSupported()) return false;
if (Notification.permission !== 'granted') return false;
const registration = await navigator.serviceWorker.getRegistration(SW_SCOPE);
if (!registration) return false;
const sub = await registration.pushManager.getSubscription();
return sub !== null && localStorage.getItem(SUBSCRIPTION_ID_KEY) !== null;
return sub !== null && localStorage.getItem(subscriptionIdKey(accountId)) !== null;
}
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Napsat",
"compose_hint": "Napsat novou zprávu",
"no_subject": "(Bez předmětu)",
"no_body_content": "(Žádný obsah těla)",
"no_preview_available": "Náhled není k dispozici",
"loading_email": "Načítání zprávy...",
"loading": "Načítání...",
"reply": "Odpovědět",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Přepsat",
"toggle_on": "Zrušit přepsání",
"toggle_tooltip": "Volně upravujte jméno a adresu odesílatele. Pošta se stále odesílá přes vaši identitu mění se pouze viditelné záhlaví Od.",
"toggle_tooltip": "Volně upravujte jméno a adresu odesílatele. Pošta se stále odesílá přes vaši identitu - mění se pouze viditelné záhlaví Od.",
"name_label": "Jméno odesílatele",
"name_placeholder": "Jméno",
"email_label": "E-mailová adresa odesílatele",
@@ -2844,6 +2846,8 @@
"restart_title": "Úvodní průvodce",
"restart_desc": "Přehrát průvodce rozhraním krok za krokem",
"restart_button": "Spustit průvodce znovu",
"show_on_new_devices_title": "Zobrazit na nových zařízeních",
"show_on_new_devices_desc": "Přehrát uvítací banner a průvodce při prvním přihlášení na novém zařízení, i když jste je již dokončili jinde",
"sidebar_title": "Vaše poštovní schránky",
"sidebar_desc": "Toto je postranní panel se složkami. Kliknutím na libovolnou schránku zobrazíte její zprávy. Můžete vytvářet složky, přetahovat zprávy mezi nimi a okamžitě vidět počet nepřečtených e-mailů.",
"compose_title": "Napsat zprávu",
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Verfassen",
"compose_hint": "Neue Nachricht verfassen",
"no_subject": "(Kein Betreff)",
"no_body_content": "(Kein Inhalt verfügbar)",
"no_preview_available": "Keine Vorschau verfügbar",
"loading_email": "E-Mail wird geladen...",
"loading": "Lädt...",
"reply": "Antworten",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Überschreiben",
"toggle_on": "Überschreibung aufheben",
"toggle_tooltip": "Bearbeiten Sie Absendername und -adresse frei. Die E-Mail wird weiterhin über Ihre Identität gesendet nur die sichtbare Absenderkopfzeile ändert sich.",
"toggle_tooltip": "Bearbeiten Sie Absendername und -adresse frei. Die E-Mail wird weiterhin über Ihre Identität gesendet - nur die sichtbare Absenderkopfzeile ändert sich.",
"name_label": "Absendername",
"name_placeholder": "Name",
"email_label": "Absender-E-Mail-Adresse",
@@ -2844,6 +2846,8 @@
"restart_title": "Einführungstour",
"restart_desc": "Geführte Tour durch die Oberfläche erneut abspielen",
"restart_button": "Tour neu starten",
"show_on_new_devices_title": "Auf neuen Geräten anzeigen",
"show_on_new_devices_desc": "Zeige das Willkommensbanner und die Tour beim ersten Anmelden auf einem neuen Gerät erneut, auch wenn du sie bereits anderswo abgeschlossen hast",
"sidebar_title": "Ihre Postfächer",
"sidebar_desc": "Dies ist Ihre Ordner-Seitenleiste. Klicken Sie auf ein Postfach, um seine E-Mails anzuzeigen. Sie können Ordner erstellen, E-Mails zwischen ihnen verschieben und ungelesene Zähler auf einen Blick sehen.",
"compose_title": "E-Mail verfassen",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Compose",
"compose_hint": "Compose new message",
"no_subject": "(No Subject)",
"no_body_content": "(No body content available)",
"no_preview_available": "No preview available",
"loading_email": "Loading email...",
"loading": "Loading...",
"reply": "Reply",
@@ -568,7 +570,7 @@
"from_override": {
"toggle_off": "Override",
"toggle_on": "Cancel override",
"toggle_tooltip": "Edit the From name and address freely. Mail is still sent through your identity only the visible From header changes.",
"toggle_tooltip": "Edit the From name and address freely. Mail is still sent through your identity - only the visible From header changes.",
"name_label": "From name",
"name_placeholder": "Name",
"email_label": "From email address",
@@ -2867,6 +2869,8 @@
"restart_title": "Introductory tour",
"restart_desc": "Replay the guided walkthrough of the interface",
"restart_button": "Restart tour",
"show_on_new_devices_title": "Show on new devices",
"show_on_new_devices_desc": "Replay the welcome banner and tour the first time you sign in on a new device, even if you've already completed them elsewhere",
"sidebar_title": "Your mailboxes",
"sidebar_desc": "This is your folder sidebar. Click any mailbox to view its emails. You can create folders, drag emails between them, and see unread counts at a glance.",
"compose_title": "Compose an email",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Redactar",
"compose_hint": "Redactar nuevo mensaje",
"no_subject": "(Sin Asunto)",
"no_body_content": "(Sin contenido disponible)",
"no_preview_available": "Vista previa no disponible",
"loading_email": "Cargando correo...",
"loading": "Cargando...",
"reply": "Responder",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Anular",
"toggle_on": "Cancelar anulación",
"toggle_tooltip": "Edita libremente el nombre y la dirección del remitente. El correo aún se envía a través de tu identidad solo cambia el encabezado De visible.",
"toggle_tooltip": "Edita libremente el nombre y la dirección del remitente. El correo aún se envía a través de tu identidad - solo cambia el encabezado De visible.",
"name_label": "Nombre del remitente",
"name_placeholder": "Nombre",
"email_label": "Dirección de correo del remitente",
@@ -2844,6 +2846,8 @@
"restart_title": "Tour introductorio",
"restart_desc": "Repetir el recorrido guiado por la interfaz",
"restart_button": "Reiniciar tour",
"show_on_new_devices_title": "Mostrar en dispositivos nuevos",
"show_on_new_devices_desc": "Vuelve a mostrar el banner de bienvenida y el tour la primera vez que inicies sesión en un dispositivo nuevo, incluso si ya los completaste en otro lugar",
"sidebar_title": "Tus buzones",
"sidebar_desc": "Esta es tu barra lateral de carpetas. Haz clic en cualquier buzón para ver sus correos. Puedes crear carpetas, arrastrar correos entre ellas y ver los contadores de no leídos.",
"compose_title": "Redactar un correo",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Rédiger",
"compose_hint": "Rédiger un nouveau message",
"no_subject": "(Sans objet)",
"no_body_content": "(Aucun contenu disponible)",
"no_preview_available": "Aucun aperçu disponible",
"loading_email": "Chargement de l'email...",
"loading": "Chargement...",
"reply": "Répondre",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Remplacer",
"toggle_on": "Annuler le remplacement",
"toggle_tooltip": "Modifiez librement le nom et l'adresse d'expéditeur. Le courrier est toujours envoyé via votre identité seul l'en-tête De visible change.",
"toggle_tooltip": "Modifiez librement le nom et l'adresse d'expéditeur. Le courrier est toujours envoyé via votre identité - seul l'en-tête De visible change.",
"name_label": "Nom de l'expéditeur",
"name_placeholder": "Nom",
"email_label": "Adresse e-mail de l'expéditeur",
@@ -2844,6 +2846,8 @@
"restart_title": "Visite d'introduction",
"restart_desc": "Rejouer la visite guidée de l'interface",
"restart_button": "Relancer la visite",
"show_on_new_devices_title": "Afficher sur les nouveaux appareils",
"show_on_new_devices_desc": "Rejouer la bannière d'accueil et la visite lors de votre première connexion sur un nouvel appareil, même si vous les avez déjà terminées ailleurs",
"sidebar_title": "Vos boîtes mail",
"sidebar_desc": "Voici votre barre latérale de dossiers. Cliquez sur une boîte pour voir ses emails. Vous pouvez créer des dossiers, glisser des emails entre eux et voir les compteurs de non lus.",
"compose_title": "Rédiger un email",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Componi",
"compose_hint": "Componi nuovo messaggio",
"no_subject": "(Nessun oggetto)",
"no_body_content": "(Nessun contenuto disponibile)",
"no_preview_available": "Anteprima non disponibile",
"loading_email": "Caricamento messaggio...",
"loading": "Caricamento...",
"reply": "Rispondi",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Sovrascrivi",
"toggle_on": "Annulla sovrascrittura",
"toggle_tooltip": "Modifica liberamente nome e indirizzo del mittente. La posta viene comunque inviata tramite la tua identità cambia solo l'intestazione Da visibile.",
"toggle_tooltip": "Modifica liberamente nome e indirizzo del mittente. La posta viene comunque inviata tramite la tua identità - cambia solo l'intestazione Da visibile.",
"name_label": "Nome mittente",
"name_placeholder": "Nome",
"email_label": "Indirizzo email del mittente",
@@ -2844,6 +2846,8 @@
"restart_title": "Tour introduttivo",
"restart_desc": "Rivedi la guida dell'interfaccia",
"restart_button": "Riavvia il tour",
"show_on_new_devices_title": "Mostra sui nuovi dispositivi",
"show_on_new_devices_desc": "Rivedi il banner di benvenuto e il tour al primo accesso su un nuovo dispositivo, anche se li hai già completati altrove",
"sidebar_title": "Le tue caselle di posta",
"sidebar_desc": "Questa è la barra laterale delle cartelle. Clicca su una casella per vedere le email. Puoi creare cartelle, trascinare email tra loro e vedere i conteggi dei non letti.",
"compose_title": "Scrivi un'email",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "作成",
"compose_hint": "新しいメッセージを作成",
"no_subject": "(件名なし)",
"no_body_content": "(本文がありません)",
"no_preview_available": "プレビューは利用できません",
"loading_email": "メールを読み込み中...",
"loading": "読み込み中...",
"reply": "返信",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "上書き",
"toggle_on": "上書きを取り消す",
"toggle_tooltip": "差出人名とアドレスを自由に編集できます。メールは引き続きあなたのアイデンティティ経由で送信されます 表示される差出人ヘッダーのみが変更されます。",
"toggle_tooltip": "差出人名とアドレスを自由に編集できます。メールは引き続きあなたのアイデンティティ経由で送信されます - 表示される差出人ヘッダーのみが変更されます。",
"name_label": "差出人名",
"name_placeholder": "名前",
"email_label": "差出人メールアドレス",
@@ -2844,6 +2846,8 @@
"restart_title": "紹介ツアー",
"restart_desc": "インターフェースのガイドツアーを再生する",
"restart_button": "ツアーを再開",
"show_on_new_devices_title": "新しいデバイスで表示",
"show_on_new_devices_desc": "他のデバイスで完了済みでも、新しいデバイスで初めてサインインしたときにウェルカムバナーとツアーを再表示します",
"sidebar_title": "メールボックス",
"sidebar_desc": "フォルダーサイドバーです。メールボックスをクリックしてメールを表示できます。フォルダーの作成、メールのドラッグ移動、未読数の確認ができます。",
"compose_title": "メールを作成",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "메일 쓰기",
"compose_hint": "새 메시지 작성",
"no_subject": "(제목 없음)",
"no_body_content": "(본문 내용 없음)",
"no_preview_available": "미리 보기를 사용할 수 없습니다",
"loading_email": "메일을 불러오는 중...",
"loading": "불러오는 중...",
"reply": "답장",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "재정의",
"toggle_on": "재정의 취소",
"toggle_tooltip": "보낸 사람 이름과 주소를 자유롭게 편집하세요. 메일은 여전히 사용자의 ID를 통해 전송되며 표시되는 보낸 사람 헤더만 변경됩니다.",
"toggle_tooltip": "보낸 사람 이름과 주소를 자유롭게 편집하세요. 메일은 여전히 사용자의 ID를 통해 전송되며 - 표시되는 보낸 사람 헤더만 변경됩니다.",
"name_label": "보낸 사람 이름",
"name_placeholder": "이름",
"email_label": "보낸 사람 이메일 주소",
@@ -2844,6 +2846,8 @@
"restart_title": "소개 투어",
"restart_desc": "인터페이스를 설명해 주는 투어를 다시 시작해요",
"restart_button": "투어 다시 시작",
"show_on_new_devices_title": "새 기기에서 표시",
"show_on_new_devices_desc": "다른 곳에서 이미 완료했더라도 새 기기에 처음 로그인할 때 환영 배너와 투어를 다시 표시해요",
"sidebar_title": "편지함",
"sidebar_desc": "여기는 폴더 사이드바예요. 폴더를 클릭하면 그 안의 메일을 볼 수 있어요. 폴더를 만들거나, 메일을 드래그해서 옮길 수 있고 안 읽은 메일 개수도 한눈에 확인돼요.",
"compose_title": "메일 쓰기",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Rakstīt",
"compose_hint": "Rakstīt jaunu ziņojumu",
"no_subject": "(nav temata)",
"no_body_content": "(nav satura)",
"no_preview_available": "Priekšskatījums nav pieejams",
"loading_email": "Ielādē vēstuli...",
"loading": "Ielādē...",
"reply": "Atbildēt",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Pārrakstīt",
"toggle_on": "Atcelt pārrakstīšanu",
"toggle_tooltip": "Brīvi rediģējiet sūtītāja vārdu un adresi. Pasts joprojām tiek sūtīts caur jūsu identitāti mainās tikai redzamais No galvenes ieraksts.",
"toggle_tooltip": "Brīvi rediģējiet sūtītāja vārdu un adresi. Pasts joprojām tiek sūtīts caur jūsu identitāti - mainās tikai redzamais No galvenes ieraksts.",
"name_label": "Sūtītāja vārds",
"name_placeholder": "Vārds",
"email_label": "Sūtītāja e-pasta adrese",
@@ -2844,6 +2846,8 @@
"restart_title": "Iepazīšanās ekskursija",
"restart_desc": "Atkārtot soli pa solim pamācību par saskarni",
"restart_button": "Restartēt ekskursiju",
"show_on_new_devices_title": "Rādīt jaunās ierīcēs",
"show_on_new_devices_desc": "Atkārtot sveiciena reklāmkarogu un ekskursiju, pirmoreiz pierakstoties jaunā ierīcē, pat ja esat tos jau pabeidzis citur",
"sidebar_title": "Jūsu pastkastes",
"sidebar_desc": "Šī ir sānu josla ar mapēm. Noklikšķiniet uz jebkuras pastkastes, lai skatītu vēstules. Varat izveidot mapes un pārvietot vēstules.",
"compose_title": "Rakstīt vēstuli",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Opstellen",
"compose_hint": "Nieuw bericht opstellen",
"no_subject": "(Geen onderwerp)",
"no_body_content": "(Geen inhoud beschikbaar)",
"no_preview_available": "Geen voorbeeld beschikbaar",
"loading_email": "E-mail laden...",
"loading": "Laden...",
"reply": "Beantwoorden",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Overschrijven",
"toggle_on": "Overschrijven annuleren",
"toggle_tooltip": "Bewerk de naam en het adres van de afzender vrij. E-mail wordt nog steeds via je identiteit verzonden alleen de zichtbare Van-koptekst verandert.",
"toggle_tooltip": "Bewerk de naam en het adres van de afzender vrij. E-mail wordt nog steeds via je identiteit verzonden - alleen de zichtbare Van-koptekst verandert.",
"name_label": "Afzendernaam",
"name_placeholder": "Naam",
"email_label": "E-mailadres afzender",
@@ -2844,6 +2846,8 @@
"restart_title": "Introductietour",
"restart_desc": "Bekijk de rondleiding door de interface opnieuw",
"restart_button": "Tour herstarten",
"show_on_new_devices_title": "Tonen op nieuwe apparaten",
"show_on_new_devices_desc": "Herhaal de welkomstbanner en de rondleiding wanneer je voor het eerst inlogt op een nieuw apparaat, zelfs als je ze elders al hebt voltooid",
"sidebar_title": "Uw mailboxen",
"sidebar_desc": "Dit is uw mappenbalk. Klik op een mailbox om de e-mails te bekijken. U kunt mappen maken, e-mails tussen mappen slepen en ongelezen aantallen zien.",
"compose_title": "E-mail schrijven",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Napisz",
"compose_hint": "Napisz nową wiadomość",
"no_subject": "(Bez tematu)",
"no_body_content": "(Brak treści)",
"no_preview_available": "Podgląd niedostępny",
"loading_email": "Ładowanie wiadomości...",
"loading": "Ładowanie...",
"reply": "Odpowiedz",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Zastąp",
"toggle_on": "Anuluj zastąpienie",
"toggle_tooltip": "Swobodnie edytuj nazwę i adres nadawcy. Poczta jest nadal wysyłana przez twoją tożsamość zmienia się tylko widoczny nagłówek Od.",
"toggle_tooltip": "Swobodnie edytuj nazwę i adres nadawcy. Poczta jest nadal wysyłana przez twoją tożsamość - zmienia się tylko widoczny nagłówek Od.",
"name_label": "Nazwa nadawcy",
"name_placeholder": "Nazwa",
"email_label": "Adres e-mail nadawcy",
@@ -2844,6 +2846,8 @@
"restart_title": "Przewodnik wprowadzający",
"restart_desc": "Odtwórz przewodnik po interfejsie krok po kroku",
"restart_button": "Uruchom przewodnik ponownie",
"show_on_new_devices_title": "Pokaż na nowych urządzeniach",
"show_on_new_devices_desc": "Wyświetl ponownie baner powitalny i przewodnik przy pierwszym logowaniu na nowym urządzeniu, nawet jeśli zostały już ukończone w innym miejscu",
"sidebar_title": "Twoje skrzynki pocztowe",
"sidebar_desc": "To jest pasek boczny z folderami. Kliknij dowolną skrzynkę, aby zobaczyć jej wiadomości. Możesz tworzyć foldery, przeciągać między nimi wiadomości i od razu widzieć liczbę nieprzeczytanych.",
"compose_title": "Napisz wiadomość",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Redigir",
"compose_hint": "Redigir nova mensagem",
"no_subject": "(Sem Assunto)",
"no_body_content": "(Sem conteúdo disponível)",
"no_preview_available": "Pré-visualização não disponível",
"loading_email": "Carregando e-mail...",
"loading": "Carregando...",
"reply": "Responder",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Substituir",
"toggle_on": "Cancelar substituição",
"toggle_tooltip": "Edite livremente o nome e o endereço do remetente. O email ainda é enviado através da sua identidade apenas o cabeçalho De visível muda.",
"toggle_tooltip": "Edite livremente o nome e o endereço do remetente. O email ainda é enviado através da sua identidade - apenas o cabeçalho De visível muda.",
"name_label": "Nome do remetente",
"name_placeholder": "Nome",
"email_label": "Endereço de email do remetente",
@@ -2844,6 +2846,8 @@
"restart_title": "Tour introdutório",
"restart_desc": "Rever o tour guiado da interface",
"restart_button": "Reiniciar tour",
"show_on_new_devices_title": "Mostrar em novos dispositivos",
"show_on_new_devices_desc": "Reproduzir o banner de boas-vindas e o tour no primeiro login num novo dispositivo, mesmo que já os tenhas concluído noutro lado",
"sidebar_title": "Suas caixas de correio",
"sidebar_desc": "Esta é a barra lateral de pastas. Clique em qualquer caixa para ver seus e-mails. Você pode criar pastas, arrastar e-mails entre elas e ver contadores de não lidos.",
"compose_title": "Escrever um e-mail",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Написать",
"compose_hint": "Написать новое сообщение",
"no_subject": "(Без темы)",
"no_body_content": "(Содержимое отсутствует)",
"no_preview_available": "Предварительный просмотр недоступен",
"loading_email": "Загрузка письма...",
"loading": "Загрузка...",
"reply": "Ответить",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Переопределить",
"toggle_on": "Отменить переопределение",
"toggle_tooltip": "Свободно редактируйте имя и адрес отправителя. Письмо по-прежнему отправляется через вашу учётную запись меняется только видимый заголовок От.",
"toggle_tooltip": "Свободно редактируйте имя и адрес отправителя. Письмо по-прежнему отправляется через вашу учётную запись - меняется только видимый заголовок От.",
"name_label": "Имя отправителя",
"name_placeholder": "Имя",
"email_label": "Email отправителя",
@@ -2844,6 +2846,8 @@
"restart_title": "Ознакомительный тур",
"restart_desc": "Повторить пошаговое руководство по интерфейсу",
"restart_button": "Перезапустить тур",
"show_on_new_devices_title": "Показывать на новых устройствах",
"show_on_new_devices_desc": "Повторить приветственный баннер и тур при первом входе на новом устройстве, даже если вы уже завершили их в другом месте",
"sidebar_title": "Ваши почтовые ящики",
"sidebar_desc": "Это боковая панель с папками. Нажмите на любой почтовый ящик для просмотра писем. Вы можете создавать папки, перетаскивать письма между ними и видеть количество непрочитанных.",
"compose_title": "Написать письмо",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Yeni E-posta",
"compose_hint": "Yeni e-posta oluştur",
"no_subject": "(Konu Yok)",
"no_body_content": "(İçerik yok)",
"no_preview_available": "Önizleme kullanılamıyor",
"loading_email": "E-posta yükleniyor...",
"loading": "Yükleniyor...",
"reply": "Yanıtla",
@@ -568,7 +570,7 @@
"from_override": {
"toggle_off": "Geçersiz kıl",
"toggle_on": "Geçersiz kılmayı iptal et",
"toggle_tooltip": "Gönderen adını ve adresini serbestçe düzenleyin. Posta hâlâ kimliğiniz üzerinden gönderilir yalnızca görünür Kimden başlığı değişir.",
"toggle_tooltip": "Gönderen adını ve adresini serbestçe düzenleyin. Posta hâlâ kimliğiniz üzerinden gönderilir - yalnızca görünür Kimden başlığı değişir.",
"name_label": "Gönderen adı",
"name_placeholder": "Ad",
"email_label": "Gönderen e-posta adresi",
@@ -2867,6 +2869,8 @@
"restart_title": "Tanıtım turu",
"restart_desc": "Arayüzün rehberli gezintisini tekrar oynat",
"restart_button": "Turu yeniden başlat",
"show_on_new_devices_title": "Yeni cihazlarda göster",
"show_on_new_devices_desc": "Başka bir yerde tamamlamış olsanız bile, yeni bir cihazda ilk oturum açtığınızda karşılama afişini ve turu yeniden gösterin",
"sidebar_title": "Posta kutularınız",
"sidebar_desc": "Bu sizin klasör kenar çubuğunuzdur. E-postalarını görüntülemek için herhangi bir posta kutusuna tıklayın. Klasörler oluşturabilir, e-postaları aralarında sürükleyebilir ve okunmamış sayılarını bir bakışta görebilirsiniz.",
"compose_title": "E-posta oluştur",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "Скласти",
"compose_hint": "Написати нове повідомлення",
"no_subject": "(без теми)",
"no_body_content": "(вміст відсутній)",
"no_preview_available": "Попередній перегляд недоступний",
"loading_email": "Завантаження електронної пошти...",
"loading": "Завантаження...",
"reply": "Відповісти",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "Замінити",
"toggle_on": "Скасувати заміну",
"toggle_tooltip": "Вільно редагуйте ім'я та адресу відправника. Пошта все ще надсилається через вашу ідентичність змінюється лише видимий заголовок Від.",
"toggle_tooltip": "Вільно редагуйте ім'я та адресу відправника. Пошта все ще надсилається через вашу ідентичність - змінюється лише видимий заголовок Від.",
"name_label": "Ім'я відправника",
"name_placeholder": "Ім'я",
"email_label": "Електронна адреса відправника",
@@ -2844,6 +2846,8 @@
"restart_title": "Ознайомчий тур",
"restart_desc": "Повторіть покрокове керівництво по інтерфейсу",
"restart_button": "Перезапустити тур",
"show_on_new_devices_title": "Показувати на нових пристроях",
"show_on_new_devices_desc": "Повторіть привітальний банер і тур під час першого входу на новому пристрої, навіть якщо ви вже завершили їх в іншому місці",
"sidebar_title": "Ваші поштові скриньки",
"sidebar_desc": "Це бічна панель вашої папки. Натисніть будь-яку поштову скриньку, щоб переглянути її електронні листи. Ви можете створювати папки, перетягувати електронні листи між ними та миттєво переглядати кількість непрочитаних.",
"compose_title": "Створіть електронний лист",
+5 -1
View File
@@ -249,6 +249,8 @@
"compose": "撰写邮件",
"compose_hint": "撰写新邮件",
"no_subject": "(无主题)",
"no_body_content": "(无正文内容)",
"no_preview_available": "无可用预览",
"loading_email": "正在加载邮件...",
"loading": "正在加载…",
"reply": "回复",
@@ -565,7 +567,7 @@
"from_override": {
"toggle_off": "覆盖",
"toggle_on": "取消覆盖",
"toggle_tooltip": "自由编辑发件人姓名和地址。邮件仍通过您的身份发送 仅可见的发件人标题发生变化。",
"toggle_tooltip": "自由编辑发件人姓名和地址。邮件仍通过您的身份发送 - 仅可见的发件人标题发生变化。",
"name_label": "发件人姓名",
"name_placeholder": "姓名",
"email_label": "发件人电子邮件地址",
@@ -2844,6 +2846,8 @@
"restart_title": "新手导览",
"restart_desc": "重新查看界面功能引导",
"restart_button": "重新开始导览",
"show_on_new_devices_title": "在新设备上显示",
"show_on_new_devices_desc": "首次在新设备登录时重新显示欢迎横幅和导览,即使您已在其他设备完成",
"sidebar_title": "邮箱文件夹",
"sidebar_desc": "这里是邮箱文件夹列表。点击任意文件夹即可查看邮件。你可以创建文件夹、拖动邮件进行整理,并快速查看未读邮件数量。",
"compose_title": "写邮件",
+6
View File
@@ -46,6 +46,12 @@ const nextConfig: NextConfig = {
// it from node_modules at runtime instead of trying to bundle it. Used by
// PLUGIN_DEV_DIR's on-the-fly bundler.
serverExternalPackages: ["esbuild"],
// Sibling repos checked out under ./repos/ are unrelated source trees that
// Turbopack's NFT can otherwise rope into the trace when dynamic fs calls
// confuse it. Keeps the build from ballooning memory tracing dead code.
outputFileTracingExcludes: {
"*": ["./repos/**/*"],
},
turbopack: {
root: import.meta.dirname,
},
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "bulwark-webmail",
"version": "1.6.5",
"version": "1.6.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bulwark-webmail",
"version": "1.6.5",
"version": "1.6.7",
"license": "AGPL-3.0-only",
"dependencies": {
"@tanstack/react-virtual": "^3.13.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bulwark-webmail",
"version": "1.6.5",
"version": "1.6.7",
"description": "Bulwark Webmail - a modern webmail client built for Stalwart Mail Server",
"author": "Bulwark Webmail <bulwark@rbm.systems>",
"license": "AGPL-3.0-only",
+1 -1
View File
@@ -37,7 +37,7 @@ export async function proxy(request: NextRequest) {
pathname === "/api/health" ||
pathname.startsWith("/_next/") ||
pathname.startsWith("/branding/") ||
// Public read endpoint serves wizard-uploaded branding assets so
// Public read endpoint - serves wizard-uploaded branding assets so
// image previews work during the wizard. No auth on the GET route.
pathname.startsWith("/api/admin/branding/") ||
/\.[^/]+$/.test(pathname);
+14 -1
View File
@@ -98,6 +98,16 @@ async function handlePush(event) {
? payload.accountLabel
: "";
// JMAP StateChange wraps changes in { changed: { [accountId]: {...} } }.
// The relay forwards a single account's StateChange per push, so the first
// key is the one this notification is for. Without this the preview API
// would just fall back to the first signed-in slot and surface mail from
// the wrong account.
const changed = payload && payload.changed && typeof payload.changed === "object"
? payload.changed
: null;
const accountId = changed ? Object.keys(changed)[0] || "" : "";
// Best effort: ask the webmail to look up the latest unread email so we can
// build a useful notification. If the request fails (offline, session
// expired, server down) we fall back to a generic "New mail" so the user
@@ -105,7 +115,10 @@ async function handlePush(event) {
let preview = null;
let previewOk = false;
try {
const res = await fetch(`${BASE_PATH}/api/push/preview`, {
const previewUrl = accountId
? `${BASE_PATH}/api/push/preview?accountId=${encodeURIComponent(accountId)}`
: `${BASE_PATH}/api/push/preview`;
const res = await fetch(previewUrl, {
credentials: "include",
cache: "no-store",
});

Some files were not shown because too many files have changed in this diff Show More