From ba4a4202090322fe8f84a8fbcc785129575748af Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 02:45:42 +0000 Subject: [PATCH 1/6] feat: calendar view with CalDAV support for self-hosted Exchange MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a full week-view calendar that reads events from Exchange via CalDAV (the same IMAP host/credentials are reused — no extra config needed). Backend (main process): - CalDavProvider: HTTP PROPFIND/REPORT against standard CalDAV and Exchange-specific /EWS/Calendar/ endpoints with Basic auth; inline iCal parser handles VEVENT fields, UTC/local/all-day dates, attendees - CalendarHandler: IPC channels calendar:list and calendar:events - AccountManager: calendarProviders map with lazy connect/cache Renderer: - CalendarStore (Pinia): week navigation, per-calendar toggling, event loading - CalendarView: full-screen layout matching liquid-glass design system - WeekView: 7-column time grid, overlap layout, current-time indicator, scrolls to business hours on mount, all-day event row - EventBlock: positioned absolute event card with status variants - EventDetailPopup: full event details (time, location, organizer, attendees) - Router: /calendar route added - AccountSwitcher: mail / calendar nav icons with active-state highlight - AppIcon: added 'calendar' SVG icon Co-Authored-By: Claude Sonnet 4.6 --- src/main/index.ts | 2 + src/main/ipc/calendar.handler.ts | 12 + src/main/providers/caldav.provider.ts | 530 ++++++++++++++++++ src/main/services/account-manager.ts | 46 ++ src/renderer/src/components/AppIcon.vue | 7 + .../src/components/calendar/EventBlock.vue | 92 +++ .../components/calendar/EventDetailPopup.vue | 200 +++++++ .../src/components/calendar/WeekView.vue | 520 +++++++++++++++++ .../components/sidebar/AccountSwitcher.vue | 36 +- src/renderer/src/main.ts | 5 + src/renderer/src/stores/calendar.store.ts | 135 +++++ src/renderer/src/views/CalendarView.vue | 496 ++++++++++++++++ src/shared/types/calendar.ts | 22 + src/shared/types/ipc.ts | 7 + 14 files changed, 2107 insertions(+), 3 deletions(-) create mode 100644 src/main/ipc/calendar.handler.ts create mode 100644 src/main/providers/caldav.provider.ts create mode 100644 src/renderer/src/components/calendar/EventBlock.vue create mode 100644 src/renderer/src/components/calendar/EventDetailPopup.vue create mode 100644 src/renderer/src/components/calendar/WeekView.vue create mode 100644 src/renderer/src/stores/calendar.store.ts create mode 100644 src/renderer/src/views/CalendarView.vue create mode 100644 src/shared/types/calendar.ts diff --git a/src/main/index.ts b/src/main/index.ts index efe5621..719ff95 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -5,6 +5,7 @@ import { AccountManager } from './services/account-manager' import { registerAccountHandlers } from './ipc/accounts.handler' import { registerFolderHandlers } from './ipc/folders.handler' import { registerMessageHandlers } from './ipc/messages.handler' +import { registerCalendarHandlers } from './ipc/calendar.handler' import type { ComposeSession } from '@shared/types/message' const accountManager = new AccountManager() @@ -142,6 +143,7 @@ app.whenReady().then(async () => { registerAccountHandlers(accountManager) registerFolderHandlers(accountManager) registerMessageHandlers(accountManager) + registerCalendarHandlers(accountManager) createWindow() diff --git a/src/main/ipc/calendar.handler.ts b/src/main/ipc/calendar.handler.ts new file mode 100644 index 0000000..aa6a2b2 --- /dev/null +++ b/src/main/ipc/calendar.handler.ts @@ -0,0 +1,12 @@ +import type { AccountManager } from '../services/account-manager' +import { registerHandler } from './registry' + +export function registerCalendarHandlers(manager: AccountManager): void { + registerHandler('calendar:list', ({ accountId }) => + manager.listCalendars(accountId) + ) + + registerHandler('calendar:events', ({ accountId, calendarId, start, end }) => + manager.listCalendarEvents(accountId, calendarId, new Date(start), new Date(end)) + ) +} diff --git a/src/main/providers/caldav.provider.ts b/src/main/providers/caldav.provider.ts new file mode 100644 index 0000000..3394c4d --- /dev/null +++ b/src/main/providers/caldav.provider.ts @@ -0,0 +1,530 @@ +/** + * CalDAV provider for Exchange (and any CalDAV-compliant server). + * + * Uses only Node.js built-in `https`/`http` — no extra npm deps. + * Exchange 2013+ exposes CalDAV at /EWS/Calendar/; standard servers + * advertise the principal via /.well-known/caldav (RFC 6764). + * + * Auth: HTTP Basic, same credentials as IMAP. + */ + +import https from 'node:https' +import http from 'node:http' +import type { IncomingMessage } from 'node:http' +import type { AccountConfig, ImapCredentials } from '@shared/types/account' +import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar' + +// ── HTTP helper ──────────────────────────────────────────────────────────────── + +interface RequestOptions { + protocol: 'https' | 'http' + hostname: string + port: number + path: string + method: string + headers: Record + body?: string + allowSelfSigned?: boolean +} + +interface RequestResult { + status: number + headers: IncomingMessage['headers'] + body: string +} + +function request(opts: RequestOptions): Promise { + return new Promise((resolve, reject) => { + const module_ = opts.protocol === 'https' ? https : http + const req = module_.request( + { + hostname: opts.hostname, + port: opts.port, + path: opts.path, + method: opts.method, + headers: opts.headers, + rejectUnauthorized: !opts.allowSelfSigned, + timeout: 15_000 + }, + (res) => { + let data = '' + res.setEncoding('utf8') + res.on('data', (chunk) => { data += chunk }) + res.on('end', () => { + resolve({ status: res.statusCode ?? 0, headers: res.headers, body: data }) + }) + } + ) + req.on('timeout', () => { req.destroy(new Error('CalDAV request timed out')) }) + req.on('error', reject) + if (opts.body) req.write(opts.body) + req.end() + }) +} + +// ── Minimal iCal parser ──────────────────────────────────────────────────────── + +interface RawVEvent { + uid: string + summary: string + dtstart: string + dtStartParams: string + dtend: string + dtEndParams: string + location: string + description: string + organizer: string + attendees: string[] + status: string +} + +/** RFC 5545 line-unfolding: CRLF followed by a space or tab is a continuation. */ +function unfoldLines(raw: string): string[] { + return raw.replace(/\r\n[ \t]/g, '').replace(/\n[ \t]/g, '').split(/\r\n|\n/) +} + +function decodeICalText(value: string): string { + return value.replace(/\\n/g, '\n').replace(/\\,/g, ',').replace(/\\;/g, ';').replace(/\\\\/g, '\\') +} + +function extractEmail(value: string): string { + // ORGANIZER:mailto:user@example.com or ATTENDEE;CN=Name:mailto:user@example.com + const match = value.match(/mailto:([^\s;,>]+)/i) + return match ? match[1] : value +} + +function parseVEvents(icalText: string): RawVEvent[] { + const events: RawVEvent[] = [] + const lines = unfoldLines(icalText) + + let inEvent = false + let props: Record> = {} + + for (const line of lines) { + if (line === 'BEGIN:VEVENT') { + inEvent = true + props = {} + continue + } + if (line === 'END:VEVENT') { + inEvent = false + + const get = (key: string) => props[key]?.[0]?.value ?? '' + const getParams = (key: string) => props[key]?.[0]?.params ?? '' + const getAll = (key: string) => (props[key] ?? []).map((x) => x.value) + + events.push({ + uid: get('UID'), + summary: decodeICalText(get('SUMMARY')), + dtstart: get('DTSTART'), + dtStartParams: getParams('DTSTART'), + dtend: get('DTEND'), + dtEndParams: getParams('DTEND'), + location: decodeICalText(get('LOCATION')), + description: decodeICalText(get('DESCRIPTION')), + organizer: extractEmail(get('ORGANIZER')), + attendees: getAll('ATTENDEE').map(extractEmail).filter(Boolean), + status: get('STATUS').toLowerCase() + }) + continue + } + + if (!inEvent) continue + + const colonIdx = line.indexOf(':') + if (colonIdx === -1) continue + + const keyFull = line.substring(0, colonIdx) + const value = line.substring(colonIdx + 1) + const semicolonIdx = keyFull.indexOf(';') + const key = semicolonIdx === -1 ? keyFull : keyFull.substring(0, semicolonIdx) + const params = semicolonIdx === -1 ? '' : keyFull.substring(semicolonIdx + 1) + + if (!props[key]) props[key] = [] + props[key].push({ value, params }) + } + + return events +} + +/** + * Parse iCal date/time string to a JS Date. + * Handles: DATE (20240401), DATE-TIME UTC (20240401T090000Z), + * DATE-TIME local (20240401T090000), with TZID param ignored (treated as local). + */ +function parseICalDate(value: string, params: string): { date: Date; isAllDay: boolean } { + const isAllDay = params.includes('VALUE=DATE') || /^\d{8}$/.test(value) + + if (isAllDay) { + const y = parseInt(value.slice(0, 4), 10) + const m = parseInt(value.slice(4, 6), 10) - 1 + const d = parseInt(value.slice(6, 8), 10) + return { date: new Date(Date.UTC(y, m, d)), isAllDay: true } + } + + const isUTC = value.endsWith('Z') + const clean = isUTC ? value.slice(0, -1) : value + + const y = parseInt(clean.slice(0, 4), 10) + const mo = parseInt(clean.slice(4, 6), 10) - 1 + const d = parseInt(clean.slice(6, 8), 10) + const h = clean.length > 8 ? parseInt(clean.slice(9, 11), 10) : 0 + const mi = clean.length > 8 ? parseInt(clean.slice(11, 13), 10) : 0 + const s = clean.length > 8 ? parseInt(clean.slice(13, 15), 10) : 0 + + const date = isUTC + ? new Date(Date.UTC(y, mo, d, h, mi, s)) + : new Date(y, mo, d, h, mi, s) + + return { date, isAllDay: false } +} + +// ── XML helpers ──────────────────────────────────────────────────────────────── + +/** Extract all (or namespaced equivalent) block contents from a multistatus XML response. */ +function extractCalendarData(xml: string): string[] { + const results: string[] = [] + // Match both namespaced and un-namespaced calendar-data elements + const re = /<(?:[^:\s>]+:)?calendar-data[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?calendar-data>/g + let match: RegExpExecArray | null + while ((match = re.exec(xml)) !== null) { + // CalDAV may XML-encode special chars inside calendar-data + const raw = match[1] + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&') + .replace(/ /g, '\r') + .trim() + if (raw.length > 0) results.push(raw) + } + return results +} + +/** Extract calendar collections from a PROPFIND multistatus response. */ +interface CalDavCalendar { + href: string + displayName: string +} + +function extractCalendars(xml: string, baseUrl: string): CalDavCalendar[] { + const calendars: CalDavCalendar[] = [] + + // Split by blocks + const responseRe = /<(?:[^:\s>]+:)?response[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?response>/g + let match: RegExpExecArray | null + + while ((match = responseRe.exec(xml)) !== null) { + const block = match[1] + + // Must contain calendar resourcetype + if (!/<(?:[^:\s>]+:)?calendar[^>]*\/>/.test(block) && + !/<(?:[^:\s>]+:)?calendar[^>]*>/.test(block)) continue + + const hrefMatch = block.match(/<(?:[^:\s>]+:)?href[^>]*>([^<]+)<\/(?:[^:\s>]+:)?href>/) + const nameMatch = block.match(/<(?:[^:\s>]+:)?displayname[^>]*>([^<]*)<\/(?:[^:\s>]+:)?displayname>/) + + if (hrefMatch) { + calendars.push({ + href: hrefMatch[1].trim(), + displayName: nameMatch ? decodeICalText(nameMatch[1].trim()) : 'Calendar' + }) + } + } + + // If nothing found, treat the base path itself as the calendar + if (calendars.length === 0 && baseUrl.length > 0) { + calendars.push({ href: baseUrl, displayName: 'Calendar' }) + } + + return calendars +} + +// ── CalDAV Provider ──────────────────────────────────────────────────────────── + +export class CalDavProvider { + private readonly hostname: string + private readonly protocol: 'https' | 'http' + private readonly port: number + private readonly username: string + private readonly password: string + private readonly allowSelfSigned: boolean + private readonly authHeader: string + + /** Resolved CalDAV base path (e.g. "/EWS/Calendar/") */ + private basePath: string | null = null + + constructor(config: AccountConfig) { + const creds = config.credentials as ImapCredentials + + // Derive HTTPS endpoint from IMAP host; Exchange typically shares the hostname + this.hostname = creds.host + this.protocol = creds.secure ? 'https' : 'http' + this.port = creds.secure ? 443 : 80 + this.username = creds.username + this.password = creds.password + this.allowSelfSigned = creds.smtpAllowSelfSigned ?? false + + const encoded = Buffer.from(`${this.username}:${this.password}`).toString('base64') + this.authHeader = `Basic ${encoded}` + } + + // ── Discovery ────────────────────────────────────────────────────────────── + + /** + * Try to discover the CalDAV endpoint. + * Priority: /.well-known/caldav (RFC 6764) → /EWS/Calendar/ (Exchange) → /caldav/ (generic) + * Returns the resolved path or null if none found. + */ + async discoverBasePath(): Promise { + const candidates = [ + '/.well-known/caldav', + '/EWS/Calendar/', + `/EWS/Calendar/${this.username}/`, + '/caldav/', + `/caldav/${this.username}/`, + '/dav/', + ] + + for (const path of candidates) { + try { + const result = await this.req('PROPFIND', path, { + Depth: '0', + 'Content-Type': 'application/xml; charset=utf-8', + }) + + // 207 Multi-Status = CalDAV responded, 301/302 = redirect → follow + if (result.status === 207) return path + if (result.status === 301 || result.status === 302) { + const location = result.headers['location'] + if (location) { + const u = new URL(location, `${this.protocol}://${this.hostname}`) + return u.pathname + } + } + } catch { + // Try next candidate + } + } + + return null + } + + async connect(): Promise { + this.basePath = await this.discoverBasePath() + if (!this.basePath) { + throw new Error( + `CalDAV endpoint not found on ${this.hostname}. ` + + `Ensure Exchange CalDAV is enabled (Exchange 2013+).` + ) + } + } + + isConnected(): boolean { + return this.basePath !== null + } + + // ── List calendars ───────────────────────────────────────────────────────── + + async listCalendars(accountId: string): Promise { + if (!this.basePath) throw new Error('CalDAV not connected') + + const body = ` + + + + + +` + + const result = await this.req('PROPFIND', this.basePath, { + Depth: '1', + 'Content-Type': 'application/xml; charset=utf-8', + }, body) + + if (result.status !== 207) { + // Treat the base path as a single calendar on any other 2xx + return [{ + id: this.basePath, + name: 'Calendar', + accountId + }] + } + + const cals = extractCalendars(result.body, this.basePath) + return cals.map((c) => ({ + id: c.href, + name: c.displayName || 'Calendar', + accountId + })) + } + + // ── Fetch events ─────────────────────────────────────────────────────────── + + async listEvents( + accountId: string, + calendarId: string, + start: Date, + end: Date + ): Promise { + const startStr = toUtcString(start) + const endStr = toUtcString(end) + + const body = ` + + + + + + + + + + + + +` + + const result = await this.req('REPORT', calendarId, { + Depth: '1', + 'Content-Type': 'application/xml; charset=utf-8', + }, body) + + if (result.status !== 207) { + // Exchange may not support time-range; fall back to PROPFIND + client-side filtering + return this.fetchAllEventsAndFilter(accountId, calendarId, start, end) + } + + return this.parseMultistatusEvents(result.body, accountId, calendarId) + } + + /** Fallback: fetch all VEVENT objects and filter client-side by time range. */ + private async fetchAllEventsAndFilter( + accountId: string, + calendarId: string, + start: Date, + end: Date + ): Promise { + const body = ` + + + + + + + + + + +` + + const result = await this.req('REPORT', calendarId, { + Depth: '1', + 'Content-Type': 'application/xml; charset=utf-8', + }, body) + + if (result.status !== 207) return [] + + const all = this.parseMultistatusEvents(result.body, accountId, calendarId) + return all.filter((ev) => { + const evEnd = new Date(ev.end) + const evStart = new Date(ev.start) + return evStart < end && evEnd > start + }) + } + + // ── Parsing ──────────────────────────────────────────────────────────────── + + private parseMultistatusEvents( + xml: string, + accountId: string, + calendarId: string + ): CalendarEvent[] { + const events: CalendarEvent[] = [] + const icalBlocks = extractCalendarData(xml) + + for (const block of icalBlocks) { + const raw = parseVEvents(block) + for (const rv of raw) { + if (!rv.dtstart) continue + + const { date: startDate, isAllDay } = parseICalDate(rv.dtstart, rv.dtStartParams) + let endDate: Date + + if (rv.dtend) { + endDate = parseICalDate(rv.dtend, rv.dtEndParams).date + } else { + // No DTEND: for all-day events default to +1 day, for timed +1 hour + endDate = new Date(startDate) + if (isAllDay) endDate.setUTCDate(endDate.getUTCDate() + 1) + else endDate.setTime(endDate.getTime() + 60 * 60 * 1000) + } + + const id = `${calendarId}::${rv.uid || startDate.toISOString()}` + + events.push({ + id, + uid: rv.uid, + calendarId, + accountId, + title: rv.summary || '(no title)', + start: startDate.toISOString(), + end: endDate.toISOString(), + isAllDay, + location: rv.location || undefined, + description: rv.description || undefined, + organizer: rv.organizer || undefined, + attendees: rv.attendees, + status: (rv.status as CalendarEvent['status']) || 'confirmed' + }) + } + } + + return events + } + + // ── Internal HTTP helper ─────────────────────────────────────────────────── + + private async req( + method: string, + path: string, + extraHeaders: Record = {}, + body?: string + ): Promise { + const headers: Record = { + Authorization: this.authHeader, + 'User-Agent': 'AeroMail/1.0', + ...extraHeaders + } + if (body) { + headers['Content-Length'] = Buffer.byteLength(body, 'utf8').toString() + } + + return request({ + protocol: this.protocol, + hostname: this.hostname, + port: this.port, + path, + method, + headers, + body, + allowSelfSigned: this.allowSelfSigned + }) + } +} + +// ── Utility ──────────────────────────────────────────────────────────────────── + +/** Format a Date as an iCal UTC string: 20240401T000000Z */ +function toUtcString(d: Date): string { + const pad = (n: number) => String(n).padStart(2, '0') + return ( + d.getUTCFullYear().toString() + + pad(d.getUTCMonth() + 1) + + pad(d.getUTCDate()) + + 'T' + + pad(d.getUTCHours()) + + pad(d.getUTCMinutes()) + + pad(d.getUTCSeconds()) + + 'Z' + ) +} diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index 912466b..b86d602 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -3,7 +3,9 @@ import type { AccountConfig, ImapCredentials } from '@shared/types/account' import { AccountType } from '@shared/types/account' import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData } from '@shared/types/message' +import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar' import { ImapProvider } from '../providers/imap.provider' +import { CalDavProvider } from '../providers/caldav.provider' import { CredentialStore } from './credential-store' import Store from 'electron-store' @@ -16,6 +18,7 @@ const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', ' export class AccountManager { private providers = new Map() + private calendarProviders = new Map() private store: Store private credentialStore: CredentialStore private mainWindow: BrowserWindow | null = null @@ -72,6 +75,7 @@ export class AccountManager { await provider.disconnect() this.providers.delete(accountId) } + this.calendarProviders.delete(accountId) await this.credentialStore.remove(accountId) const accounts = this.store.get('accounts', []) @@ -205,6 +209,48 @@ export class AccountManager { ) } + // ── Calendar ──────────────────────────────────────────── + + async listCalendars(accountId: string): Promise { + const provider = await this.getOrCreateCalendarProvider(accountId) + return provider.listCalendars(accountId) + } + + async listCalendarEvents( + accountId: string, + calendarId: string, + start: Date, + end: Date + ): Promise { + const provider = await this.getOrCreateCalendarProvider(accountId) + return provider.listEvents(accountId, calendarId, start, end) + } + + private async getOrCreateCalendarProvider(accountId: string): Promise { + const existing = this.calendarProviders.get(accountId) + if (existing?.isConnected()) return existing + + const accounts = this.store.get('accounts', []) + const accMeta = accounts.find((a) => a.id === accountId) + if (!accMeta) throw new Error(`Account ${accountId} not found`) + + const credRaw = this.credentialStore.get(accountId) + if (!credRaw) throw new Error(`Credentials for ${accountId} not found`) + + let credentials: AccountConfig['credentials'] + try { + credentials = JSON.parse(credRaw) + } catch { + throw new Error('Corrupted credentials') + } + + const config: AccountConfig = { ...accMeta, credentials } + const provider = new CalDavProvider(config) + await provider.connect() + this.calendarProviders.set(accountId, provider) + return provider + } + // ── Auto-reconnect ────────────────────────────────────── private async withAutoReconnect(accountId: string, fn: () => Promise): Promise { diff --git a/src/renderer/src/components/AppIcon.vue b/src/renderer/src/components/AppIcon.vue index 0a8b5d2..72881f6 100644 --- a/src/renderer/src/components/AppIcon.vue +++ b/src/renderer/src/components/AppIcon.vue @@ -24,6 +24,7 @@ export type IconName = | 'pdf' | 'image' | 'bell-off' + | 'calendar' const props = defineProps<{ name: IconName @@ -141,6 +142,12 @@ const paths: Record = { `, + calendar: ` + + + + + `, } diff --git a/src/renderer/src/components/calendar/EventBlock.vue b/src/renderer/src/components/calendar/EventBlock.vue new file mode 100644 index 0000000..47c2d76 --- /dev/null +++ b/src/renderer/src/components/calendar/EventBlock.vue @@ -0,0 +1,92 @@ + + + + + diff --git a/src/renderer/src/components/calendar/EventDetailPopup.vue b/src/renderer/src/components/calendar/EventDetailPopup.vue new file mode 100644 index 0000000..6476f72 --- /dev/null +++ b/src/renderer/src/components/calendar/EventDetailPopup.vue @@ -0,0 +1,200 @@ + + + + + diff --git a/src/renderer/src/components/calendar/WeekView.vue b/src/renderer/src/components/calendar/WeekView.vue new file mode 100644 index 0000000..9c56cff --- /dev/null +++ b/src/renderer/src/components/calendar/WeekView.vue @@ -0,0 +1,520 @@ + + + + + diff --git a/src/renderer/src/components/sidebar/AccountSwitcher.vue b/src/renderer/src/components/sidebar/AccountSwitcher.vue index 2953f0b..bb89327 100644 --- a/src/renderer/src/components/sidebar/AccountSwitcher.vue +++ b/src/renderer/src/components/sidebar/AccountSwitcher.vue @@ -1,6 +1,6 @@ + + + + diff --git a/src/shared/types/calendar.ts b/src/shared/types/calendar.ts new file mode 100644 index 0000000..9aafb35 --- /dev/null +++ b/src/shared/types/calendar.ts @@ -0,0 +1,22 @@ +export interface CalendarInfo { + id: string + name: string + color?: string + accountId: string +} + +export interface CalendarEvent { + id: string + uid: string + calendarId: string + accountId: string + title: string + start: string // ISO 8601 + end: string // ISO 8601 + isAllDay: boolean + location?: string + description?: string + organizer?: string + attendees: string[] + status?: 'tentative' | 'confirmed' | 'cancelled' +} diff --git a/src/shared/types/ipc.ts b/src/shared/types/ipc.ts index 3d78f26..3043b85 100644 --- a/src/shared/types/ipc.ts +++ b/src/shared/types/ipc.ts @@ -1,6 +1,7 @@ import type { AccountConfig } from './account' import type { FolderListResult, MessageListResult } from './provider' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, ComposeSession } from './message' +import type { CalendarInfo, CalendarEvent } from './calendar' export interface IpcChannelMap { 'accounts:list': [void, AccountConfig[]] @@ -47,6 +48,12 @@ export interface IpcChannelMap { 'app:setZoom': [{ factor: number }, void] 'app:isEncryptionAvailable': [void, boolean] + + 'calendar:list': [{ accountId: string }, CalendarInfo[]] + 'calendar:events': [ + { accountId: string; calendarId: string; start: string; end: string }, + CalendarEvent[] + ] } export interface IpcEventMap { From adbf8b8e49525604aadb1d88435d788696822a9f Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 03:03:48 +0000 Subject: [PATCH 2/6] fix: add NTLMv2 authentication for corporate Exchange CalDAV Exchange servers with Basic auth disabled return 401 WWW-Authenticate:NTLM/Negotiate. Added pure-JS NTLMv2 implementation (no new deps) and auto-detection in CalDavProvider. - src/main/lib/ntlm.ts: MD4 (avoids OpenSSL 3.x legacy issues), Type1/Type2/Type3 message builder for NTLMv2 (HMAC-MD5 + NTProofStr + blob with server challenge) - CalDavProvider.req(): tries Basic first; on 401+NTLM header auto-switches to NTLM mode - CalDavProvider.reqNtlm(): 3-way handshake on a dedicated keepAlive/maxSockets:1 agent to guarantee both Negotiate and Authenticate use the same TCP connection Co-Authored-By: Claude Sonnet 4.6 --- src/main/lib/ntlm.ts | 207 ++++++++++++ src/main/providers/caldav.provider.ts | 467 +++++++++++--------------- 2 files changed, 408 insertions(+), 266 deletions(-) create mode 100644 src/main/lib/ntlm.ts diff --git a/src/main/lib/ntlm.ts b/src/main/lib/ntlm.ts new file mode 100644 index 0000000..405dd3f --- /dev/null +++ b/src/main/lib/ntlm.ts @@ -0,0 +1,207 @@ +/** + * NTLM (NTLMv2) authentication for HTTP — MS-NLMP spec. + * Pure Node.js crypto, no external deps. + * + * Flow over HTTP: + * Client → Server: method + Authorization: NTLM + * Server → Client: 401 + WWW-Authenticate: NTLM + * Client → Server: method + Authorization: NTLM + actual body + * Server → Client: 207 / 200 + * + * All three round-trips MUST use the same TCP connection (keepAlive agent). + */ + +import crypto from 'node:crypto' + +// ── MD4 (pure JS) ───────────────────────────────────────────────────────────── +// Needed for NT hash: MD4(UTF-16LE(password)). +// Node.js 20+ / OpenSSL 3.x moved MD4 to the legacy provider, so we +// implement it ourselves to avoid any availability issues. + +function md4(buf: Buffer): Buffer { + const F = (x: number, y: number, z: number) => (x & y) | (~x & z) + const G = (x: number, y: number, z: number) => (x & y) | (x & z) | (y & z) + const H = (x: number, y: number, z: number) => x ^ y ^ z + const add = (a: number, b: number) => (a + b) >>> 0 + const rol = (x: number, n: number) => ((x << n) | (x >>> (32 - n))) >>> 0 + + const l = buf.length + const extra = ((56 - l - 1) % 64 + 64) % 64 + const padded = Buffer.alloc(l + 1 + extra + 8) + buf.copy(padded) + padded[l] = 0x80 + const bitLen = l * 8 + padded.writeUInt32LE(bitLen >>> 0, padded.length - 8) + padded.writeUInt32LE(Math.floor(bitLen / 2 ** 32), padded.length - 4) + + let a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476 + + for (let off = 0; off < padded.length; off += 64) { + const X = Array.from({ length: 16 }, (_, i) => padded.readUInt32LE(off + i * 4)) + let [A, B, C, D] = [a, b, c, d] + + // Round 1: F, shifts 3,7,11,19, word order 0..15 + for (let i = 0; i < 16; i++) { + A = rol(add(add(A, F(B, C, D)), X[i]), [3, 7, 11, 19][i & 3]) + ;[A, B, C, D] = [D, A, B, C] + } + // Round 2: G, shifts 3,5,9,13, word order 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 + const r2 = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15] + for (let i = 0; i < 16; i++) { + A = rol(add(add(add(A, G(B, C, D)), X[r2[i]]), 0x5a827999), [3, 5, 9, 13][i & 3]) + ;[A, B, C, D] = [D, A, B, C] + } + // Round 3: H, shifts 3,9,11,15, word order 0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15 + const r3 = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] + for (let i = 0; i < 16; i++) { + A = rol(add(add(add(A, H(B, C, D)), X[r3[i]]), 0x6ed9eba1), [3, 9, 11, 15][i & 3]) + ;[A, B, C, D] = [D, A, B, C] + } + + a = add(a, A); b = add(b, B); c = add(c, C); d = add(d, D) + } + + const out = Buffer.alloc(16) + out.writeUInt32LE(a, 0); out.writeUInt32LE(b, 4) + out.writeUInt32LE(c, 8); out.writeUInt32LE(d, 12) + return out +} + +// ── NTLM message builder ─────────────────────────────────────────────────────── + +const NTLMSSP_SIG = Buffer.from('NTLMSSP\0', 'ascii') + +// Negotiate flags for NTLMv2 +// UNICODE | REQUEST_TARGET | NTLM | ALWAYS_SIGN | EXTENDED_SESSION_SECURITY | 128bit | 56bit +const NTLM_FLAGS = 0xa0088215 + +/** Build Type 1 (Negotiate) message. Returns the full Authorization header value. */ +export function buildNegotiateHeader(): string { + const buf = Buffer.alloc(40) + NTLMSSP_SIG.copy(buf) + buf.writeUInt32LE(1, 8) // MessageType = NTLMSSP_NEGOTIATE + buf.writeUInt32LE(NTLM_FLAGS, 12) + // DomainName: empty + buf.writeUInt16LE(0, 16); buf.writeUInt16LE(0, 18); buf.writeUInt32LE(40, 20) + // Workstation: empty + buf.writeUInt16LE(0, 24); buf.writeUInt16LE(0, 26); buf.writeUInt32LE(40, 28) + return 'NTLM ' + buf.toString('base64') +} + +/** Parse the server's Type 2 (Challenge) message from the WWW-Authenticate header value. */ +export function parseChallenge(headerValue: string): { + challenge: Buffer + targetInfo: Buffer +} { + const b64 = headerValue.replace(/^NTLM\s+/i, '').trim() + const buf = Buffer.from(b64, 'base64') + + const serverChallenge = buf.slice(24, 32) + + // TargetInfoFields at offset 40: Len(2) MaxLen(2) Offset(4) + let targetInfo = Buffer.alloc(0) + if (buf.length >= 48) { + const len = buf.readUInt16LE(40) + const offset = buf.readUInt32LE(44) + if (len > 0 && offset + len <= buf.length) { + targetInfo = buf.slice(offset, offset + len) + } + } + + return { challenge: serverChallenge, targetInfo } +} + +/** Split "DOMAIN\\user", "user@domain", or "user" into { user, domain }. */ +export function splitUser(username: string): { user: string; domain: string } { + const bs = username.indexOf('\\') + if (bs !== -1) return { domain: username.slice(0, bs), user: username.slice(bs + 1) } + const at = username.indexOf('@') + if (at !== -1) return { user: username.slice(0, at), domain: username.slice(at + 1) } + return { user: username, domain: '' } +} + +/** + * Build Type 3 (Authenticate) message. + * Returns the full Authorization header value (NTLMv2). + */ +export function buildAuthenticateHeader( + username: string, + domain: string, + password: string, + serverChallenge: Buffer, + targetInfo: Buffer +): string { + // NT hash and NTLMv2 session key + const ntHashBuf = md4(Buffer.from(password, 'utf16le')) + const responseKeyNT = crypto + .createHmac('md5', ntHashBuf) + .update(Buffer.from((username.toUpperCase() + domain.toUpperCase()), 'utf16le')) + .digest() + + // Client challenge (random 8 bytes) + const clientChallenge = crypto.randomBytes(8) + + // Timestamp: 100ns intervals since 1601-01-01 (Windows FILETIME) + const EPOCH_DIFF_MS = BigInt('11644473600000') // ms from 1601 to 1970 + const nowMs = BigInt(Date.now()) + const fileTime = (nowMs + EPOCH_DIFF_MS) * BigInt(10000) + const timestamp = Buffer.alloc(8) + timestamp.writeBigUInt64LE(fileTime) + + // NTLMv2 blob (the "NTChallengeResponse blob") + const blob = Buffer.concat([ + Buffer.from([0x01, 0x01, 0x00, 0x00]), // Signature + Buffer.from([0x00, 0x00, 0x00, 0x00]), // Reserved + timestamp, // Timestamp + clientChallenge, // ChallengeFromClient + Buffer.from([0x00, 0x00, 0x00, 0x00]), // Reserved + targetInfo, // AvPairs from server Type 2 + Buffer.from([0x00, 0x00, 0x00, 0x00]), // AvPairs list terminator + ]) + + // NTProofStr = HMAC-MD5(ResponseKeyNT, ServerChallenge + blob) + const ntProofStr = crypto + .createHmac('md5', responseKeyNT) + .update(Buffer.concat([serverChallenge, blob])) + .digest() + + const ntResponse = Buffer.concat([ntProofStr, blob]) + const lmResponse = Buffer.alloc(24, 0) // empty LM response + + const userBuf = Buffer.from(username, 'utf16le') + const domBuf = Buffer.from(domain, 'utf16le') + const wsBuf = Buffer.alloc(0) + const skBuf = Buffer.alloc(0) // no session key + + // Build Type 3 header (88 bytes fixed) + payload + let payOff = 88 + const lmOff = payOff; payOff += lmResponse.length + const ntOff = payOff; payOff += ntResponse.length + const domOff = payOff; payOff += domBuf.length + const usrOff = payOff; payOff += userBuf.length + const wsOff = payOff; payOff += wsBuf.length + const skOff = payOff + + const msg = Buffer.alloc(skOff + skBuf.length) + NTLMSSP_SIG.copy(msg) + msg.writeUInt32LE(3, 8) // MessageType = NTLMSSP_AUTH + + const writeField = (off: number, len: number, dataOff: number) => { + msg.writeUInt16LE(len, off); msg.writeUInt16LE(len, off + 2); msg.writeUInt32LE(dataOff, off + 4) + } + writeField(12, lmResponse.length, lmOff) + writeField(20, ntResponse.length, ntOff) + writeField(28, domBuf.length, domOff) + writeField(36, userBuf.length, usrOff) + writeField(44, wsBuf.length, wsOff) + writeField(52, skBuf.length, skOff) + msg.writeUInt32LE(NTLM_FLAGS, 60) + // Version at 64 (8 bytes) and MIC at 72 (16 bytes) left as zeros + + lmResponse.copy(msg, lmOff) + ntResponse.copy(msg, ntOff) + domBuf.copy(msg, domOff) + userBuf.copy(msg, usrOff) + + return 'NTLM ' + msg.toString('base64') +} diff --git a/src/main/providers/caldav.provider.ts b/src/main/providers/caldav.provider.ts index 3394c4d..6f63539 100644 --- a/src/main/providers/caldav.provider.ts +++ b/src/main/providers/caldav.provider.ts @@ -5,7 +5,8 @@ * Exchange 2013+ exposes CalDAV at /EWS/Calendar/; standard servers * advertise the principal via /.well-known/caldav (RFC 6764). * - * Auth: HTTP Basic, same credentials as IMAP. + * Auth: tries HTTP Basic first; if server demands NTLM (corporate Exchange), + * falls back to NTLMv2 authentication automatically. */ import https from 'node:https' @@ -13,6 +14,12 @@ import http from 'node:http' import type { IncomingMessage } from 'node:http' import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar' +import { + buildNegotiateHeader, + parseChallenge, + buildAuthenticateHeader, + splitUser +} from '../lib/ntlm' // ── HTTP helper ──────────────────────────────────────────────────────────────── @@ -25,6 +32,7 @@ interface RequestOptions { headers: Record body?: string allowSelfSigned?: boolean + agent?: https.Agent | http.Agent } interface RequestResult { @@ -33,7 +41,7 @@ interface RequestResult { body: string } -function request(opts: RequestOptions): Promise { +function rawRequest(opts: RequestOptions): Promise { return new Promise((resolve, reject) => { const module_ = opts.protocol === 'https' ? https : http const req = module_.request( @@ -44,7 +52,8 @@ function request(opts: RequestOptions): Promise { method: opts.method, headers: opts.headers, rejectUnauthorized: !opts.allowSelfSigned, - timeout: 15_000 + timeout: 15_000, + agent: opts.agent }, (res) => { let data = '' @@ -88,7 +97,6 @@ function decodeICalText(value: string): string { } function extractEmail(value: string): string { - // ORGANIZER:mailto:user@example.com or ATTENDEE;CN=Name:mailto:user@example.com const match = value.match(/mailto:([^\s;,>]+)/i) return match ? match[1] : value } @@ -101,146 +109,93 @@ function parseVEvents(icalText: string): RawVEvent[] { let props: Record> = {} for (const line of lines) { - if (line === 'BEGIN:VEVENT') { - inEvent = true - props = {} - continue - } + if (line === 'BEGIN:VEVENT') { inEvent = true; props = {}; continue } if (line === 'END:VEVENT') { inEvent = false - - const get = (key: string) => props[key]?.[0]?.value ?? '' - const getParams = (key: string) => props[key]?.[0]?.params ?? '' - const getAll = (key: string) => (props[key] ?? []).map((x) => x.value) - + const get = (k: string) => props[k]?.[0]?.value ?? '' + const getParams = (k: string) => props[k]?.[0]?.params ?? '' + const getAll = (k: string) => (props[k] ?? []).map((x) => x.value) events.push({ - uid: get('UID'), - summary: decodeICalText(get('SUMMARY')), - dtstart: get('DTSTART'), - dtStartParams: getParams('DTSTART'), - dtend: get('DTEND'), - dtEndParams: getParams('DTEND'), - location: decodeICalText(get('LOCATION')), - description: decodeICalText(get('DESCRIPTION')), + uid: get('UID'), summary: decodeICalText(get('SUMMARY')), + dtstart: get('DTSTART'), dtStartParams: getParams('DTSTART'), + dtend: get('DTEND'), dtEndParams: getParams('DTEND'), + location: decodeICalText(get('LOCATION')), description: decodeICalText(get('DESCRIPTION')), organizer: extractEmail(get('ORGANIZER')), attendees: getAll('ATTENDEE').map(extractEmail).filter(Boolean), status: get('STATUS').toLowerCase() }) continue } - if (!inEvent) continue - - const colonIdx = line.indexOf(':') - if (colonIdx === -1) continue - - const keyFull = line.substring(0, colonIdx) - const value = line.substring(colonIdx + 1) - const semicolonIdx = keyFull.indexOf(';') - const key = semicolonIdx === -1 ? keyFull : keyFull.substring(0, semicolonIdx) - const params = semicolonIdx === -1 ? '' : keyFull.substring(semicolonIdx + 1) - + const ci = line.indexOf(':') + if (ci === -1) continue + const keyFull = line.substring(0, ci) + const value = line.substring(ci + 1) + const si = keyFull.indexOf(';') + const key = si === -1 ? keyFull : keyFull.substring(0, si) + const params = si === -1 ? '' : keyFull.substring(si + 1) if (!props[key]) props[key] = [] props[key].push({ value, params }) } - return events } -/** - * Parse iCal date/time string to a JS Date. - * Handles: DATE (20240401), DATE-TIME UTC (20240401T090000Z), - * DATE-TIME local (20240401T090000), with TZID param ignored (treated as local). - */ function parseICalDate(value: string, params: string): { date: Date; isAllDay: boolean } { const isAllDay = params.includes('VALUE=DATE') || /^\d{8}$/.test(value) - if (isAllDay) { - const y = parseInt(value.slice(0, 4), 10) - const m = parseInt(value.slice(4, 6), 10) - 1 - const d = parseInt(value.slice(6, 8), 10) - return { date: new Date(Date.UTC(y, m, d)), isAllDay: true } + return { + date: new Date(Date.UTC( + parseInt(value.slice(0, 4), 10), + parseInt(value.slice(4, 6), 10) - 1, + parseInt(value.slice(6, 8), 10) + )), + isAllDay: true + } } - const isUTC = value.endsWith('Z') const clean = isUTC ? value.slice(0, -1) : value - - const y = parseInt(clean.slice(0, 4), 10) - const mo = parseInt(clean.slice(4, 6), 10) - 1 - const d = parseInt(clean.slice(6, 8), 10) - const h = clean.length > 8 ? parseInt(clean.slice(9, 11), 10) : 0 + const y = parseInt(clean.slice(0, 4), 10), mo = parseInt(clean.slice(4, 6), 10) - 1 + const d = parseInt(clean.slice(6, 8), 10) + const h = clean.length > 8 ? parseInt(clean.slice(9, 11), 10) : 0 const mi = clean.length > 8 ? parseInt(clean.slice(11, 13), 10) : 0 - const s = clean.length > 8 ? parseInt(clean.slice(13, 15), 10) : 0 - - const date = isUTC - ? new Date(Date.UTC(y, mo, d, h, mi, s)) - : new Date(y, mo, d, h, mi, s) - - return { date, isAllDay: false } + const s = clean.length > 8 ? parseInt(clean.slice(13, 15), 10) : 0 + return { date: isUTC ? new Date(Date.UTC(y, mo, d, h, mi, s)) : new Date(y, mo, d, h, mi, s), isAllDay: false } } // ── XML helpers ──────────────────────────────────────────────────────────────── -/** Extract all (or namespaced equivalent) block contents from a multistatus XML response. */ function extractCalendarData(xml: string): string[] { const results: string[] = [] - // Match both namespaced and un-namespaced calendar-data elements const re = /<(?:[^:\s>]+:)?calendar-data[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?calendar-data>/g let match: RegExpExecArray | null while ((match = re.exec(xml)) !== null) { - // CalDAV may XML-encode special chars inside calendar-data - const raw = match[1] - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/&/g, '&') - .replace(/ /g, '\r') - .trim() + const raw = match[1].replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&').replace(/ /g, '\r').trim() if (raw.length > 0) results.push(raw) } return results } -/** Extract calendar collections from a PROPFIND multistatus response. */ -interface CalDavCalendar { - href: string - displayName: string -} +interface CalDavCalendar { href: string; displayName: string } function extractCalendars(xml: string, baseUrl: string): CalDavCalendar[] { const calendars: CalDavCalendar[] = [] - - // Split by blocks const responseRe = /<(?:[^:\s>]+:)?response[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?response>/g let match: RegExpExecArray | null - while ((match = responseRe.exec(xml)) !== null) { const block = match[1] - - // Must contain calendar resourcetype - if (!/<(?:[^:\s>]+:)?calendar[^>]*\/>/.test(block) && - !/<(?:[^:\s>]+:)?calendar[^>]*>/.test(block)) continue - + if (!/<(?:[^:\s>]+:)?calendar[^>]*\/?>/.test(block)) continue const hrefMatch = block.match(/<(?:[^:\s>]+:)?href[^>]*>([^<]+)<\/(?:[^:\s>]+:)?href>/) const nameMatch = block.match(/<(?:[^:\s>]+:)?displayname[^>]*>([^<]*)<\/(?:[^:\s>]+:)?displayname>/) - - if (hrefMatch) { - calendars.push({ - href: hrefMatch[1].trim(), - displayName: nameMatch ? decodeICalText(nameMatch[1].trim()) : 'Calendar' - }) - } + if (hrefMatch) calendars.push({ href: hrefMatch[1].trim(), displayName: nameMatch ? nameMatch[1].trim() : 'Calendar' }) } - - // If nothing found, treat the base path itself as the calendar - if (calendars.length === 0 && baseUrl.length > 0) { - calendars.push({ href: baseUrl, displayName: 'Calendar' }) - } - + if (calendars.length === 0 && baseUrl.length > 0) calendars.push({ href: baseUrl, displayName: 'Calendar' }) return calendars } // ── CalDAV Provider ──────────────────────────────────────────────────────────── +type AuthMode = 'basic' | 'ntlm' + export class CalDavProvider { private readonly hostname: string private readonly protocol: 'https' | 'http' @@ -248,34 +203,38 @@ export class CalDavProvider { private readonly username: string private readonly password: string private readonly allowSelfSigned: boolean - private readonly authHeader: string + private readonly basicAuthHeader: string - /** Resolved CalDAV base path (e.g. "/EWS/Calendar/") */ private basePath: string | null = null + private authMode: AuthMode = 'basic' constructor(config: AccountConfig) { const creds = config.credentials as ImapCredentials - - // Derive HTTPS endpoint from IMAP host; Exchange typically shares the hostname this.hostname = creds.host this.protocol = creds.secure ? 'https' : 'http' this.port = creds.secure ? 443 : 80 this.username = creds.username this.password = creds.password this.allowSelfSigned = creds.smtpAllowSelfSigned ?? false - - const encoded = Buffer.from(`${this.username}:${this.password}`).toString('base64') - this.authHeader = `Basic ${encoded}` + this.basicAuthHeader = 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64') } // ── Discovery ────────────────────────────────────────────────────────────── - /** - * Try to discover the CalDAV endpoint. - * Priority: /.well-known/caldav (RFC 6764) → /EWS/Calendar/ (Exchange) → /caldav/ (generic) - * Returns the resolved path or null if none found. - */ - async discoverBasePath(): Promise { + async connect(): Promise { + this.basePath = await this.discoverBasePath() + if (!this.basePath) { + throw new Error( + `CalDAV endpoint not found on ${this.hostname}. ` + + `Verified paths: /.well-known/caldav, /EWS/Calendar/. ` + + `Ensure Exchange CalDAV is enabled (Exchange 2013+).` + ) + } + } + + isConnected(): boolean { return this.basePath !== null } + + private async discoverBasePath(): Promise { const candidates = [ '/.well-known/caldav', '/EWS/Calendar/', @@ -287,202 +246,100 @@ export class CalDavProvider { for (const path of candidates) { try { - const result = await this.req('PROPFIND', path, { - Depth: '0', - 'Content-Type': 'application/xml; charset=utf-8', - }) - - // 207 Multi-Status = CalDAV responded, 301/302 = redirect → follow + const result = await this.req('PROPFIND', path, { Depth: '0' }) if (result.status === 207) return path if (result.status === 301 || result.status === 302) { const location = result.headers['location'] - if (location) { - const u = new URL(location, `${this.protocol}://${this.hostname}`) - return u.pathname + if (typeof location === 'string') { + try { return new URL(location, `${this.protocol}://${this.hostname}`).pathname } catch { /* skip */ } } } } catch { // Try next candidate } } - return null } - async connect(): Promise { - this.basePath = await this.discoverBasePath() - if (!this.basePath) { - throw new Error( - `CalDAV endpoint not found on ${this.hostname}. ` + - `Ensure Exchange CalDAV is enabled (Exchange 2013+).` - ) - } - } - - isConnected(): boolean { - return this.basePath !== null - } - // ── List calendars ───────────────────────────────────────────────────────── async listCalendars(accountId: string): Promise { if (!this.basePath) throw new Error('CalDAV not connected') - const body = ` - - - - + ` - - const result = await this.req('PROPFIND', this.basePath, { - Depth: '1', - 'Content-Type': 'application/xml; charset=utf-8', - }, body) - + const result = await this.req('PROPFIND', this.basePath, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) if (result.status !== 207) { - // Treat the base path as a single calendar on any other 2xx - return [{ - id: this.basePath, - name: 'Calendar', - accountId - }] + return [{ id: this.basePath, name: 'Calendar', accountId }] } - - const cals = extractCalendars(result.body, this.basePath) - return cals.map((c) => ({ - id: c.href, - name: c.displayName || 'Calendar', - accountId + return extractCalendars(result.body, this.basePath).map((c) => ({ + id: c.href, name: c.displayName || 'Calendar', accountId })) } // ── Fetch events ─────────────────────────────────────────────────────────── - async listEvents( - accountId: string, - calendarId: string, - start: Date, - end: Date - ): Promise { - const startStr = toUtcString(start) - const endStr = toUtcString(end) - + async listEvents(accountId: string, calendarId: string, start: Date, end: Date): Promise { const body = ` - - - - + - + ` - const result = await this.req('REPORT', calendarId, { - Depth: '1', - 'Content-Type': 'application/xml; charset=utf-8', - }, body) - - if (result.status !== 207) { - // Exchange may not support time-range; fall back to PROPFIND + client-side filtering - return this.fetchAllEventsAndFilter(accountId, calendarId, start, end) - } - - return this.parseMultistatusEvents(result.body, accountId, calendarId) + const result = await this.req('REPORT', calendarId, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) + if (result.status !== 207) return this.fetchAllAndFilter(accountId, calendarId, start, end) + return this.parseMultistatus(result.body, accountId, calendarId) } - /** Fallback: fetch all VEVENT objects and filter client-side by time range. */ - private async fetchAllEventsAndFilter( - accountId: string, - calendarId: string, - start: Date, - end: Date - ): Promise { + private async fetchAllAndFilter(accountId: string, calendarId: string, start: Date, end: Date): Promise { const body = ` - - - - - - - - - + + ` - - const result = await this.req('REPORT', calendarId, { - Depth: '1', - 'Content-Type': 'application/xml; charset=utf-8', - }, body) - + const result = await this.req('REPORT', calendarId, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) if (result.status !== 207) return [] - - const all = this.parseMultistatusEvents(result.body, accountId, calendarId) - return all.filter((ev) => { - const evEnd = new Date(ev.end) - const evStart = new Date(ev.start) - return evStart < end && evEnd > start - }) + return this.parseMultistatus(result.body, accountId, calendarId).filter((ev) => + new Date(ev.start) < end && new Date(ev.end) > start + ) } - // ── Parsing ──────────────────────────────────────────────────────────────── - - private parseMultistatusEvents( - xml: string, - accountId: string, - calendarId: string - ): CalendarEvent[] { + private parseMultistatus(xml: string, accountId: string, calendarId: string): CalendarEvent[] { const events: CalendarEvent[] = [] - const icalBlocks = extractCalendarData(xml) - - for (const block of icalBlocks) { - const raw = parseVEvents(block) - for (const rv of raw) { + for (const block of extractCalendarData(xml)) { + for (const rv of parseVEvents(block)) { if (!rv.dtstart) continue - const { date: startDate, isAllDay } = parseICalDate(rv.dtstart, rv.dtStartParams) let endDate: Date - - if (rv.dtend) { - endDate = parseICalDate(rv.dtend, rv.dtEndParams).date - } else { - // No DTEND: for all-day events default to +1 day, for timed +1 hour - endDate = new Date(startDate) - if (isAllDay) endDate.setUTCDate(endDate.getUTCDate() + 1) - else endDate.setTime(endDate.getTime() + 60 * 60 * 1000) - } - - const id = `${calendarId}::${rv.uid || startDate.toISOString()}` - + if (rv.dtend) endDate = parseICalDate(rv.dtend, rv.dtEndParams).date + else { endDate = new Date(startDate); if (isAllDay) endDate.setUTCDate(endDate.getUTCDate() + 1); else endDate.setTime(endDate.getTime() + 3_600_000) } events.push({ - id, - uid: rv.uid, - calendarId, - accountId, + id: `${calendarId}::${rv.uid || startDate.toISOString()}`, + uid: rv.uid, calendarId, accountId, title: rv.summary || '(no title)', - start: startDate.toISOString(), - end: endDate.toISOString(), - isAllDay, - location: rv.location || undefined, - description: rv.description || undefined, - organizer: rv.organizer || undefined, - attendees: rv.attendees, + start: startDate.toISOString(), end: endDate.toISOString(), isAllDay, + location: rv.location || undefined, description: rv.description || undefined, + organizer: rv.organizer || undefined, attendees: rv.attendees, status: (rv.status as CalendarEvent['status']) || 'confirmed' }) } } - return events } - // ── Internal HTTP helper ─────────────────────────────────────────────────── + // ── Authenticated HTTP request ───────────────────────────────────────────── + // + // Strategy: + // 1. Try with Basic auth (or NTLM if already detected). + // 2. If server replies 401 with WWW-Authenticate containing "NTLM", + // switch to NTLM and retry. private async req( method: string, @@ -490,41 +347,119 @@ export class CalDavProvider { extraHeaders: Record = {}, body?: string ): Promise { - const headers: Record = { - Authorization: this.authHeader, - 'User-Agent': 'AeroMail/1.0', - ...extraHeaders - } - if (body) { - headers['Content-Length'] = Buffer.byteLength(body, 'utf8').toString() + if (this.authMode === 'ntlm') { + return this.reqNtlm(method, path, extraHeaders, body) } - return request({ + // Try Basic first + const result = await this.rawReq(method, path, { Authorization: this.basicAuthHeader, ...extraHeaders }, body) + + if (result.status === 401 && this.needsNtlm(result.headers)) { + // Server requires NTLM — switch mode and retry + this.authMode = 'ntlm' + return this.reqNtlm(method, path, extraHeaders, body) + } + + return result + } + + /** + * Execute a full NTLMv2 3-way handshake and return the authenticated response. + * + * Both the Negotiate (Type 1) and Authenticate (Type 3) requests MUST use the + * same TCP connection. We achieve this by creating a fresh keepAlive Agent with + * maxSockets:1 for each operation — the first socket created is reused for the + * second request automatically. + */ + private async reqNtlm( + method: string, + path: string, + extraHeaders: Record = {}, + body?: string + ): Promise { + const agentOpts = { keepAlive: true, maxSockets: 1, rejectUnauthorized: !this.allowSelfSigned } + const agent = this.protocol === 'https' + ? new https.Agent(agentOpts) + : new http.Agent({ keepAlive: true, maxSockets: 1 }) + + try { + // Step 1: Type 1 Negotiate (no body, just the method + NTLM negotiate header) + const type1Result = await this.rawReq( + method, path, + { Authorization: buildNegotiateHeader(), ...extraHeaders }, + undefined, + agent + ) + + // Step 2: Extract Type 2 Challenge from 401 response + const wwwAuth = this.extractNtlmChallenge(type1Result.headers) + if (!wwwAuth) { + // Server accepted Type 1 without a challenge (unusual) — return as-is + return type1Result + } + + const { challenge, targetInfo } = parseChallenge(wwwAuth) + const { user, domain } = splitUser(this.username) + const type3Header = buildAuthenticateHeader(user, domain, this.password, challenge, targetInfo) + + // Step 3: Type 3 Authenticate with actual request body + const finalResult = await this.rawReq( + method, path, + { Authorization: type3Header, ...extraHeaders }, + body, + agent + ) + return finalResult + } finally { + agent.destroy() + } + } + + private rawReq( + method: string, + path: string, + headers: Record, + body?: string, + agent?: https.Agent | http.Agent + ): Promise { + const allHeaders: Record = { + 'User-Agent': 'AeroMail/1.0', + ...headers + } + if (body) allHeaders['Content-Length'] = Buffer.byteLength(body, 'utf8').toString() + + return rawRequest({ protocol: this.protocol, hostname: this.hostname, port: this.port, path, method, - headers, + headers: allHeaders, body, - allowSelfSigned: this.allowSelfSigned + allowSelfSigned: this.allowSelfSigned, + agent }) } + + /** Returns the NTLM challenge header value, or null if the response doesn't contain one. */ + private extractNtlmChallenge(headers: IncomingMessage['headers']): string | null { + const auth = headers['www-authenticate'] + const list = Array.isArray(auth) ? auth : typeof auth === 'string' ? auth.split(',') : [] + const ntlmHeader = list.map((s) => s.trim()).find((s) => /^NTLM\s+/i.test(s)) + return ntlmHeader ?? null + } + + /** Returns true if a 401 response is asking for NTLM/Negotiate. */ + private needsNtlm(headers: IncomingMessage['headers']): boolean { + const auth = headers['www-authenticate'] + const s = Array.isArray(auth) ? auth.join(',') : auth ?? '' + return /NTLM|Negotiate/i.test(s) + } } // ── Utility ──────────────────────────────────────────────────────────────────── -/** Format a Date as an iCal UTC string: 20240401T000000Z */ function toUtcString(d: Date): string { - const pad = (n: number) => String(n).padStart(2, '0') - return ( - d.getUTCFullYear().toString() + - pad(d.getUTCMonth() + 1) + - pad(d.getUTCDate()) + - 'T' + - pad(d.getUTCHours()) + - pad(d.getUTCMinutes()) + - pad(d.getUTCSeconds()) + - 'Z' - ) + const p = (n: number) => String(n).padStart(2, '0') + return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z` } From 42093ed8f395ec89affeafb7877ddb5cc6d8c36f Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 03:13:16 +0000 Subject: [PATCH 3/6] feat: add separate CalDAV endpoint settings per account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ImapCredentials now has caldavHost/caldavPort/caldavSecure/caldavPath. When set, CalDavProvider uses them instead of the IMAP host. caldavPath skips autodiscovery and hits the URL directly. Both AddAccountDialog and EditAccountDialog have a collapsible "Настройки CalDAV" section (same pattern as SMTP). Co-Authored-By: Claude Sonnet 4.6 --- src/main/providers/caldav.provider.ts | 31 ++++++++++-- .../components/accounts/AddAccountDialog.vue | 48 +++++++++++++++++++ .../components/accounts/EditAccountDialog.vue | 48 +++++++++++++++++++ src/shared/types/account.ts | 5 ++ 4 files changed, 127 insertions(+), 5 deletions(-) diff --git a/src/main/providers/caldav.provider.ts b/src/main/providers/caldav.provider.ts index 6f63539..341a656 100644 --- a/src/main/providers/caldav.provider.ts +++ b/src/main/providers/caldav.provider.ts @@ -206,28 +206,49 @@ export class CalDavProvider { private readonly basicAuthHeader: string private basePath: string | null = null + private staticBasePath: string | null = null private authMode: AuthMode = 'basic' constructor(config: AccountConfig) { const creds = config.credentials as ImapCredentials - this.hostname = creds.host - this.protocol = creds.secure ? 'https' : 'http' - this.port = creds.secure ? 443 : 80 + + // CalDAV endpoint: use dedicated settings when provided, fall back to IMAP host + const calSecure = creds.caldavSecure ?? creds.secure + this.hostname = creds.caldavHost || creds.host + this.protocol = calSecure ? 'https' : 'http' + this.port = creds.caldavPort ?? (calSecure ? 443 : 80) this.username = creds.username this.password = creds.password this.allowSelfSigned = creds.smtpAllowSelfSigned ?? false + + // If a static CalDAV path is configured, skip autodiscovery + this.staticBasePath = creds.caldavPath?.trim() || null + this.basicAuthHeader = 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64') } // ── Discovery ────────────────────────────────────────────────────────────── async connect(): Promise { + if (this.staticBasePath) { + // User supplied an explicit path — verify it works, skip autodiscovery + const result = await this.req('PROPFIND', this.staticBasePath, { Depth: '0' }) + if (result.status !== 207 && result.status !== 200) { + throw new Error( + `CalDAV path "${this.staticBasePath}" on ${this.hostname} returned HTTP ${result.status}. ` + + `Check the CalDAV URL and credentials.` + ) + } + this.basePath = this.staticBasePath + return + } + this.basePath = await this.discoverBasePath() if (!this.basePath) { throw new Error( `CalDAV endpoint not found on ${this.hostname}. ` + - `Verified paths: /.well-known/caldav, /EWS/Calendar/. ` + - `Ensure Exchange CalDAV is enabled (Exchange 2013+).` + `Tried: /.well-known/caldav, /EWS/Calendar/. ` + + `Set the CalDAV URL explicitly in account settings, or ensure Exchange CalDAV is enabled (Exchange 2013+).` ) } } diff --git a/src/renderer/src/components/accounts/AddAccountDialog.vue b/src/renderer/src/components/accounts/AddAccountDialog.vue index 2cfda49..af568bb 100644 --- a/src/renderer/src/components/accounts/AddAccountDialog.vue +++ b/src/renderer/src/components/accounts/AddAccountDialog.vue @@ -34,6 +34,12 @@ const smtpSecure = ref(false) const smtpAllowSelfSigned = ref(false) const showSmtp = ref(false) +const caldavHost = ref('') +const caldavPort = ref(443) +const caldavSecure = ref(true) +const caldavPath = ref('') +const showCaldav = ref(false) + function generateId(): string { return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}` } @@ -57,6 +63,14 @@ async function handleSubmit(): Promise { smtpSecure: smtpSecure.value, ...(smtpAllowSelfSigned.value ? { smtpAllowSelfSigned: true } : {}) } + : {}), + ...(showCaldav.value && caldavHost.value + ? { + caldavHost: caldavHost.value, + caldavPort: caldavPort.value, + caldavSecure: caldavSecure.value, + ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}) + } : {}) } const config: AccountConfig = { @@ -173,6 +187,40 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value && imapP + +
+ +
+
+
+ + +
+
+ + +
+
+
+ +
+
+ + +
+
+
+ diff --git a/src/renderer/src/components/accounts/EditAccountDialog.vue b/src/renderer/src/components/accounts/EditAccountDialog.vue index aa14d2d..56dbd55 100644 --- a/src/renderer/src/components/accounts/EditAccountDialog.vue +++ b/src/renderer/src/components/accounts/EditAccountDialog.vue @@ -32,6 +32,12 @@ const smtpPort = ref(creds.smtpPort ?? 587) const smtpSecure = ref(creds.smtpSecure ?? false) const showSmtp = ref(!!creds.smtpHost) +const caldavHost = ref(creds.caldavHost ?? '') +const caldavPort = ref(creds.caldavPort ?? 443) +const caldavSecure = ref(creds.caldavSecure ?? true) +const caldavPath = ref(creds.caldavPath ?? '') +const showCaldav = ref(!!creds.caldavHost) + async function handleSubmit(): Promise { testing.value = true error.value = '' @@ -45,6 +51,14 @@ async function handleSubmit(): Promise { password: imapPassword.value, ...(showSmtp.value && smtpHost.value ? { smtpHost: smtpHost.value, smtpPort: smtpPort.value, smtpSecure: smtpSecure.value } + : {}), + ...(showCaldav.value && caldavHost.value + ? { + caldavHost: caldavHost.value, + caldavPort: caldavPort.value, + caldavSecure: caldavSecure.value, + ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}) + } : {}) } const config: AccountConfig = { @@ -155,6 +169,40 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value) + +
+ +
+
+
+ + +
+
+ + +
+
+
+ +
+
+ + +
+
+
+ diff --git a/src/shared/types/account.ts b/src/shared/types/account.ts index 503fb9d..0fcfa8a 100644 --- a/src/shared/types/account.ts +++ b/src/shared/types/account.ts @@ -14,6 +14,11 @@ export interface ImapCredentials { smtpSecure?: boolean // Разрешить самоподписанные сертификаты — только для корпоративных серверов smtpAllowSelfSigned?: boolean + // CalDAV — опционально; если не указан хост, используется IMAP-хост + caldavHost?: string + caldavPort?: number + caldavSecure?: boolean + caldavPath?: string // базовый путь, например /EWS/Calendar/ (если пуст — autodiscovery) } export type AccountCredentials = ImapCredentials From 360d389a87c42d3f3f58f559096ce45268e3350e Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 03:16:12 +0000 Subject: [PATCH 4/6] fix: make CalDAV error text selectable and copyable Co-Authored-By: Claude Sonnet 4.6 --- src/renderer/src/views/CalendarView.vue | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/renderer/src/views/CalendarView.vue b/src/renderer/src/views/CalendarView.vue index 0c1b02e..5a2104c 100644 --- a/src/renderer/src/views/CalendarView.vue +++ b/src/renderer/src/views/CalendarView.vue @@ -303,6 +303,9 @@ function handleEventClick(ev: CalendarEvent): void { font-size: 11px; color: var(--text-muted); word-break: break-all; + user-select: text; + -webkit-user-select: text; + cursor: text; } .error-hint { From d47b30bbb069ac8da531b65e45d12cf0786c00b8 Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 03:20:25 +0000 Subject: [PATCH 5/6] fix: surface CalDAV TLS/network errors and add caldavAllowSelfSigned option - discoverBasePath now throws on TLS errors immediately instead of silently swallowing them as "endpoint not found" - TLS errors include a hint to enable the new self-signed cert option - Other errors (network, auth) are collected and shown in the final message - Added caldavAllowSelfSigned field to ImapCredentials and both account dialogs - CalDavProvider prefers caldavAllowSelfSigned, falls back to smtpAllowSelfSigned Co-Authored-By: Claude Sonnet 4.6 --- src/main/providers/caldav.provider.ts | 41 ++++++++++++++++--- .../components/accounts/AddAccountDialog.vue | 20 ++++++--- .../components/accounts/EditAccountDialog.vue | 20 ++++++--- src/shared/types/account.ts | 3 +- 4 files changed, 65 insertions(+), 19 deletions(-) diff --git a/src/main/providers/caldav.provider.ts b/src/main/providers/caldav.provider.ts index 341a656..ab2666a 100644 --- a/src/main/providers/caldav.provider.ts +++ b/src/main/providers/caldav.provider.ts @@ -219,7 +219,8 @@ export class CalDavProvider { this.port = creds.caldavPort ?? (calSecure ? 443 : 80) this.username = creds.username this.password = creds.password - this.allowSelfSigned = creds.smtpAllowSelfSigned ?? false + // caldavAllowSelfSigned takes precedence; fall back to smtpAllowSelfSigned for legacy configs + this.allowSelfSigned = creds.caldavAllowSelfSigned ?? creds.smtpAllowSelfSigned ?? false // If a static CalDAV path is configured, skip autodiscovery this.staticBasePath = creds.caldavPath?.trim() || null @@ -244,11 +245,11 @@ export class CalDavProvider { } this.basePath = await this.discoverBasePath() + // discoverBasePath throws on TLS/network errors; returning null means all paths gave 404/403 if (!this.basePath) { throw new Error( - `CalDAV endpoint not found on ${this.hostname}. ` + - `Tried: /.well-known/caldav, /EWS/Calendar/. ` + - `Set the CalDAV URL explicitly in account settings, or ensure Exchange CalDAV is enabled (Exchange 2013+).` + `CalDAV not found on ${this.hostname} — all candidate paths returned 404/403.\n` + + `Set the CalDAV path explicitly in account settings (e.g. /EWS/Calendar/).` ) } } @@ -265,6 +266,9 @@ export class CalDavProvider { '/dav/', ] + // Collect errors so we can surface the most useful one if all paths fail + const errors: string[] = [] + for (const path of candidates) { try { const result = await this.req('PROPFIND', path, { Depth: '0' }) @@ -275,10 +279,31 @@ export class CalDavProvider { try { return new URL(location, `${this.protocol}://${this.hostname}`).pathname } catch { /* skip */ } } } - } catch { - // Try next candidate + // Record non-successful status for diagnostics (skip common "not found" ones) + if (result.status !== 404 && result.status !== 403) { + errors.push(`${path} → HTTP ${result.status}`) + } + } catch (err) { + const msg = (err as Error).message ?? String(err) + // TLS errors: surface immediately — retrying other paths won't help + if (isTlsError(msg)) { + throw new Error( + `TLS certificate error connecting to ${this.hostname}: ${msg}\n` + + `Enable "Разрешить самоподписанные сертификаты" in CalDAV settings.` + ) + } + errors.push(`${path} → ${msg}`) } } + + if (errors.length > 0) { + throw new Error( + `CalDAV endpoint not found on ${this.hostname}.\n` + + errors.map((e) => ` • ${e}`).join('\n') + '\n' + + `Set the CalDAV path explicitly in account settings (e.g. /EWS/Calendar/).` + ) + } + return null } @@ -480,6 +505,10 @@ export class CalDavProvider { // ── Utility ──────────────────────────────────────────────────────────────────── +function isTlsError(msg: string): boolean { + return /self.signed|UNABLE_TO_VERIFY|CERT_|certificate|SSL|TLS/i.test(msg) +} + function toUtcString(d: Date): string { const p = (n: number) => String(n).padStart(2, '0') return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z` diff --git a/src/renderer/src/components/accounts/AddAccountDialog.vue b/src/renderer/src/components/accounts/AddAccountDialog.vue index af568bb..ed2bb9f 100644 --- a/src/renderer/src/components/accounts/AddAccountDialog.vue +++ b/src/renderer/src/components/accounts/AddAccountDialog.vue @@ -34,11 +34,12 @@ const smtpSecure = ref(false) const smtpAllowSelfSigned = ref(false) const showSmtp = ref(false) -const caldavHost = ref('') -const caldavPort = ref(443) -const caldavSecure = ref(true) -const caldavPath = ref('') -const showCaldav = ref(false) +const caldavHost = ref('') +const caldavPort = ref(443) +const caldavSecure = ref(true) +const caldavPath = ref('') +const caldavAllowSelfSigned = ref(false) +const showCaldav = ref(false) function generateId(): string { return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}` @@ -69,7 +70,8 @@ async function handleSubmit(): Promise { caldavHost: caldavHost.value, caldavPort: caldavPort.value, caldavSecure: caldavSecure.value, - ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}) + ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}), + ...(caldavAllowSelfSigned.value ? { caldavAllowSelfSigned: true } : {}) } : {}) } @@ -218,6 +220,12 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value && imapP +
+ +
diff --git a/src/renderer/src/components/accounts/EditAccountDialog.vue b/src/renderer/src/components/accounts/EditAccountDialog.vue index 56dbd55..10b8bc4 100644 --- a/src/renderer/src/components/accounts/EditAccountDialog.vue +++ b/src/renderer/src/components/accounts/EditAccountDialog.vue @@ -32,11 +32,12 @@ const smtpPort = ref(creds.smtpPort ?? 587) const smtpSecure = ref(creds.smtpSecure ?? false) const showSmtp = ref(!!creds.smtpHost) -const caldavHost = ref(creds.caldavHost ?? '') -const caldavPort = ref(creds.caldavPort ?? 443) -const caldavSecure = ref(creds.caldavSecure ?? true) -const caldavPath = ref(creds.caldavPath ?? '') -const showCaldav = ref(!!creds.caldavHost) +const caldavHost = ref(creds.caldavHost ?? '') +const caldavPort = ref(creds.caldavPort ?? 443) +const caldavSecure = ref(creds.caldavSecure ?? true) +const caldavPath = ref(creds.caldavPath ?? '') +const caldavAllowSelfSigned = ref(creds.caldavAllowSelfSigned ?? false) +const showCaldav = ref(!!creds.caldavHost) async function handleSubmit(): Promise { testing.value = true @@ -57,7 +58,8 @@ async function handleSubmit(): Promise { caldavHost: caldavHost.value, caldavPort: caldavPort.value, caldavSecure: caldavSecure.value, - ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}) + ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}), + ...(caldavAllowSelfSigned.value ? { caldavAllowSelfSigned: true } : {}) } : {}) } @@ -200,6 +202,12 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value) +
+ +
diff --git a/src/shared/types/account.ts b/src/shared/types/account.ts index 0fcfa8a..530824e 100644 --- a/src/shared/types/account.ts +++ b/src/shared/types/account.ts @@ -18,7 +18,8 @@ export interface ImapCredentials { caldavHost?: string caldavPort?: number caldavSecure?: boolean - caldavPath?: string // базовый путь, например /EWS/Calendar/ (если пуст — autodiscovery) + caldavPath?: string // базовый путь, например /EWS/Calendar/ (если пуст — autodiscovery) + caldavAllowSelfSigned?: boolean // разрешить самоподписанные/недоверенные сертификаты } export type AccountCredentials = ImapCredentials From f130823c7c0bda94ec3955b6780ebbd9eadd5b30 Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 05:29:48 +0000 Subject: [PATCH 6/6] feat: replace CalDAV with EWS SOAP for Exchange calendar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rewrote calendar provider to use EWS (Exchange Web Services) SOAP API instead of CalDAV, which is disabled on most Exchange deployments - NTLM: extract TargetName from Type 2 challenge and use as domain fallback when username has no explicit domain (fixes NTLMv2 hash) - listCalendars: GetFolder for main calendar name + FindFolder for sub-calendars (main "Календарь" folder now always shown first) - listEvents: FindItem with CalendarView for automatic recurrence expansion - Removed ~600 lines of CalDAV/iCal parser dead code - Added calendar:probe IPC channel with EWS diagnostic info - CalendarView: "Найти CalDAV путь" button shows probe results Co-Authored-By: Claude Sonnet 4.6 --- src/main/ipc/calendar.handler.ts | 4 + src/main/lib/ntlm.ts | 16 +- src/main/providers/caldav.provider.ts | 506 ++++++++++-------------- src/main/services/account-manager.ts | 21 + src/renderer/src/views/CalendarView.vue | 106 ++++- src/shared/types/ipc.ts | 4 + 6 files changed, 346 insertions(+), 311 deletions(-) diff --git a/src/main/ipc/calendar.handler.ts b/src/main/ipc/calendar.handler.ts index aa6a2b2..54f1666 100644 --- a/src/main/ipc/calendar.handler.ts +++ b/src/main/ipc/calendar.handler.ts @@ -9,4 +9,8 @@ export function registerCalendarHandlers(manager: AccountManager): void { registerHandler('calendar:events', ({ accountId, calendarId, start, end }) => manager.listCalendarEvents(accountId, calendarId, new Date(start), new Date(end)) ) + + registerHandler('calendar:probe', ({ accountId }) => + manager.probeCalendarPaths(accountId) + ) } diff --git a/src/main/lib/ntlm.ts b/src/main/lib/ntlm.ts index 405dd3f..d498592 100644 --- a/src/main/lib/ntlm.ts +++ b/src/main/lib/ntlm.ts @@ -92,23 +92,35 @@ export function buildNegotiateHeader(): string { export function parseChallenge(headerValue: string): { challenge: Buffer targetInfo: Buffer + /** NetBIOS domain name from the server (e.g. "S7"). Use as domain fallback when none in username. */ + targetName: string } { const b64 = headerValue.replace(/^NTLM\s+/i, '').trim() const buf = Buffer.from(b64, 'base64') const serverChallenge = buf.slice(24, 32) + // TargetNameFields at offset 12: Len(2) MaxLen(2) Offset(4) — the server's NetBIOS domain + let targetName = '' + if (buf.length >= 20) { + const len = buf.readUInt16LE(12) + const offset = buf.readUInt32LE(16) + if (len > 0 && offset + len <= buf.length) { + targetName = buf.slice(offset, offset + len).toString('utf16le') + } + } + // TargetInfoFields at offset 40: Len(2) MaxLen(2) Offset(4) let targetInfo = Buffer.alloc(0) if (buf.length >= 48) { - const len = buf.readUInt16LE(40) + const len = buf.readUInt16LE(40) const offset = buf.readUInt32LE(44) if (len > 0 && offset + len <= buf.length) { targetInfo = buf.slice(offset, offset + len) } } - return { challenge: serverChallenge, targetInfo } + return { challenge: serverChallenge, targetInfo, targetName } } /** Split "DOMAIN\\user", "user@domain", or "user" into { user, domain }. */ diff --git a/src/main/providers/caldav.provider.ts b/src/main/providers/caldav.provider.ts index ab2666a..348846f 100644 --- a/src/main/providers/caldav.provider.ts +++ b/src/main/providers/caldav.provider.ts @@ -1,12 +1,9 @@ /** - * CalDAV provider for Exchange (and any CalDAV-compliant server). + * Exchange calendar provider via EWS (Exchange Web Services) SOAP API. * * Uses only Node.js built-in `https`/`http` — no extra npm deps. - * Exchange 2013+ exposes CalDAV at /EWS/Calendar/; standard servers - * advertise the principal via /.well-known/caldav (RFC 6764). - * - * Auth: tries HTTP Basic first; if server demands NTLM (corporate Exchange), - * falls back to NTLMv2 authentication automatically. + * Auth: tries HTTP Basic first; if server demands NTLM, falls back to NTLMv2. + * EWS endpoint: POST /EWS/Exchange.asmx */ import https from 'node:https' @@ -64,328 +61,266 @@ function rawRequest(opts: RequestOptions): Promise { }) } ) - req.on('timeout', () => { req.destroy(new Error('CalDAV request timed out')) }) + req.on('timeout', () => { req.destroy(new Error('Request timed out')) }) req.on('error', reject) if (opts.body) req.write(opts.body) req.end() }) } -// ── Minimal iCal parser ──────────────────────────────────────────────────────── - -interface RawVEvent { - uid: string - summary: string - dtstart: string - dtStartParams: string - dtend: string - dtEndParams: string - location: string - description: string - organizer: string - attendees: string[] - status: string -} - -/** RFC 5545 line-unfolding: CRLF followed by a space or tab is a continuation. */ -function unfoldLines(raw: string): string[] { - return raw.replace(/\r\n[ \t]/g, '').replace(/\n[ \t]/g, '').split(/\r\n|\n/) -} - -function decodeICalText(value: string): string { - return value.replace(/\\n/g, '\n').replace(/\\,/g, ',').replace(/\\;/g, ';').replace(/\\\\/g, '\\') -} - -function extractEmail(value: string): string { - const match = value.match(/mailto:([^\s;,>]+)/i) - return match ? match[1] : value -} - -function parseVEvents(icalText: string): RawVEvent[] { - const events: RawVEvent[] = [] - const lines = unfoldLines(icalText) - - let inEvent = false - let props: Record> = {} - - for (const line of lines) { - if (line === 'BEGIN:VEVENT') { inEvent = true; props = {}; continue } - if (line === 'END:VEVENT') { - inEvent = false - const get = (k: string) => props[k]?.[0]?.value ?? '' - const getParams = (k: string) => props[k]?.[0]?.params ?? '' - const getAll = (k: string) => (props[k] ?? []).map((x) => x.value) - events.push({ - uid: get('UID'), summary: decodeICalText(get('SUMMARY')), - dtstart: get('DTSTART'), dtStartParams: getParams('DTSTART'), - dtend: get('DTEND'), dtEndParams: getParams('DTEND'), - location: decodeICalText(get('LOCATION')), description: decodeICalText(get('DESCRIPTION')), - organizer: extractEmail(get('ORGANIZER')), - attendees: getAll('ATTENDEE').map(extractEmail).filter(Boolean), - status: get('STATUS').toLowerCase() - }) - continue - } - if (!inEvent) continue - const ci = line.indexOf(':') - if (ci === -1) continue - const keyFull = line.substring(0, ci) - const value = line.substring(ci + 1) - const si = keyFull.indexOf(';') - const key = si === -1 ? keyFull : keyFull.substring(0, si) - const params = si === -1 ? '' : keyFull.substring(si + 1) - if (!props[key]) props[key] = [] - props[key].push({ value, params }) - } - return events -} - -function parseICalDate(value: string, params: string): { date: Date; isAllDay: boolean } { - const isAllDay = params.includes('VALUE=DATE') || /^\d{8}$/.test(value) - if (isAllDay) { - return { - date: new Date(Date.UTC( - parseInt(value.slice(0, 4), 10), - parseInt(value.slice(4, 6), 10) - 1, - parseInt(value.slice(6, 8), 10) - )), - isAllDay: true - } - } - const isUTC = value.endsWith('Z') - const clean = isUTC ? value.slice(0, -1) : value - const y = parseInt(clean.slice(0, 4), 10), mo = parseInt(clean.slice(4, 6), 10) - 1 - const d = parseInt(clean.slice(6, 8), 10) - const h = clean.length > 8 ? parseInt(clean.slice(9, 11), 10) : 0 - const mi = clean.length > 8 ? parseInt(clean.slice(11, 13), 10) : 0 - const s = clean.length > 8 ? parseInt(clean.slice(13, 15), 10) : 0 - return { date: isUTC ? new Date(Date.UTC(y, mo, d, h, mi, s)) : new Date(y, mo, d, h, mi, s), isAllDay: false } -} - -// ── XML helpers ──────────────────────────────────────────────────────────────── - -function extractCalendarData(xml: string): string[] { - const results: string[] = [] - const re = /<(?:[^:\s>]+:)?calendar-data[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?calendar-data>/g - let match: RegExpExecArray | null - while ((match = re.exec(xml)) !== null) { - const raw = match[1].replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&').replace(/ /g, '\r').trim() - if (raw.length > 0) results.push(raw) - } - return results -} - -interface CalDavCalendar { href: string; displayName: string } - -function extractCalendars(xml: string, baseUrl: string): CalDavCalendar[] { - const calendars: CalDavCalendar[] = [] - const responseRe = /<(?:[^:\s>]+:)?response[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?response>/g - let match: RegExpExecArray | null - while ((match = responseRe.exec(xml)) !== null) { - const block = match[1] - if (!/<(?:[^:\s>]+:)?calendar[^>]*\/?>/.test(block)) continue - const hrefMatch = block.match(/<(?:[^:\s>]+:)?href[^>]*>([^<]+)<\/(?:[^:\s>]+:)?href>/) - const nameMatch = block.match(/<(?:[^:\s>]+:)?displayname[^>]*>([^<]*)<\/(?:[^:\s>]+:)?displayname>/) - if (hrefMatch) calendars.push({ href: hrefMatch[1].trim(), displayName: nameMatch ? nameMatch[1].trim() : 'Calendar' }) - } - if (calendars.length === 0 && baseUrl.length > 0) calendars.push({ href: baseUrl, displayName: 'Calendar' }) - return calendars -} - -// ── CalDAV Provider ──────────────────────────────────────────────────────────── +// ── EWS Provider ────────────────────────────────────────────────────────────── type AuthMode = 'basic' | 'ntlm' +const EWS_PATH = '/EWS/Exchange.asmx' + export class CalDavProvider { private readonly hostname: string private readonly protocol: 'https' | 'http' private readonly port: number private readonly username: string + private readonly email: string private readonly password: string private readonly allowSelfSigned: boolean private readonly basicAuthHeader: string - private basePath: string | null = null - private staticBasePath: string | null = null private authMode: AuthMode = 'basic' + private connected = false constructor(config: AccountConfig) { const creds = config.credentials as ImapCredentials - // CalDAV endpoint: use dedicated settings when provided, fall back to IMAP host const calSecure = creds.caldavSecure ?? creds.secure - this.hostname = creds.caldavHost || creds.host + this.hostname = (creds.caldavHost || creds.host).replace(/\/+$/, '') this.protocol = calSecure ? 'https' : 'http' this.port = creds.caldavPort ?? (calSecure ? 443 : 80) this.username = creds.username + this.email = config.email || creds.username this.password = creds.password - // caldavAllowSelfSigned takes precedence; fall back to smtpAllowSelfSigned for legacy configs this.allowSelfSigned = creds.caldavAllowSelfSigned ?? creds.smtpAllowSelfSigned ?? false - - // If a static CalDAV path is configured, skip autodiscovery - this.staticBasePath = creds.caldavPath?.trim() || null - this.basicAuthHeader = 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64') } - // ── Discovery ────────────────────────────────────────────────────────────── + // ── Connection ──────────────────────────────────────────────────────────── async connect(): Promise { - if (this.staticBasePath) { - // User supplied an explicit path — verify it works, skip autodiscovery - const result = await this.req('PROPFIND', this.staticBasePath, { Depth: '0' }) - if (result.status !== 207 && result.status !== 200) { - throw new Error( - `CalDAV path "${this.staticBasePath}" on ${this.hostname} returned HTTP ${result.status}. ` + - `Check the CalDAV URL and credentials.` - ) - } - this.basePath = this.staticBasePath - return + const result = await this.ewsReq('GetFolder', ` + + Default + + `) + + if (result.status !== 200) { + const hint = result.status === 401 || result.status === 403 + ? '\nПроверьте логин и пароль.' + : result.status === 404 + ? '\nEWS не найден на сервере. Убедитесь что Exchange доступен по этому адресу.' + : '' + throw new Error(`EWS ${this.hostname} вернул HTTP ${result.status}.${hint}`) } - this.basePath = await this.discoverBasePath() - // discoverBasePath throws on TLS/network errors; returning null means all paths gave 404/403 - if (!this.basePath) { - throw new Error( - `CalDAV not found on ${this.hostname} — all candidate paths returned 404/403.\n` + - `Set the CalDAV path explicitly in account settings (e.g. /EWS/Calendar/).` - ) + if (!result.body.includes('ResponseClass="Success"')) { + const err = result.body.match(/<[mt]:MessageText>([^<]+)<\/[mt]:MessageText>/) + throw new Error(`EWS ошибка: ${err ? err[1] : result.body.slice(0, 300)}`) } + + this.connected = true } - isConnected(): boolean { return this.basePath !== null } + isConnected(): boolean { return this.connected } - private async discoverBasePath(): Promise { - const candidates = [ - '/.well-known/caldav', - '/EWS/Calendar/', - `/EWS/Calendar/${this.username}/`, - '/caldav/', - `/caldav/${this.username}/`, - '/dav/', - ] + // ── Diagnostics ─────────────────────────────────────────────────────────── - // Collect errors so we can surface the most useful one if all paths fail - const errors: string[] = [] + async probePaths(): Promise<{ path: string; status: number; note: string }[]> { + const results: { path: string; status: number; note: string }[] = [] - for (const path of candidates) { - try { - const result = await this.req('PROPFIND', path, { Depth: '0' }) - if (result.status === 207) return path - if (result.status === 301 || result.status === 302) { - const location = result.headers['location'] - if (typeof location === 'string') { - try { return new URL(location, `${this.protocol}://${this.hostname}`).pathname } catch { /* skip */ } - } - } - // Record non-successful status for diagnostics (skip common "not found" ones) - if (result.status !== 404 && result.status !== 403) { - errors.push(`${path} → HTTP ${result.status}`) - } - } catch (err) { - const msg = (err as Error).message ?? String(err) - // TLS errors: surface immediately — retrying other paths won't help - if (isTlsError(msg)) { - throw new Error( - `TLS certificate error connecting to ${this.hostname}: ${msg}\n` + - `Enable "Разрешить самоподписанные сертификаты" in CalDAV settings.` - ) - } - errors.push(`${path} → ${msg}`) - } + // Test EWS endpoint + try { + const r = await this.ewsReq('GetFolder', ` + + Default + + `) + const ok = r.status === 200 && r.body.includes('ResponseClass="Success"') + results.push({ + path: EWS_PATH, + status: r.status, + note: ok ? '✓ EWS работает' : `HTTP ${r.status}` + }) + } catch (err) { + results.push({ path: EWS_PATH, status: 0, note: (err as Error).message }) } - if (errors.length > 0) { - throw new Error( - `CalDAV endpoint not found on ${this.hostname}.\n` + - errors.map((e) => ` • ${e}`).join('\n') + '\n' + - `Set the CalDAV path explicitly in account settings (e.g. /EWS/Calendar/).` - ) + // Test Autodiscover + try { + const ad = await this.tryAutodiscover() + results.push({ + path: '/autodiscover/autodiscover.xml', + status: ad ? 200 : 404, + note: ad ? `✓ EWS URL: ${ad.ewsUrl}` : 'Autodiscover недоступен' + }) + } catch (err) { + results.push({ path: '/autodiscover/autodiscover.xml', status: 0, note: (err as Error).message }) } - return null + return results } - // ── List calendars ───────────────────────────────────────────────────────── + // ── List calendars ──────────────────────────────────────────────────────── async listCalendars(accountId: string): Promise { - if (!this.basePath) throw new Error('CalDAV not connected') - const body = ` - - -` - const result = await this.req('PROPFIND', this.basePath, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) - if (result.status !== 207) { - return [{ id: this.basePath, name: 'Calendar', accountId }] + // Get the main calendar folder's display name + const mainName = await this.ewsGetFolderName('calendar') + + // Get sub-calendars (FindFolder returns children, NOT the parent itself) + const subResult = await this.ewsReq('FindFolder', ` + + Default + + `) + + const calendars: CalendarInfo[] = [ + { id: 'calendar', name: mainName, accountId } + ] + + if (subResult.status === 200) { + const re = /([\s\S]*?)<\/t:CalendarFolder>/g + let m: RegExpExecArray | null + while ((m = re.exec(subResult.body)) !== null) { + const block = m[1] + const idM = block.match(/([^<]+)<\/t:DisplayName>/) + if (idM) calendars.push({ id: idM[1], name: nameM ? nameM[1] : 'Calendar', accountId }) + } } - return extractCalendars(result.body, this.basePath).map((c) => ({ - id: c.href, name: c.displayName || 'Calendar', accountId - })) + + return calendars } - // ── Fetch events ─────────────────────────────────────────────────────────── + // ── List events ─────────────────────────────────────────────────────────── async listEvents(accountId: string, calendarId: string, start: Date, end: Date): Promise { - const body = ` - - - - - - - - - -` + const startStr = start.toISOString().slice(0, 19) + 'Z' + const endStr = end.toISOString().slice(0, 19) + 'Z' + const folderEl = calendarId === 'calendar' + ? `` + : `` - const result = await this.req('REPORT', calendarId, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) - if (result.status !== 207) return this.fetchAllAndFilter(accountId, calendarId, start, end) - return this.parseMultistatus(result.body, accountId, calendarId) + const result = await this.ewsReq('FindItem', ` + + + IdOnly + + + + + + + + + + + + + ${folderEl} + `) + + if (result.status !== 200) return [] + return this.parseEwsEvents(result.body, accountId, calendarId) } - private async fetchAllAndFilter(accountId: string, calendarId: string, start: Date, end: Date): Promise { - const body = ` - - - -` - const result = await this.req('REPORT', calendarId, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) - if (result.status !== 207) return [] - return this.parseMultistatus(result.body, accountId, calendarId).filter((ev) => - new Date(ev.start) < end && new Date(ev.end) > start - ) + // ── EWS helpers ─────────────────────────────────────────────────────────── + + private ewsReq(action: string, soapBody: string): Promise { + const full = ` + + + ${soapBody} +` + return this.req('POST', EWS_PATH, { + 'Content-Type': 'text/xml; charset=utf-8', + 'SOAPAction': `"http://schemas.microsoft.com/exchange/services/2006/messages/${action}"` + }, full) } - private parseMultistatus(xml: string, accountId: string, calendarId: string): CalendarEvent[] { - const events: CalendarEvent[] = [] - for (const block of extractCalendarData(xml)) { - for (const rv of parseVEvents(block)) { - if (!rv.dtstart) continue - const { date: startDate, isAllDay } = parseICalDate(rv.dtstart, rv.dtStartParams) - let endDate: Date - if (rv.dtend) endDate = parseICalDate(rv.dtend, rv.dtEndParams).date - else { endDate = new Date(startDate); if (isAllDay) endDate.setUTCDate(endDate.getUTCDate() + 1); else endDate.setTime(endDate.getTime() + 3_600_000) } - events.push({ - id: `${calendarId}::${rv.uid || startDate.toISOString()}`, - uid: rv.uid, calendarId, accountId, - title: rv.summary || '(no title)', - start: startDate.toISOString(), end: endDate.toISOString(), isAllDay, - location: rv.location || undefined, description: rv.description || undefined, - organizer: rv.organizer || undefined, attendees: rv.attendees, - status: (rv.status as CalendarEvent['status']) || 'confirmed' - }) + private async ewsGetFolderName(distinguishedId: string): Promise { + try { + const result = await this.ewsReq('GetFolder', ` + + Default + + `) + if (result.status === 200) { + const m = result.body.match(/([^<]+)<\/t:DisplayName>/) + if (m) return m[1] } + } catch { /* fall through */ } + return distinguishedId === 'calendar' ? 'Календарь' : distinguishedId + } + + private parseEwsEvents(xml: string, accountId: string, calendarId: string): CalendarEvent[] { + const events: CalendarEvent[] = [] + const re = /([\s\S]*?)<\/t:CalendarItem>/g + let m: RegExpExecArray | null + while ((m = re.exec(xml)) !== null) { + const block = m[1] + const get = (tag: string): string => { + const r = block.match(new RegExp(`]*)?>([\\s\\S]*?)<\\/t:${tag}>`)) + return r ? r[1].replace(/<[^>]+>/g, '').trim() : '' + } + const idM = block.match(/[\s\S]*?([^<]+)<\/t:EmailAddress>/) + events.push({ + id: `ews::${idM[1]}`, + uid: idM[1], + calendarId, + accountId, + title: get('Subject') || '(без темы)', + start: start.toISOString(), + end: end.toISOString(), + isAllDay, + location: get('Location') || undefined, + description: get('Body') || undefined, + organizer: organizerM ? organizerM[1] : undefined, + attendees: [], + status: fbStatus === 'tentative' ? 'tentative' : 'confirmed' + }) } return events } + private async tryAutodiscover(): Promise<{ ewsUrl: string } | null> { + const body = ` + + + ${this.email} + http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a + +` + const headers = { 'Content-Type': 'text/xml; charset=utf-8' } + for (const path of ['/autodiscover/autodiscover.xml', '/Autodiscover/Autodiscover.xml']) { + try { + const result = await this.req('POST', path, headers, body) + if (result.status === 200) { + const m = result.body.match(/([^<]+)<\/EwsUrl>/i) + if (m) return { ewsUrl: m[1].trim() } + } + } catch { /* try next */ } + } + return null + } + // ── Authenticated HTTP request ───────────────────────────────────────────── - // - // Strategy: - // 1. Try with Basic auth (or NTLM if already detected). - // 2. If server replies 401 with WWW-Authenticate containing "NTLM", - // switch to NTLM and retry. private async req( method: string, @@ -397,11 +332,9 @@ export class CalDavProvider { return this.reqNtlm(method, path, extraHeaders, body) } - // Try Basic first const result = await this.rawReq(method, path, { Authorization: this.basicAuthHeader, ...extraHeaders }, body) if (result.status === 401 && this.needsNtlm(result.headers)) { - // Server requires NTLM — switch mode and retry this.authMode = 'ntlm' return this.reqNtlm(method, path, extraHeaders, body) } @@ -410,12 +343,8 @@ export class CalDavProvider { } /** - * Execute a full NTLMv2 3-way handshake and return the authenticated response. - * - * Both the Negotiate (Type 1) and Authenticate (Type 3) requests MUST use the - * same TCP connection. We achieve this by creating a fresh keepAlive Agent with - * maxSockets:1 for each operation — the first socket created is reused for the - * second request automatically. + * NTLMv2 3-way handshake. Both Type 1 and Type 3 must use the same TCP + * connection — achieved with a fresh keepAlive Agent (maxSockets: 1). */ private async reqNtlm( method: string, @@ -429,7 +358,6 @@ export class CalDavProvider { : new http.Agent({ keepAlive: true, maxSockets: 1 }) try { - // Step 1: Type 1 Negotiate (no body, just the method + NTLM negotiate header) const type1Result = await this.rawReq( method, path, { Authorization: buildNegotiateHeader(), ...extraHeaders }, @@ -437,25 +365,20 @@ export class CalDavProvider { agent ) - // Step 2: Extract Type 2 Challenge from 401 response const wwwAuth = this.extractNtlmChallenge(type1Result.headers) - if (!wwwAuth) { - // Server accepted Type 1 without a challenge (unusual) — return as-is - return type1Result - } + if (!wwwAuth) return type1Result - const { challenge, targetInfo } = parseChallenge(wwwAuth) - const { user, domain } = splitUser(this.username) + const { challenge, targetInfo, targetName } = parseChallenge(wwwAuth) + const { user, domain: explicitDomain } = splitUser(this.username) + const domain = explicitDomain || targetName const type3Header = buildAuthenticateHeader(user, domain, this.password, challenge, targetInfo) - // Step 3: Type 3 Authenticate with actual request body - const finalResult = await this.rawReq( + return await this.rawReq( method, path, { Authorization: type3Header, ...extraHeaders }, body, agent ) - return finalResult } finally { agent.destroy() } @@ -468,10 +391,7 @@ export class CalDavProvider { body?: string, agent?: https.Agent | http.Agent ): Promise { - const allHeaders: Record = { - 'User-Agent': 'AeroMail/1.0', - ...headers - } + const allHeaders: Record = { 'User-Agent': 'AeroMail/1.0', ...headers } if (body) allHeaders['Content-Length'] = Buffer.byteLength(body, 'utf8').toString() return rawRequest({ @@ -487,29 +407,15 @@ export class CalDavProvider { }) } - /** Returns the NTLM challenge header value, or null if the response doesn't contain one. */ private extractNtlmChallenge(headers: IncomingMessage['headers']): string | null { const auth = headers['www-authenticate'] const list = Array.isArray(auth) ? auth : typeof auth === 'string' ? auth.split(',') : [] - const ntlmHeader = list.map((s) => s.trim()).find((s) => /^NTLM\s+/i.test(s)) - return ntlmHeader ?? null + return list.map((s) => s.trim()).find((s) => /^NTLM\s+/i.test(s)) ?? null } - /** Returns true if a 401 response is asking for NTLM/Negotiate. */ private needsNtlm(headers: IncomingMessage['headers']): boolean { const auth = headers['www-authenticate'] const s = Array.isArray(auth) ? auth.join(',') : auth ?? '' return /NTLM|Negotiate/i.test(s) } } - -// ── Utility ──────────────────────────────────────────────────────────────────── - -function isTlsError(msg: string): boolean { - return /self.signed|UNABLE_TO_VERIFY|CERT_|certificate|SSL|TLS/i.test(msg) -} - -function toUtcString(d: Date): string { - const p = (n: number) => String(n).padStart(2, '0') - return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z` -} diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index b86d602..0878702 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -226,6 +226,27 @@ export class AccountManager { return provider.listEvents(accountId, calendarId, start, end) } + async probeCalendarPaths(accountId: string): Promise<{ path: string; status: number; note: string }[]> { + // Create a fresh provider (no cached state) and probe without connecting + const accounts = this.store.get('accounts', []) + const accMeta = accounts.find((a) => a.id === accountId) + if (!accMeta) throw new Error(`Account ${accountId} not found`) + + const credRaw = this.credentialStore.get(accountId) + if (!credRaw) throw new Error(`Credentials for ${accountId} not found`) + + let credentials: AccountConfig['credentials'] + try { + credentials = JSON.parse(credRaw) + } catch { + throw new Error('Corrupted credentials') + } + + const config: AccountConfig = { ...accMeta, credentials } + const provider = new CalDavProvider(config) + return provider.probePaths() + } + private async getOrCreateCalendarProvider(accountId: string): Promise { const existing = this.calendarProviders.get(accountId) if (existing?.isConnected()) return existing diff --git a/src/renderer/src/views/CalendarView.vue b/src/renderer/src/views/CalendarView.vue index 5a2104c..bd45706 100644 --- a/src/renderer/src/views/CalendarView.vue +++ b/src/renderer/src/views/CalendarView.vue @@ -1,5 +1,5 @@