From adbf8b8e49525604aadb1d88435d788696822a9f Mon Sep 17 00:00:00 2001 From: Aero Mail Dev Date: Thu, 16 Apr 2026 03:03:48 +0000 Subject: [PATCH] fix: add NTLMv2 authentication for corporate Exchange CalDAV Exchange servers with Basic auth disabled return 401 WWW-Authenticate:NTLM/Negotiate. Added pure-JS NTLMv2 implementation (no new deps) and auto-detection in CalDavProvider. - src/main/lib/ntlm.ts: MD4 (avoids OpenSSL 3.x legacy issues), Type1/Type2/Type3 message builder for NTLMv2 (HMAC-MD5 + NTProofStr + blob with server challenge) - CalDavProvider.req(): tries Basic first; on 401+NTLM header auto-switches to NTLM mode - CalDavProvider.reqNtlm(): 3-way handshake on a dedicated keepAlive/maxSockets:1 agent to guarantee both Negotiate and Authenticate use the same TCP connection Co-Authored-By: Claude Sonnet 4.6 --- src/main/lib/ntlm.ts | 207 ++++++++++++ src/main/providers/caldav.provider.ts | 467 +++++++++++--------------- 2 files changed, 408 insertions(+), 266 deletions(-) create mode 100644 src/main/lib/ntlm.ts diff --git a/src/main/lib/ntlm.ts b/src/main/lib/ntlm.ts new file mode 100644 index 0000000..405dd3f --- /dev/null +++ b/src/main/lib/ntlm.ts @@ -0,0 +1,207 @@ +/** + * NTLM (NTLMv2) authentication for HTTP — MS-NLMP spec. + * Pure Node.js crypto, no external deps. + * + * Flow over HTTP: + * Client → Server: method + Authorization: NTLM + * Server → Client: 401 + WWW-Authenticate: NTLM + * Client → Server: method + Authorization: NTLM + actual body + * Server → Client: 207 / 200 + * + * All three round-trips MUST use the same TCP connection (keepAlive agent). + */ + +import crypto from 'node:crypto' + +// ── MD4 (pure JS) ───────────────────────────────────────────────────────────── +// Needed for NT hash: MD4(UTF-16LE(password)). +// Node.js 20+ / OpenSSL 3.x moved MD4 to the legacy provider, so we +// implement it ourselves to avoid any availability issues. + +function md4(buf: Buffer): Buffer { + const F = (x: number, y: number, z: number) => (x & y) | (~x & z) + const G = (x: number, y: number, z: number) => (x & y) | (x & z) | (y & z) + const H = (x: number, y: number, z: number) => x ^ y ^ z + const add = (a: number, b: number) => (a + b) >>> 0 + const rol = (x: number, n: number) => ((x << n) | (x >>> (32 - n))) >>> 0 + + const l = buf.length + const extra = ((56 - l - 1) % 64 + 64) % 64 + const padded = Buffer.alloc(l + 1 + extra + 8) + buf.copy(padded) + padded[l] = 0x80 + const bitLen = l * 8 + padded.writeUInt32LE(bitLen >>> 0, padded.length - 8) + padded.writeUInt32LE(Math.floor(bitLen / 2 ** 32), padded.length - 4) + + let a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476 + + for (let off = 0; off < padded.length; off += 64) { + const X = Array.from({ length: 16 }, (_, i) => padded.readUInt32LE(off + i * 4)) + let [A, B, C, D] = [a, b, c, d] + + // Round 1: F, shifts 3,7,11,19, word order 0..15 + for (let i = 0; i < 16; i++) { + A = rol(add(add(A, F(B, C, D)), X[i]), [3, 7, 11, 19][i & 3]) + ;[A, B, C, D] = [D, A, B, C] + } + // Round 2: G, shifts 3,5,9,13, word order 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 + const r2 = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15] + for (let i = 0; i < 16; i++) { + A = rol(add(add(add(A, G(B, C, D)), X[r2[i]]), 0x5a827999), [3, 5, 9, 13][i & 3]) + ;[A, B, C, D] = [D, A, B, C] + } + // Round 3: H, shifts 3,9,11,15, word order 0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15 + const r3 = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] + for (let i = 0; i < 16; i++) { + A = rol(add(add(add(A, H(B, C, D)), X[r3[i]]), 0x6ed9eba1), [3, 9, 11, 15][i & 3]) + ;[A, B, C, D] = [D, A, B, C] + } + + a = add(a, A); b = add(b, B); c = add(c, C); d = add(d, D) + } + + const out = Buffer.alloc(16) + out.writeUInt32LE(a, 0); out.writeUInt32LE(b, 4) + out.writeUInt32LE(c, 8); out.writeUInt32LE(d, 12) + return out +} + +// ── NTLM message builder ─────────────────────────────────────────────────────── + +const NTLMSSP_SIG = Buffer.from('NTLMSSP\0', 'ascii') + +// Negotiate flags for NTLMv2 +// UNICODE | REQUEST_TARGET | NTLM | ALWAYS_SIGN | EXTENDED_SESSION_SECURITY | 128bit | 56bit +const NTLM_FLAGS = 0xa0088215 + +/** Build Type 1 (Negotiate) message. Returns the full Authorization header value. */ +export function buildNegotiateHeader(): string { + const buf = Buffer.alloc(40) + NTLMSSP_SIG.copy(buf) + buf.writeUInt32LE(1, 8) // MessageType = NTLMSSP_NEGOTIATE + buf.writeUInt32LE(NTLM_FLAGS, 12) + // DomainName: empty + buf.writeUInt16LE(0, 16); buf.writeUInt16LE(0, 18); buf.writeUInt32LE(40, 20) + // Workstation: empty + buf.writeUInt16LE(0, 24); buf.writeUInt16LE(0, 26); buf.writeUInt32LE(40, 28) + return 'NTLM ' + buf.toString('base64') +} + +/** Parse the server's Type 2 (Challenge) message from the WWW-Authenticate header value. */ +export function parseChallenge(headerValue: string): { + challenge: Buffer + targetInfo: Buffer +} { + const b64 = headerValue.replace(/^NTLM\s+/i, '').trim() + const buf = Buffer.from(b64, 'base64') + + const serverChallenge = buf.slice(24, 32) + + // TargetInfoFields at offset 40: Len(2) MaxLen(2) Offset(4) + let targetInfo = Buffer.alloc(0) + if (buf.length >= 48) { + const len = buf.readUInt16LE(40) + const offset = buf.readUInt32LE(44) + if (len > 0 && offset + len <= buf.length) { + targetInfo = buf.slice(offset, offset + len) + } + } + + return { challenge: serverChallenge, targetInfo } +} + +/** Split "DOMAIN\\user", "user@domain", or "user" into { user, domain }. */ +export function splitUser(username: string): { user: string; domain: string } { + const bs = username.indexOf('\\') + if (bs !== -1) return { domain: username.slice(0, bs), user: username.slice(bs + 1) } + const at = username.indexOf('@') + if (at !== -1) return { user: username.slice(0, at), domain: username.slice(at + 1) } + return { user: username, domain: '' } +} + +/** + * Build Type 3 (Authenticate) message. + * Returns the full Authorization header value (NTLMv2). + */ +export function buildAuthenticateHeader( + username: string, + domain: string, + password: string, + serverChallenge: Buffer, + targetInfo: Buffer +): string { + // NT hash and NTLMv2 session key + const ntHashBuf = md4(Buffer.from(password, 'utf16le')) + const responseKeyNT = crypto + .createHmac('md5', ntHashBuf) + .update(Buffer.from((username.toUpperCase() + domain.toUpperCase()), 'utf16le')) + .digest() + + // Client challenge (random 8 bytes) + const clientChallenge = crypto.randomBytes(8) + + // Timestamp: 100ns intervals since 1601-01-01 (Windows FILETIME) + const EPOCH_DIFF_MS = BigInt('11644473600000') // ms from 1601 to 1970 + const nowMs = BigInt(Date.now()) + const fileTime = (nowMs + EPOCH_DIFF_MS) * BigInt(10000) + const timestamp = Buffer.alloc(8) + timestamp.writeBigUInt64LE(fileTime) + + // NTLMv2 blob (the "NTChallengeResponse blob") + const blob = Buffer.concat([ + Buffer.from([0x01, 0x01, 0x00, 0x00]), // Signature + Buffer.from([0x00, 0x00, 0x00, 0x00]), // Reserved + timestamp, // Timestamp + clientChallenge, // ChallengeFromClient + Buffer.from([0x00, 0x00, 0x00, 0x00]), // Reserved + targetInfo, // AvPairs from server Type 2 + Buffer.from([0x00, 0x00, 0x00, 0x00]), // AvPairs list terminator + ]) + + // NTProofStr = HMAC-MD5(ResponseKeyNT, ServerChallenge + blob) + const ntProofStr = crypto + .createHmac('md5', responseKeyNT) + .update(Buffer.concat([serverChallenge, blob])) + .digest() + + const ntResponse = Buffer.concat([ntProofStr, blob]) + const lmResponse = Buffer.alloc(24, 0) // empty LM response + + const userBuf = Buffer.from(username, 'utf16le') + const domBuf = Buffer.from(domain, 'utf16le') + const wsBuf = Buffer.alloc(0) + const skBuf = Buffer.alloc(0) // no session key + + // Build Type 3 header (88 bytes fixed) + payload + let payOff = 88 + const lmOff = payOff; payOff += lmResponse.length + const ntOff = payOff; payOff += ntResponse.length + const domOff = payOff; payOff += domBuf.length + const usrOff = payOff; payOff += userBuf.length + const wsOff = payOff; payOff += wsBuf.length + const skOff = payOff + + const msg = Buffer.alloc(skOff + skBuf.length) + NTLMSSP_SIG.copy(msg) + msg.writeUInt32LE(3, 8) // MessageType = NTLMSSP_AUTH + + const writeField = (off: number, len: number, dataOff: number) => { + msg.writeUInt16LE(len, off); msg.writeUInt16LE(len, off + 2); msg.writeUInt32LE(dataOff, off + 4) + } + writeField(12, lmResponse.length, lmOff) + writeField(20, ntResponse.length, ntOff) + writeField(28, domBuf.length, domOff) + writeField(36, userBuf.length, usrOff) + writeField(44, wsBuf.length, wsOff) + writeField(52, skBuf.length, skOff) + msg.writeUInt32LE(NTLM_FLAGS, 60) + // Version at 64 (8 bytes) and MIC at 72 (16 bytes) left as zeros + + lmResponse.copy(msg, lmOff) + ntResponse.copy(msg, ntOff) + domBuf.copy(msg, domOff) + userBuf.copy(msg, usrOff) + + return 'NTLM ' + msg.toString('base64') +} diff --git a/src/main/providers/caldav.provider.ts b/src/main/providers/caldav.provider.ts index 3394c4d..6f63539 100644 --- a/src/main/providers/caldav.provider.ts +++ b/src/main/providers/caldav.provider.ts @@ -5,7 +5,8 @@ * Exchange 2013+ exposes CalDAV at /EWS/Calendar/; standard servers * advertise the principal via /.well-known/caldav (RFC 6764). * - * Auth: HTTP Basic, same credentials as IMAP. + * Auth: tries HTTP Basic first; if server demands NTLM (corporate Exchange), + * falls back to NTLMv2 authentication automatically. */ import https from 'node:https' @@ -13,6 +14,12 @@ import http from 'node:http' import type { IncomingMessage } from 'node:http' import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar' +import { + buildNegotiateHeader, + parseChallenge, + buildAuthenticateHeader, + splitUser +} from '../lib/ntlm' // ── HTTP helper ──────────────────────────────────────────────────────────────── @@ -25,6 +32,7 @@ interface RequestOptions { headers: Record body?: string allowSelfSigned?: boolean + agent?: https.Agent | http.Agent } interface RequestResult { @@ -33,7 +41,7 @@ interface RequestResult { body: string } -function request(opts: RequestOptions): Promise { +function rawRequest(opts: RequestOptions): Promise { return new Promise((resolve, reject) => { const module_ = opts.protocol === 'https' ? https : http const req = module_.request( @@ -44,7 +52,8 @@ function request(opts: RequestOptions): Promise { method: opts.method, headers: opts.headers, rejectUnauthorized: !opts.allowSelfSigned, - timeout: 15_000 + timeout: 15_000, + agent: opts.agent }, (res) => { let data = '' @@ -88,7 +97,6 @@ function decodeICalText(value: string): string { } function extractEmail(value: string): string { - // ORGANIZER:mailto:user@example.com or ATTENDEE;CN=Name:mailto:user@example.com const match = value.match(/mailto:([^\s;,>]+)/i) return match ? match[1] : value } @@ -101,146 +109,93 @@ function parseVEvents(icalText: string): RawVEvent[] { let props: Record> = {} for (const line of lines) { - if (line === 'BEGIN:VEVENT') { - inEvent = true - props = {} - continue - } + if (line === 'BEGIN:VEVENT') { inEvent = true; props = {}; continue } if (line === 'END:VEVENT') { inEvent = false - - const get = (key: string) => props[key]?.[0]?.value ?? '' - const getParams = (key: string) => props[key]?.[0]?.params ?? '' - const getAll = (key: string) => (props[key] ?? []).map((x) => x.value) - + const get = (k: string) => props[k]?.[0]?.value ?? '' + const getParams = (k: string) => props[k]?.[0]?.params ?? '' + const getAll = (k: string) => (props[k] ?? []).map((x) => x.value) events.push({ - uid: get('UID'), - summary: decodeICalText(get('SUMMARY')), - dtstart: get('DTSTART'), - dtStartParams: getParams('DTSTART'), - dtend: get('DTEND'), - dtEndParams: getParams('DTEND'), - location: decodeICalText(get('LOCATION')), - description: decodeICalText(get('DESCRIPTION')), + uid: get('UID'), summary: decodeICalText(get('SUMMARY')), + dtstart: get('DTSTART'), dtStartParams: getParams('DTSTART'), + dtend: get('DTEND'), dtEndParams: getParams('DTEND'), + location: decodeICalText(get('LOCATION')), description: decodeICalText(get('DESCRIPTION')), organizer: extractEmail(get('ORGANIZER')), attendees: getAll('ATTENDEE').map(extractEmail).filter(Boolean), status: get('STATUS').toLowerCase() }) continue } - if (!inEvent) continue - - const colonIdx = line.indexOf(':') - if (colonIdx === -1) continue - - const keyFull = line.substring(0, colonIdx) - const value = line.substring(colonIdx + 1) - const semicolonIdx = keyFull.indexOf(';') - const key = semicolonIdx === -1 ? keyFull : keyFull.substring(0, semicolonIdx) - const params = semicolonIdx === -1 ? '' : keyFull.substring(semicolonIdx + 1) - + const ci = line.indexOf(':') + if (ci === -1) continue + const keyFull = line.substring(0, ci) + const value = line.substring(ci + 1) + const si = keyFull.indexOf(';') + const key = si === -1 ? keyFull : keyFull.substring(0, si) + const params = si === -1 ? '' : keyFull.substring(si + 1) if (!props[key]) props[key] = [] props[key].push({ value, params }) } - return events } -/** - * Parse iCal date/time string to a JS Date. - * Handles: DATE (20240401), DATE-TIME UTC (20240401T090000Z), - * DATE-TIME local (20240401T090000), with TZID param ignored (treated as local). - */ function parseICalDate(value: string, params: string): { date: Date; isAllDay: boolean } { const isAllDay = params.includes('VALUE=DATE') || /^\d{8}$/.test(value) - if (isAllDay) { - const y = parseInt(value.slice(0, 4), 10) - const m = parseInt(value.slice(4, 6), 10) - 1 - const d = parseInt(value.slice(6, 8), 10) - return { date: new Date(Date.UTC(y, m, d)), isAllDay: true } + return { + date: new Date(Date.UTC( + parseInt(value.slice(0, 4), 10), + parseInt(value.slice(4, 6), 10) - 1, + parseInt(value.slice(6, 8), 10) + )), + isAllDay: true + } } - const isUTC = value.endsWith('Z') const clean = isUTC ? value.slice(0, -1) : value - - const y = parseInt(clean.slice(0, 4), 10) - const mo = parseInt(clean.slice(4, 6), 10) - 1 - const d = parseInt(clean.slice(6, 8), 10) - const h = clean.length > 8 ? parseInt(clean.slice(9, 11), 10) : 0 + const y = parseInt(clean.slice(0, 4), 10), mo = parseInt(clean.slice(4, 6), 10) - 1 + const d = parseInt(clean.slice(6, 8), 10) + const h = clean.length > 8 ? parseInt(clean.slice(9, 11), 10) : 0 const mi = clean.length > 8 ? parseInt(clean.slice(11, 13), 10) : 0 - const s = clean.length > 8 ? parseInt(clean.slice(13, 15), 10) : 0 - - const date = isUTC - ? new Date(Date.UTC(y, mo, d, h, mi, s)) - : new Date(y, mo, d, h, mi, s) - - return { date, isAllDay: false } + const s = clean.length > 8 ? parseInt(clean.slice(13, 15), 10) : 0 + return { date: isUTC ? new Date(Date.UTC(y, mo, d, h, mi, s)) : new Date(y, mo, d, h, mi, s), isAllDay: false } } // ── XML helpers ──────────────────────────────────────────────────────────────── -/** Extract all (or namespaced equivalent) block contents from a multistatus XML response. */ function extractCalendarData(xml: string): string[] { const results: string[] = [] - // Match both namespaced and un-namespaced calendar-data elements const re = /<(?:[^:\s>]+:)?calendar-data[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?calendar-data>/g let match: RegExpExecArray | null while ((match = re.exec(xml)) !== null) { - // CalDAV may XML-encode special chars inside calendar-data - const raw = match[1] - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/&/g, '&') - .replace(/ /g, '\r') - .trim() + const raw = match[1].replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&').replace(/ /g, '\r').trim() if (raw.length > 0) results.push(raw) } return results } -/** Extract calendar collections from a PROPFIND multistatus response. */ -interface CalDavCalendar { - href: string - displayName: string -} +interface CalDavCalendar { href: string; displayName: string } function extractCalendars(xml: string, baseUrl: string): CalDavCalendar[] { const calendars: CalDavCalendar[] = [] - - // Split by blocks const responseRe = /<(?:[^:\s>]+:)?response[^>]*>([\s\S]*?)<\/(?:[^:\s>]+:)?response>/g let match: RegExpExecArray | null - while ((match = responseRe.exec(xml)) !== null) { const block = match[1] - - // Must contain calendar resourcetype - if (!/<(?:[^:\s>]+:)?calendar[^>]*\/>/.test(block) && - !/<(?:[^:\s>]+:)?calendar[^>]*>/.test(block)) continue - + if (!/<(?:[^:\s>]+:)?calendar[^>]*\/?>/.test(block)) continue const hrefMatch = block.match(/<(?:[^:\s>]+:)?href[^>]*>([^<]+)<\/(?:[^:\s>]+:)?href>/) const nameMatch = block.match(/<(?:[^:\s>]+:)?displayname[^>]*>([^<]*)<\/(?:[^:\s>]+:)?displayname>/) - - if (hrefMatch) { - calendars.push({ - href: hrefMatch[1].trim(), - displayName: nameMatch ? decodeICalText(nameMatch[1].trim()) : 'Calendar' - }) - } + if (hrefMatch) calendars.push({ href: hrefMatch[1].trim(), displayName: nameMatch ? nameMatch[1].trim() : 'Calendar' }) } - - // If nothing found, treat the base path itself as the calendar - if (calendars.length === 0 && baseUrl.length > 0) { - calendars.push({ href: baseUrl, displayName: 'Calendar' }) - } - + if (calendars.length === 0 && baseUrl.length > 0) calendars.push({ href: baseUrl, displayName: 'Calendar' }) return calendars } // ── CalDAV Provider ──────────────────────────────────────────────────────────── +type AuthMode = 'basic' | 'ntlm' + export class CalDavProvider { private readonly hostname: string private readonly protocol: 'https' | 'http' @@ -248,34 +203,38 @@ export class CalDavProvider { private readonly username: string private readonly password: string private readonly allowSelfSigned: boolean - private readonly authHeader: string + private readonly basicAuthHeader: string - /** Resolved CalDAV base path (e.g. "/EWS/Calendar/") */ private basePath: string | null = null + private authMode: AuthMode = 'basic' constructor(config: AccountConfig) { const creds = config.credentials as ImapCredentials - - // Derive HTTPS endpoint from IMAP host; Exchange typically shares the hostname this.hostname = creds.host this.protocol = creds.secure ? 'https' : 'http' this.port = creds.secure ? 443 : 80 this.username = creds.username this.password = creds.password this.allowSelfSigned = creds.smtpAllowSelfSigned ?? false - - const encoded = Buffer.from(`${this.username}:${this.password}`).toString('base64') - this.authHeader = `Basic ${encoded}` + this.basicAuthHeader = 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64') } // ── Discovery ────────────────────────────────────────────────────────────── - /** - * Try to discover the CalDAV endpoint. - * Priority: /.well-known/caldav (RFC 6764) → /EWS/Calendar/ (Exchange) → /caldav/ (generic) - * Returns the resolved path or null if none found. - */ - async discoverBasePath(): Promise { + async connect(): Promise { + this.basePath = await this.discoverBasePath() + if (!this.basePath) { + throw new Error( + `CalDAV endpoint not found on ${this.hostname}. ` + + `Verified paths: /.well-known/caldav, /EWS/Calendar/. ` + + `Ensure Exchange CalDAV is enabled (Exchange 2013+).` + ) + } + } + + isConnected(): boolean { return this.basePath !== null } + + private async discoverBasePath(): Promise { const candidates = [ '/.well-known/caldav', '/EWS/Calendar/', @@ -287,202 +246,100 @@ export class CalDavProvider { for (const path of candidates) { try { - const result = await this.req('PROPFIND', path, { - Depth: '0', - 'Content-Type': 'application/xml; charset=utf-8', - }) - - // 207 Multi-Status = CalDAV responded, 301/302 = redirect → follow + const result = await this.req('PROPFIND', path, { Depth: '0' }) if (result.status === 207) return path if (result.status === 301 || result.status === 302) { const location = result.headers['location'] - if (location) { - const u = new URL(location, `${this.protocol}://${this.hostname}`) - return u.pathname + if (typeof location === 'string') { + try { return new URL(location, `${this.protocol}://${this.hostname}`).pathname } catch { /* skip */ } } } } catch { // Try next candidate } } - return null } - async connect(): Promise { - this.basePath = await this.discoverBasePath() - if (!this.basePath) { - throw new Error( - `CalDAV endpoint not found on ${this.hostname}. ` + - `Ensure Exchange CalDAV is enabled (Exchange 2013+).` - ) - } - } - - isConnected(): boolean { - return this.basePath !== null - } - // ── List calendars ───────────────────────────────────────────────────────── async listCalendars(accountId: string): Promise { if (!this.basePath) throw new Error('CalDAV not connected') - const body = ` - - - - + ` - - const result = await this.req('PROPFIND', this.basePath, { - Depth: '1', - 'Content-Type': 'application/xml; charset=utf-8', - }, body) - + const result = await this.req('PROPFIND', this.basePath, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) if (result.status !== 207) { - // Treat the base path as a single calendar on any other 2xx - return [{ - id: this.basePath, - name: 'Calendar', - accountId - }] + return [{ id: this.basePath, name: 'Calendar', accountId }] } - - const cals = extractCalendars(result.body, this.basePath) - return cals.map((c) => ({ - id: c.href, - name: c.displayName || 'Calendar', - accountId + return extractCalendars(result.body, this.basePath).map((c) => ({ + id: c.href, name: c.displayName || 'Calendar', accountId })) } // ── Fetch events ─────────────────────────────────────────────────────────── - async listEvents( - accountId: string, - calendarId: string, - start: Date, - end: Date - ): Promise { - const startStr = toUtcString(start) - const endStr = toUtcString(end) - + async listEvents(accountId: string, calendarId: string, start: Date, end: Date): Promise { const body = ` - - - - + - + ` - const result = await this.req('REPORT', calendarId, { - Depth: '1', - 'Content-Type': 'application/xml; charset=utf-8', - }, body) - - if (result.status !== 207) { - // Exchange may not support time-range; fall back to PROPFIND + client-side filtering - return this.fetchAllEventsAndFilter(accountId, calendarId, start, end) - } - - return this.parseMultistatusEvents(result.body, accountId, calendarId) + const result = await this.req('REPORT', calendarId, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) + if (result.status !== 207) return this.fetchAllAndFilter(accountId, calendarId, start, end) + return this.parseMultistatus(result.body, accountId, calendarId) } - /** Fallback: fetch all VEVENT objects and filter client-side by time range. */ - private async fetchAllEventsAndFilter( - accountId: string, - calendarId: string, - start: Date, - end: Date - ): Promise { + private async fetchAllAndFilter(accountId: string, calendarId: string, start: Date, end: Date): Promise { const body = ` - - - - - - - - - + + ` - - const result = await this.req('REPORT', calendarId, { - Depth: '1', - 'Content-Type': 'application/xml; charset=utf-8', - }, body) - + const result = await this.req('REPORT', calendarId, { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, body) if (result.status !== 207) return [] - - const all = this.parseMultistatusEvents(result.body, accountId, calendarId) - return all.filter((ev) => { - const evEnd = new Date(ev.end) - const evStart = new Date(ev.start) - return evStart < end && evEnd > start - }) + return this.parseMultistatus(result.body, accountId, calendarId).filter((ev) => + new Date(ev.start) < end && new Date(ev.end) > start + ) } - // ── Parsing ──────────────────────────────────────────────────────────────── - - private parseMultistatusEvents( - xml: string, - accountId: string, - calendarId: string - ): CalendarEvent[] { + private parseMultistatus(xml: string, accountId: string, calendarId: string): CalendarEvent[] { const events: CalendarEvent[] = [] - const icalBlocks = extractCalendarData(xml) - - for (const block of icalBlocks) { - const raw = parseVEvents(block) - for (const rv of raw) { + for (const block of extractCalendarData(xml)) { + for (const rv of parseVEvents(block)) { if (!rv.dtstart) continue - const { date: startDate, isAllDay } = parseICalDate(rv.dtstart, rv.dtStartParams) let endDate: Date - - if (rv.dtend) { - endDate = parseICalDate(rv.dtend, rv.dtEndParams).date - } else { - // No DTEND: for all-day events default to +1 day, for timed +1 hour - endDate = new Date(startDate) - if (isAllDay) endDate.setUTCDate(endDate.getUTCDate() + 1) - else endDate.setTime(endDate.getTime() + 60 * 60 * 1000) - } - - const id = `${calendarId}::${rv.uid || startDate.toISOString()}` - + if (rv.dtend) endDate = parseICalDate(rv.dtend, rv.dtEndParams).date + else { endDate = new Date(startDate); if (isAllDay) endDate.setUTCDate(endDate.getUTCDate() + 1); else endDate.setTime(endDate.getTime() + 3_600_000) } events.push({ - id, - uid: rv.uid, - calendarId, - accountId, + id: `${calendarId}::${rv.uid || startDate.toISOString()}`, + uid: rv.uid, calendarId, accountId, title: rv.summary || '(no title)', - start: startDate.toISOString(), - end: endDate.toISOString(), - isAllDay, - location: rv.location || undefined, - description: rv.description || undefined, - organizer: rv.organizer || undefined, - attendees: rv.attendees, + start: startDate.toISOString(), end: endDate.toISOString(), isAllDay, + location: rv.location || undefined, description: rv.description || undefined, + organizer: rv.organizer || undefined, attendees: rv.attendees, status: (rv.status as CalendarEvent['status']) || 'confirmed' }) } } - return events } - // ── Internal HTTP helper ─────────────────────────────────────────────────── + // ── Authenticated HTTP request ───────────────────────────────────────────── + // + // Strategy: + // 1. Try with Basic auth (or NTLM if already detected). + // 2. If server replies 401 with WWW-Authenticate containing "NTLM", + // switch to NTLM and retry. private async req( method: string, @@ -490,41 +347,119 @@ export class CalDavProvider { extraHeaders: Record = {}, body?: string ): Promise { - const headers: Record = { - Authorization: this.authHeader, - 'User-Agent': 'AeroMail/1.0', - ...extraHeaders - } - if (body) { - headers['Content-Length'] = Buffer.byteLength(body, 'utf8').toString() + if (this.authMode === 'ntlm') { + return this.reqNtlm(method, path, extraHeaders, body) } - return request({ + // Try Basic first + const result = await this.rawReq(method, path, { Authorization: this.basicAuthHeader, ...extraHeaders }, body) + + if (result.status === 401 && this.needsNtlm(result.headers)) { + // Server requires NTLM — switch mode and retry + this.authMode = 'ntlm' + return this.reqNtlm(method, path, extraHeaders, body) + } + + return result + } + + /** + * Execute a full NTLMv2 3-way handshake and return the authenticated response. + * + * Both the Negotiate (Type 1) and Authenticate (Type 3) requests MUST use the + * same TCP connection. We achieve this by creating a fresh keepAlive Agent with + * maxSockets:1 for each operation — the first socket created is reused for the + * second request automatically. + */ + private async reqNtlm( + method: string, + path: string, + extraHeaders: Record = {}, + body?: string + ): Promise { + const agentOpts = { keepAlive: true, maxSockets: 1, rejectUnauthorized: !this.allowSelfSigned } + const agent = this.protocol === 'https' + ? new https.Agent(agentOpts) + : new http.Agent({ keepAlive: true, maxSockets: 1 }) + + try { + // Step 1: Type 1 Negotiate (no body, just the method + NTLM negotiate header) + const type1Result = await this.rawReq( + method, path, + { Authorization: buildNegotiateHeader(), ...extraHeaders }, + undefined, + agent + ) + + // Step 2: Extract Type 2 Challenge from 401 response + const wwwAuth = this.extractNtlmChallenge(type1Result.headers) + if (!wwwAuth) { + // Server accepted Type 1 without a challenge (unusual) — return as-is + return type1Result + } + + const { challenge, targetInfo } = parseChallenge(wwwAuth) + const { user, domain } = splitUser(this.username) + const type3Header = buildAuthenticateHeader(user, domain, this.password, challenge, targetInfo) + + // Step 3: Type 3 Authenticate with actual request body + const finalResult = await this.rawReq( + method, path, + { Authorization: type3Header, ...extraHeaders }, + body, + agent + ) + return finalResult + } finally { + agent.destroy() + } + } + + private rawReq( + method: string, + path: string, + headers: Record, + body?: string, + agent?: https.Agent | http.Agent + ): Promise { + const allHeaders: Record = { + 'User-Agent': 'AeroMail/1.0', + ...headers + } + if (body) allHeaders['Content-Length'] = Buffer.byteLength(body, 'utf8').toString() + + return rawRequest({ protocol: this.protocol, hostname: this.hostname, port: this.port, path, method, - headers, + headers: allHeaders, body, - allowSelfSigned: this.allowSelfSigned + allowSelfSigned: this.allowSelfSigned, + agent }) } + + /** Returns the NTLM challenge header value, or null if the response doesn't contain one. */ + private extractNtlmChallenge(headers: IncomingMessage['headers']): string | null { + const auth = headers['www-authenticate'] + const list = Array.isArray(auth) ? auth : typeof auth === 'string' ? auth.split(',') : [] + const ntlmHeader = list.map((s) => s.trim()).find((s) => /^NTLM\s+/i.test(s)) + return ntlmHeader ?? null + } + + /** Returns true if a 401 response is asking for NTLM/Negotiate. */ + private needsNtlm(headers: IncomingMessage['headers']): boolean { + const auth = headers['www-authenticate'] + const s = Array.isArray(auth) ? auth.join(',') : auth ?? '' + return /NTLM|Negotiate/i.test(s) + } } // ── Utility ──────────────────────────────────────────────────────────────────── -/** Format a Date as an iCal UTC string: 20240401T000000Z */ function toUtcString(d: Date): string { - const pad = (n: number) => String(n).padStart(2, '0') - return ( - d.getUTCFullYear().toString() + - pad(d.getUTCMonth() + 1) + - pad(d.getUTCDate()) + - 'T' + - pad(d.getUTCHours()) + - pad(d.getUTCMinutes()) + - pad(d.getUTCSeconds()) + - 'Z' - ) + const p = (n: number) => String(n).padStart(2, '0') + return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z` }