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 @@