aero-mail/src/main/providers/caldav.provider.ts
d.a.kolesov 2c1a5439e8
All checks were successful
Release / release (push) Successful in 3m16s
html -> md
2026-11-11 15:14:40 +07:00

535 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Exchange calendar provider via EWS (Exchange Web Services) SOAP API.
*
* Uses only Node.js built-in `https`/`http` — no extra npm deps.
* Auth: tries HTTP Basic first; if server demands NTLM, falls back to NTLMv2.
* EWS endpoint: POST /EWS/Exchange.asmx
*/
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, AttendeeInfo, AttendeeStatus } from '@shared/types/calendar'
import { ewsBodyToMarkdown } from '../lib/html-to-markdown'
import {
buildNegotiateHeader,
parseChallenge,
buildAuthenticateHeader,
splitUser
} from '../lib/ntlm'
// ── HTTP helper ────────────────────────────────────────────────────────────────
interface RequestOptions {
protocol: 'https' | 'http'
hostname: string
port: number
path: string
method: string
headers: Record<string, string>
body?: string
allowSelfSigned?: boolean
agent?: https.Agent | http.Agent
}
interface RequestResult {
status: number
headers: IncomingMessage['headers']
body: string
}
function rawRequest(opts: RequestOptions): Promise<RequestResult> {
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,
agent: opts.agent
},
(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('Request timed out')) })
req.on('error', reject)
if (opts.body) req.write(opts.body)
req.end()
})
}
// ── 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 authMode: AuthMode = 'basic'
private connected = false
constructor(config: AccountConfig) {
const creds = config.credentials as ImapCredentials
const calSecure = creds.caldavSecure ?? creds.secure
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
this.allowSelfSigned = creds.caldavAllowSelfSigned ?? creds.smtpAllowSelfSigned ?? false
this.basicAuthHeader = 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64')
}
// ── Connection ────────────────────────────────────────────────────────────
async connect(): Promise<void> {
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}`)
}
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.connected }
// ── Diagnostics ───────────────────────────────────────────────────────────
async probePaths(): Promise<{ path: string; status: number; note: string }[]> {
const results: { path: string; status: number; note: string }[] = []
// 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 })
}
// 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 results
}
// ── List calendars ────────────────────────────────────────────────────────
async listCalendars(accountId: string): Promise<CalendarInfo[]> {
// 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 calendars
}
// ── List events ───────────────────────────────────────────────────────────
async listEvents(accountId: string, calendarId: string, start: Date, end: Date): Promise<CalendarEvent[]> {
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.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 []
const events = this.parseEwsEvents(result.body, accountId, calendarId)
if (events.length > 0) {
try { await this.enrichWithAttendees(events) } catch { /* non-fatal */ }
}
return events
}
// ── 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 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 static parseEwsBody(block: string): string | undefined {
const r = block.match(/<t:Body(?:\s([^>]*))?>([\s\S]*?)<\/t:Body>/)
if (!r) return undefined
const bodyType = r[1]?.match(/BodyType="([^"]+)"/)?.[1]
return ewsBodyToMarkdown(r[2], bodyType) || undefined
}
private async enrichWithAttendees(events: CalendarEvent[]): Promise<void> {
const eventMap = new Map<string, CalendarEvent>()
for (const e of events) eventMap.set(e.uid, e)
const idsXml = events.map((e) => `<t:ItemId Id="${e.uid}"/>`).join('\n ')
const result = await this.ewsReq('GetItem', `
<m:GetItem>
<m:ItemShape>
<t:BaseShape>IdOnly</t:BaseShape>
<t:AdditionalProperties>
<t:FieldURI FieldURI="item:Body"/>
<t:FieldURI FieldURI="calendar:RequiredAttendees"/>
<t:FieldURI FieldURI="calendar:OptionalAttendees"/>
</t:AdditionalProperties>
</m:ItemShape>
<m:ItemIds>${idsXml}</m:ItemIds>
</m:GetItem>`)
if (result.status !== 200) return
const responseRe = /<m:Items>([\s\S]*?)<\/m:Items>/g
let rm: RegExpExecArray | null
while ((rm = responseRe.exec(result.body)) !== null) {
const itemBlock = rm[1]
const idM = itemBlock.match(/<t:ItemId\s+Id="([^"]+)"/)
const target = idM ? eventMap.get(idM[1]) : undefined
if (target) {
target.attendees = this.parseAttendeesList(itemBlock)
if (!target.description) {
target.description = CalDavProvider.parseEwsBody(itemBlock)
}
}
}
}
private static smtpEmail(raw: string): string | undefined {
const s = raw.replace(/^smtp:/i, '').trim()
return s.includes('@') ? s : undefined
}
private static parseRt(rt: string): AttendeeStatus {
switch (rt.toLowerCase()) {
case 'accept': return 'accepted'
case 'decline': return 'declined'
case 'tentative': return 'tentative'
default: return 'unknown'
}
}
private parseAttendeeSection(xml: string, required: boolean): AttendeeInfo[] {
const result: AttendeeInfo[] = []
const re = /<t:Attendee>([\s\S]*?)<\/t:Attendee>/g
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null) {
const ab = m[1]
const nameM = ab.match(/<t:Name>([^<]+)<\/t:Name>/)
const emailM = ab.match(/<t:EmailAddress>([^<]+)<\/t:EmailAddress>/)
const rtM = ab.match(/<t:ResponseType>([^<]+)<\/t:ResponseType>/)
const email = emailM ? CalDavProvider.smtpEmail(emailM[1]) : undefined
const name = nameM ? nameM[1].trim() : undefined
if (!name && !email) continue
result.push({
name: name ?? email!,
email: email ?? '',
required,
status: rtM ? CalDavProvider.parseRt(rtM[1]) : 'unknown',
})
}
return result
}
private parseAttendeesList(block: string): AttendeeInfo[] {
const req = block.match(/<t:RequiredAttendees>([\s\S]*?)<\/t:RequiredAttendees>/)
const opt = block.match(/<t:OptionalAttendees>([\s\S]*?)<\/t:OptionalAttendees>/)
return [
...(req ? this.parseAttendeeSection(req[1], true) : []),
...(opt ? this.parseAttendeeSection(opt[1], false) : []),
]
}
/** Ближайшая локальная полночь: покрывает сдвиг часового пояса до ±12 ч. */
private static roundToLocalMidnight(date: Date): Date {
const shifted = new Date(date.getTime() + 12 * 3_600_000)
return new Date(shifted.getFullYear(), shifted.getMonth(), shifted.getDate())
}
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 isAllDay = get('IsAllDayEvent') === 'true'
const endStr = get('End')
let start = new Date(startStr)
let end = endStr ? new Date(endStr) : new Date(start.getTime() + 3_600_000)
if (isAllDay) {
// EWS отдаёт границы all-day в полночь часового пояса организатора (часто UTC),
// поэтому в локальном времени они «съезжают» на соседний день
start = CalDavProvider.roundToLocalMidnight(start)
end = CalDavProvider.roundToLocalMidnight(end)
if (end <= start) end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1)
}
const fbStatus = get('LegacyFreeBusyStatus').toLowerCase()
const orgBlock = block.match(/<t:Organizer>([\s\S]*?)<\/t:Organizer>/)
const orgName = orgBlock ? (orgBlock[1].match(/<t:Name>([^<]+)<\/t:Name>/) ?? [])[1]?.trim() : undefined
const orgEmailRaw = orgBlock ? (orgBlock[1].match(/<t:EmailAddress>([^<]+)<\/t:EmailAddress>/) ?? [])[1]?.trim() : undefined
// Exchange sometimes returns X500/routing addresses — keep only SMTP emails
const orgEmail = orgEmailRaw?.replace(/^smtp:/i, '').includes('@')
? orgEmailRaw.replace(/^smtp:/i, '').trim()
: undefined
const organizer = orgName && orgEmail
? `${orgName} <${orgEmail}>`
: orgName ?? orgEmail
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: CalDavProvider.parseEwsBody(block),
organizer,
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 ─────────────────────────────────────────────
private async req(
method: string,
path: string,
extraHeaders: Record<string, string> = {},
body?: string
): Promise<RequestResult> {
if (this.authMode === 'ntlm') {
return this.reqNtlm(method, path, extraHeaders, body)
}
const result = await this.rawReq(method, path, { Authorization: this.basicAuthHeader, ...extraHeaders }, body)
if (result.status === 401 && this.needsNtlm(result.headers)) {
this.authMode = 'ntlm'
return this.reqNtlm(method, path, extraHeaders, body)
}
return result
}
/**
* 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,
path: string,
extraHeaders: Record<string, string> = {},
body?: string
): Promise<RequestResult> {
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 {
const type1Result = await this.rawReq(
method, path,
{ Authorization: buildNegotiateHeader(), ...extraHeaders },
undefined,
agent
)
const wwwAuth = this.extractNtlmChallenge(type1Result.headers)
if (!wwwAuth) return type1Result
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)
return await this.rawReq(
method, path,
{ Authorization: type3Header, ...extraHeaders },
body,
agent
)
} finally {
agent.destroy()
}
}
private rawReq(
method: string,
path: string,
headers: Record<string, string>,
body?: string,
agent?: https.Agent | http.Agent
): Promise<RequestResult> {
const allHeaders: Record<string, string> = { '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: allHeaders,
body,
allowSelfSigned: this.allowSelfSigned,
agent
})
}
private extractNtlmChallenge(headers: IncomingMessage['headers']): string | null {
const auth = headers['www-authenticate']
const list = Array.isArray(auth) ? auth : typeof auth === 'string' ? auth.split(',') : []
return list.map((s) => s.trim()).find((s) => /^NTLM\s+/i.test(s)) ?? null
}
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)
}
}