/** * 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 body?: string allowSelfSigned?: boolean agent?: https.Agent | http.Agent } interface RequestResult { status: number headers: IncomingMessage['headers'] body: string } function rawRequest(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, 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 { 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}`) } 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', ` 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 }) } // 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 { // 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 calendars } // ── List events ─────────────────────────────────────────────────────────── async listEvents(accountId: string, calendarId: string, start: Date, end: Date): Promise { const startStr = start.toISOString().slice(0, 19) + 'Z' const endStr = end.toISOString().slice(0, 19) + 'Z' const folderEl = calendarId === 'calendar' ? `` : `` const result = await this.ewsReq('FindItem', ` IdOnly ${folderEl} `) 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 { 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 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 static parseEwsBody(block: string): string | undefined { const r = block.match(/]*))?>([\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 { const eventMap = new Map() for (const e of events) eventMap.set(e.uid, e) const idsXml = events.map((e) => ``).join('\n ') const result = await this.ewsReq('GetItem', ` IdOnly ${idsXml} `) if (result.status !== 200) return const responseRe = /([\s\S]*?)<\/m:Items>/g let rm: RegExpExecArray | null while ((rm = responseRe.exec(result.body)) !== null) { const itemBlock = rm[1] const idM = itemBlock.match(/([\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>/) const emailM = ab.match(/([^<]+)<\/t:EmailAddress>/) const rtM = ab.match(/([^<]+)<\/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(/([\s\S]*?)<\/t:RequiredAttendees>/) const opt = block.match(/([\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 = /([\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:Organizer>/) const orgName = orgBlock ? (orgBlock[1].match(/([^<]+)<\/t:Name>/) ?? [])[1]?.trim() : undefined const orgEmailRaw = orgBlock ? (orgBlock[1].match(/([^<]+)<\/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 = ` ${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 ───────────────────────────────────────────── private async req( method: string, path: string, extraHeaders: Record = {}, body?: string ): Promise { 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 = {}, 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 { 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, 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: 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) } }