feat: replace CalDAV with EWS SOAP for Exchange calendar
- 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 <noreply@anthropic.com>
This commit is contained in:
parent
d47b30bbb0
commit
f130823c7c
6 changed files with 346 additions and 311 deletions
|
|
@ -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)
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 }. */
|
||||
|
|
|
|||
|
|
@ -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<RequestResult> {
|
|||
})
|
||||
}
|
||||
)
|
||||
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<string, Array<{ value: string; params: string }>> = {}
|
||||
|
||||
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<void> {
|
||||
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', `
|
||||
<m:GetFolder>
|
||||
<m:FolderShape><t:BaseShape>Default</t:BaseShape></m:FolderShape>
|
||||
<m:FolderIds><t:DistinguishedFolderId Id="calendar"/></m:FolderIds>
|
||||
</m:GetFolder>`)
|
||||
|
||||
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<string | null> {
|
||||
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', `
|
||||
<m:GetFolder>
|
||||
<m:FolderShape><t:BaseShape>Default</t:BaseShape></m:FolderShape>
|
||||
<m:FolderIds><t:DistinguishedFolderId Id="calendar"/></m:FolderIds>
|
||||
</m:GetFolder>`)
|
||||
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<CalendarInfo[]> {
|
||||
if (!this.basePath) throw new Error('CalDAV not connected')
|
||||
const body = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<D:propfind xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:prop><D:resourcetype/><D:displayname/></D:prop>
|
||||
</D:propfind>`
|
||||
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', `
|
||||
<m:FindFolder Traversal="Shallow">
|
||||
<m:FolderShape><t:BaseShape>Default</t:BaseShape></m:FolderShape>
|
||||
<m:ParentFolderIds><t:DistinguishedFolderId Id="calendar"/></m:ParentFolderIds>
|
||||
</m:FindFolder>`)
|
||||
|
||||
const calendars: CalendarInfo[] = [
|
||||
{ id: 'calendar', name: mainName, accountId }
|
||||
]
|
||||
|
||||
if (subResult.status === 200) {
|
||||
const re = /<t:CalendarFolder>([\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:FolderId\s+Id="([^"]+)"/)
|
||||
const nameM = block.match(/<t:DisplayName>([^<]+)<\/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<CalendarEvent[]> {
|
||||
const body = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:prop><D:getetag/><C:calendar-data/></D:prop>
|
||||
<C:filter>
|
||||
<C:comp-filter name="VCALENDAR">
|
||||
<C:comp-filter name="VEVENT">
|
||||
<C:time-range start="${toUtcString(start)}" end="${toUtcString(end)}"/>
|
||||
</C:comp-filter>
|
||||
</C:comp-filter>
|
||||
</C:filter>
|
||||
</C:calendar-query>`
|
||||
const startStr = start.toISOString().slice(0, 19) + 'Z'
|
||||
const endStr = end.toISOString().slice(0, 19) + 'Z'
|
||||
const folderEl = calendarId === 'calendar'
|
||||
? `<t:DistinguishedFolderId Id="calendar"/>`
|
||||
: `<t:FolderId Id="${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)
|
||||
const result = await this.ewsReq('FindItem', `
|
||||
<m:FindItem Traversal="Shallow">
|
||||
<m:ItemShape>
|
||||
<t:BaseShape>IdOnly</t:BaseShape>
|
||||
<t:AdditionalProperties>
|
||||
<t:FieldURI FieldURI="item:Subject"/>
|
||||
<t:FieldURI FieldURI="item:Body"/>
|
||||
<t:FieldURI FieldURI="calendar:Start"/>
|
||||
<t:FieldURI FieldURI="calendar:End"/>
|
||||
<t:FieldURI FieldURI="calendar:Location"/>
|
||||
<t:FieldURI FieldURI="calendar:IsAllDayEvent"/>
|
||||
<t:FieldURI FieldURI="calendar:LegacyFreeBusyStatus"/>
|
||||
<t:FieldURI FieldURI="calendar:Organizer"/>
|
||||
</t:AdditionalProperties>
|
||||
</m:ItemShape>
|
||||
<m:CalendarView MaxReturnsPerPage="500" StartDate="${startStr}" EndDate="${endStr}"/>
|
||||
<m:ParentFolderIds>${folderEl}</m:ParentFolderIds>
|
||||
</m:FindItem>`)
|
||||
|
||||
if (result.status !== 200) return []
|
||||
return this.parseEwsEvents(result.body, accountId, calendarId)
|
||||
}
|
||||
|
||||
private async fetchAllAndFilter(accountId: string, calendarId: string, start: Date, end: Date): Promise<CalendarEvent[]> {
|
||||
const body = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:prop><D:getetag/><C:calendar-data/></D:prop>
|
||||
<C:filter><C:comp-filter name="VCALENDAR"><C:comp-filter name="VEVENT"/></C:comp-filter></C:filter>
|
||||
</C:calendar-query>`
|
||||
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<RequestResult> {
|
||||
const full = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
|
||||
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
|
||||
<soap:Header><t:RequestServerVersion Version="Exchange2013"/></soap:Header>
|
||||
<soap:Body>${soapBody}</soap:Body>
|
||||
</soap:Envelope>`
|
||||
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<string> {
|
||||
try {
|
||||
const result = await this.ewsReq('GetFolder', `
|
||||
<m:GetFolder>
|
||||
<m:FolderShape><t:BaseShape>Default</t:BaseShape></m:FolderShape>
|
||||
<m:FolderIds><t:DistinguishedFolderId Id="${distinguishedId}"/></m:FolderIds>
|
||||
</m:GetFolder>`)
|
||||
if (result.status === 200) {
|
||||
const m = result.body.match(/<t:DisplayName>([^<]+)<\/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 = /<t:CalendarItem>([\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(`<t:${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/t:${tag}>`))
|
||||
return r ? r[1].replace(/<[^>]+>/g, '').trim() : ''
|
||||
}
|
||||
const idM = block.match(/<t:ItemId\s+Id="([^"]+)"/)
|
||||
if (!idM) continue
|
||||
const startStr = get('Start')
|
||||
if (!startStr) continue
|
||||
const start = new Date(startStr)
|
||||
const endStr = get('End')
|
||||
const end = endStr ? new Date(endStr) : new Date(start.getTime() + 3_600_000)
|
||||
const isAllDay = get('IsAllDayEvent') === 'true'
|
||||
const fbStatus = get('LegacyFreeBusyStatus').toLowerCase()
|
||||
const organizerM = block.match(/<t:Organizer>[\s\S]*?<t:EmailAddress>([^<]+)<\/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 = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
|
||||
<Request>
|
||||
<EMailAddress>${this.email}</EMailAddress>
|
||||
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
|
||||
</Request>
|
||||
</Autodiscover>`
|
||||
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>([^<]+)<\/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<RequestResult> {
|
||||
const allHeaders: Record<string, string> = {
|
||||
'User-Agent': 'AeroMail/1.0',
|
||||
...headers
|
||||
}
|
||||
const allHeaders: Record<string, string> = { '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`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<CalDavProvider> {
|
||||
const existing = this.calendarProviders.get(accountId)
|
||||
if (existing?.isConnected()) return existing
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
<script setup lang="ts">
|
||||
import { onMounted, watch } from 'vue'
|
||||
import { onMounted, watch, ref } from 'vue'
|
||||
import { format } from 'date-fns'
|
||||
import { ru } from 'date-fns/locale'
|
||||
import { useCalendarStore } from '../stores/calendar.store'
|
||||
|
|
@ -11,12 +11,28 @@ import AddAccountDialog from '../components/accounts/AddAccountDialog.vue'
|
|||
import NotificationContainer from '../components/notifications/NotificationContainer.vue'
|
||||
import AppIcon from '../components/AppIcon.vue'
|
||||
import type { CalendarEvent } from '@shared/types/calendar'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const calStore = useCalendarStore()
|
||||
const accountsStore = useAccountsStore()
|
||||
const showAddAccount = ref(false)
|
||||
|
||||
// CalDAV path probe
|
||||
const probeResults = ref<{ path: string; status: number; note: string }[] | null>(null)
|
||||
const probing = ref(false)
|
||||
|
||||
async function probeCalDAV(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId) return
|
||||
probing.value = true
|
||||
probeResults.value = null
|
||||
try {
|
||||
probeResults.value = await window.api.invoke('calendar:probe', { accountId: accountsStore.activeAccountId })
|
||||
} catch (e) {
|
||||
probeResults.value = [{ path: '(error)', status: 0, note: (e as Error).message }]
|
||||
} finally {
|
||||
probing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Calendar color palette, same as WeekView
|
||||
const CAL_COLORS = ['#a8e600', '#38bdf8', '#a78bfa', '#f472b6', '#fb923c', '#4ade80', '#f87171']
|
||||
function calendarColor(calendarId: string): string {
|
||||
|
|
@ -65,8 +81,26 @@ function handleEventClick(ev: CalendarEvent): void {
|
|||
<div v-if="calStore.error" class="sidebar-error">
|
||||
<p class="error-title">CalDAV недоступен</p>
|
||||
<p class="error-detail">{{ calStore.error }}</p>
|
||||
<p class="error-hint">Убедитесь что Exchange 2013+ с поддержкой CalDAV доступен на том же хосте что и IMAP.</p>
|
||||
|
||||
<button class="retry-btn" @click="reload">Повторить</button>
|
||||
<button class="retry-btn probe-btn" :disabled="probing" @click="probeCalDAV">
|
||||
{{ probing ? 'Сканирование…' : 'Найти CalDAV путь' }}
|
||||
</button>
|
||||
|
||||
<!-- Probe results -->
|
||||
<div v-if="probeResults" class="probe-results">
|
||||
<p class="probe-title">Результаты сканирования:</p>
|
||||
<div
|
||||
v-for="r in probeResults"
|
||||
:key="r.path"
|
||||
class="probe-row"
|
||||
:class="{ 'probe-ok': r.status === 207 || r.status === 200 }"
|
||||
>
|
||||
<span class="probe-path">{{ r.path }}</span>
|
||||
<span class="probe-note">{{ r.note }}</span>
|
||||
</div>
|
||||
<p class="probe-hint">Скопируйте путь со статусом 207 в настройки CalDAV → «Путь».</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Calendar list -->
|
||||
|
|
@ -308,11 +342,6 @@ function handleEventClick(ev: CalendarEvent): void {
|
|||
cursor: text;
|
||||
}
|
||||
|
||||
.error-hint {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.retry-btn {
|
||||
align-self: flex-start;
|
||||
|
|
@ -324,7 +353,66 @@ function handleEventClick(ev: CalendarEvent): void {
|
|||
color: var(--text-secondary);
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
.retry-btn:hover { background: var(--glass-bg-hover); }
|
||||
.retry-btn:hover:not(:disabled) { background: var(--glass-bg-hover); }
|
||||
.retry-btn:disabled { opacity: 0.5; cursor: default; }
|
||||
|
||||
.probe-btn { margin-top: 2px; }
|
||||
|
||||
.probe-results {
|
||||
margin-top: 6px;
|
||||
border-top: 1px solid var(--glass-border);
|
||||
padding-top: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.probe-title {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.probe-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
padding: 3px 6px;
|
||||
border-radius: 5px;
|
||||
background: rgba(255,255,255,0.03);
|
||||
}
|
||||
|
||||
.probe-row.probe-ok {
|
||||
background: rgba(168, 230, 0, 0.08);
|
||||
}
|
||||
|
||||
.probe-path {
|
||||
font-size: 10px;
|
||||
font-family: monospace;
|
||||
color: var(--text-primary);
|
||||
word-break: break-all;
|
||||
user-select: text;
|
||||
-webkit-user-select: text;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.probe-note {
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.probe-row.probe-ok .probe-note {
|
||||
color: #a8e600;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.probe-hint {
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.5;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.sidebar-loading {
|
||||
flex: 1;
|
||||
|
|
|
|||
|
|
@ -54,6 +54,10 @@ export interface IpcChannelMap {
|
|||
{ accountId: string; calendarId: string; start: string; end: string },
|
||||
CalendarEvent[]
|
||||
]
|
||||
'calendar:probe': [
|
||||
{ accountId: string },
|
||||
{ path: string; status: number; note: string }[]
|
||||
]
|
||||
}
|
||||
|
||||
export interface IpcEventMap {
|
||||
|
|
|
|||
Loading…
Reference in a new issue