diff --git a/src/main/index.ts b/src/main/index.ts index efe5621..719ff95 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -5,6 +5,7 @@ import { AccountManager } from './services/account-manager' import { registerAccountHandlers } from './ipc/accounts.handler' import { registerFolderHandlers } from './ipc/folders.handler' import { registerMessageHandlers } from './ipc/messages.handler' +import { registerCalendarHandlers } from './ipc/calendar.handler' import type { ComposeSession } from '@shared/types/message' const accountManager = new AccountManager() @@ -142,6 +143,7 @@ app.whenReady().then(async () => { registerAccountHandlers(accountManager) registerFolderHandlers(accountManager) registerMessageHandlers(accountManager) + registerCalendarHandlers(accountManager) createWindow() diff --git a/src/main/ipc/calendar.handler.ts b/src/main/ipc/calendar.handler.ts new file mode 100644 index 0000000..54f1666 --- /dev/null +++ b/src/main/ipc/calendar.handler.ts @@ -0,0 +1,16 @@ +import type { AccountManager } from '../services/account-manager' +import { registerHandler } from './registry' + +export function registerCalendarHandlers(manager: AccountManager): void { + registerHandler('calendar:list', ({ accountId }) => + manager.listCalendars(accountId) + ) + + registerHandler('calendar:events', ({ accountId, calendarId, start, end }) => + manager.listCalendarEvents(accountId, calendarId, new Date(start), new Date(end)) + ) + + registerHandler('calendar:probe', ({ accountId }) => + manager.probeCalendarPaths(accountId) + ) +} diff --git a/src/main/lib/ntlm.ts b/src/main/lib/ntlm.ts new file mode 100644 index 0000000..d498592 --- /dev/null +++ b/src/main/lib/ntlm.ts @@ -0,0 +1,219 @@ +/** + * 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 + /** 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 offset = buf.readUInt32LE(44) + if (len > 0 && offset + len <= buf.length) { + targetInfo = buf.slice(offset, offset + len) + } + } + + return { challenge: serverChallenge, targetInfo, targetName } +} + +/** 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 new file mode 100644 index 0000000..348846f --- /dev/null +++ b/src/main/providers/caldav.provider.ts @@ -0,0 +1,421 @@ +/** + * 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 } from '@shared/types/calendar' +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 [] + return this.parseEwsEvents(result.body, accountId, calendarId) + } + + // ── 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 parseEwsEvents(xml: string, accountId: string, calendarId: string): CalendarEvent[] { + const events: CalendarEvent[] = [] + const re = /([\s\S]*?)<\/t:CalendarItem>/g + let m: RegExpExecArray | null + while ((m = re.exec(xml)) !== null) { + const block = m[1] + const get = (tag: string): string => { + const r = block.match(new RegExp(`]*)?>([\\s\\S]*?)<\\/t:${tag}>`)) + return r ? r[1].replace(/<[^>]+>/g, '').trim() : '' + } + const idM = block.match(/[\s\S]*?([^<]+)<\/t:EmailAddress>/) + events.push({ + id: `ews::${idM[1]}`, + uid: idM[1], + calendarId, + accountId, + title: get('Subject') || '(без темы)', + start: start.toISOString(), + end: end.toISOString(), + isAllDay, + location: get('Location') || undefined, + description: get('Body') || undefined, + organizer: organizerM ? organizerM[1] : undefined, + attendees: [], + status: fbStatus === 'tentative' ? 'tentative' : 'confirmed' + }) + } + return events + } + + private async tryAutodiscover(): Promise<{ ewsUrl: string } | null> { + const body = ` + + + ${this.email} + http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a + +` + const headers = { 'Content-Type': 'text/xml; charset=utf-8' } + for (const path of ['/autodiscover/autodiscover.xml', '/Autodiscover/Autodiscover.xml']) { + try { + const result = await this.req('POST', path, headers, body) + if (result.status === 200) { + const m = result.body.match(/([^<]+)<\/EwsUrl>/i) + if (m) return { ewsUrl: m[1].trim() } + } + } catch { /* try next */ } + } + return null + } + + // ── Authenticated HTTP request ───────────────────────────────────────────── + + 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) + } +} diff --git a/src/main/services/account-manager.ts b/src/main/services/account-manager.ts index 912466b..0878702 100644 --- a/src/main/services/account-manager.ts +++ b/src/main/services/account-manager.ts @@ -3,7 +3,9 @@ import type { AccountConfig, ImapCredentials } from '@shared/types/account' import { AccountType } from '@shared/types/account' import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData } from '@shared/types/message' +import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar' import { ImapProvider } from '../providers/imap.provider' +import { CalDavProvider } from '../providers/caldav.provider' import { CredentialStore } from './credential-store' import Store from 'electron-store' @@ -16,6 +18,7 @@ const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', ' export class AccountManager { private providers = new Map() + private calendarProviders = new Map() private store: Store private credentialStore: CredentialStore private mainWindow: BrowserWindow | null = null @@ -72,6 +75,7 @@ export class AccountManager { await provider.disconnect() this.providers.delete(accountId) } + this.calendarProviders.delete(accountId) await this.credentialStore.remove(accountId) const accounts = this.store.get('accounts', []) @@ -205,6 +209,69 @@ export class AccountManager { ) } + // ── Calendar ──────────────────────────────────────────── + + async listCalendars(accountId: string): Promise { + const provider = await this.getOrCreateCalendarProvider(accountId) + return provider.listCalendars(accountId) + } + + async listCalendarEvents( + accountId: string, + calendarId: string, + start: Date, + end: Date + ): Promise { + const provider = await this.getOrCreateCalendarProvider(accountId) + return provider.listEvents(accountId, calendarId, start, end) + } + + async probeCalendarPaths(accountId: string): Promise<{ path: string; status: number; note: string }[]> { + // Create a fresh provider (no cached state) and probe without connecting + const accounts = this.store.get('accounts', []) + const accMeta = accounts.find((a) => a.id === accountId) + if (!accMeta) throw new Error(`Account ${accountId} not found`) + + const credRaw = this.credentialStore.get(accountId) + if (!credRaw) throw new Error(`Credentials for ${accountId} not found`) + + let credentials: AccountConfig['credentials'] + try { + credentials = JSON.parse(credRaw) + } catch { + throw new Error('Corrupted credentials') + } + + const config: AccountConfig = { ...accMeta, credentials } + const provider = new CalDavProvider(config) + return provider.probePaths() + } + + private async getOrCreateCalendarProvider(accountId: string): Promise { + const existing = this.calendarProviders.get(accountId) + if (existing?.isConnected()) return existing + + 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) + await provider.connect() + this.calendarProviders.set(accountId, provider) + return provider + } + // ── Auto-reconnect ────────────────────────────────────── private async withAutoReconnect(accountId: string, fn: () => Promise): Promise { diff --git a/src/renderer/src/components/AppIcon.vue b/src/renderer/src/components/AppIcon.vue index 0a8b5d2..72881f6 100644 --- a/src/renderer/src/components/AppIcon.vue +++ b/src/renderer/src/components/AppIcon.vue @@ -24,6 +24,7 @@ export type IconName = | 'pdf' | 'image' | 'bell-off' + | 'calendar' const props = defineProps<{ name: IconName @@ -141,6 +142,12 @@ const paths: Record = { `, + calendar: ` + + + + + `, } diff --git a/src/renderer/src/components/accounts/AddAccountDialog.vue b/src/renderer/src/components/accounts/AddAccountDialog.vue index 2cfda49..ed2bb9f 100644 --- a/src/renderer/src/components/accounts/AddAccountDialog.vue +++ b/src/renderer/src/components/accounts/AddAccountDialog.vue @@ -34,6 +34,13 @@ const smtpSecure = ref(false) const smtpAllowSelfSigned = ref(false) const showSmtp = ref(false) +const caldavHost = ref('') +const caldavPort = ref(443) +const caldavSecure = ref(true) +const caldavPath = ref('') +const caldavAllowSelfSigned = ref(false) +const showCaldav = ref(false) + function generateId(): string { return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}` } @@ -57,6 +64,15 @@ async function handleSubmit(): Promise { smtpSecure: smtpSecure.value, ...(smtpAllowSelfSigned.value ? { smtpAllowSelfSigned: true } : {}) } + : {}), + ...(showCaldav.value && caldavHost.value + ? { + caldavHost: caldavHost.value, + caldavPort: caldavPort.value, + caldavSecure: caldavSecure.value, + ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}), + ...(caldavAllowSelfSigned.value ? { caldavAllowSelfSigned: true } : {}) + } : {}) } const config: AccountConfig = { @@ -173,6 +189,46 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value && imapP + +
+ +
+
+
+ + +
+
+ + +
+
+
+ +
+
+ + +
+
+ +
+
+
+ diff --git a/src/renderer/src/components/accounts/EditAccountDialog.vue b/src/renderer/src/components/accounts/EditAccountDialog.vue index aa14d2d..10b8bc4 100644 --- a/src/renderer/src/components/accounts/EditAccountDialog.vue +++ b/src/renderer/src/components/accounts/EditAccountDialog.vue @@ -32,6 +32,13 @@ const smtpPort = ref(creds.smtpPort ?? 587) const smtpSecure = ref(creds.smtpSecure ?? false) const showSmtp = ref(!!creds.smtpHost) +const caldavHost = ref(creds.caldavHost ?? '') +const caldavPort = ref(creds.caldavPort ?? 443) +const caldavSecure = ref(creds.caldavSecure ?? true) +const caldavPath = ref(creds.caldavPath ?? '') +const caldavAllowSelfSigned = ref(creds.caldavAllowSelfSigned ?? false) +const showCaldav = ref(!!creds.caldavHost) + async function handleSubmit(): Promise { testing.value = true error.value = '' @@ -45,6 +52,15 @@ async function handleSubmit(): Promise { password: imapPassword.value, ...(showSmtp.value && smtpHost.value ? { smtpHost: smtpHost.value, smtpPort: smtpPort.value, smtpSecure: smtpSecure.value } + : {}), + ...(showCaldav.value && caldavHost.value + ? { + caldavHost: caldavHost.value, + caldavPort: caldavPort.value, + caldavSecure: caldavSecure.value, + ...(caldavPath.value.trim() ? { caldavPath: caldavPath.value.trim() } : {}), + ...(caldavAllowSelfSigned.value ? { caldavAllowSelfSigned: true } : {}) + } : {}) } const config: AccountConfig = { @@ -155,6 +171,46 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value) + +
+ +
+
+
+ + +
+
+ + +
+
+
+ +
+
+ + +
+
+ +
+
+
+ diff --git a/src/renderer/src/components/calendar/EventBlock.vue b/src/renderer/src/components/calendar/EventBlock.vue new file mode 100644 index 0000000..47c2d76 --- /dev/null +++ b/src/renderer/src/components/calendar/EventBlock.vue @@ -0,0 +1,92 @@ + + + + + diff --git a/src/renderer/src/components/calendar/EventDetailPopup.vue b/src/renderer/src/components/calendar/EventDetailPopup.vue new file mode 100644 index 0000000..6476f72 --- /dev/null +++ b/src/renderer/src/components/calendar/EventDetailPopup.vue @@ -0,0 +1,200 @@ + + + + + diff --git a/src/renderer/src/components/calendar/WeekView.vue b/src/renderer/src/components/calendar/WeekView.vue new file mode 100644 index 0000000..9c56cff --- /dev/null +++ b/src/renderer/src/components/calendar/WeekView.vue @@ -0,0 +1,520 @@ + + + + + diff --git a/src/renderer/src/components/sidebar/AccountSwitcher.vue b/src/renderer/src/components/sidebar/AccountSwitcher.vue index 2953f0b..bb89327 100644 --- a/src/renderer/src/components/sidebar/AccountSwitcher.vue +++ b/src/renderer/src/components/sidebar/AccountSwitcher.vue @@ -1,6 +1,6 @@ + + + + diff --git a/src/shared/types/account.ts b/src/shared/types/account.ts index 503fb9d..530824e 100644 --- a/src/shared/types/account.ts +++ b/src/shared/types/account.ts @@ -14,6 +14,12 @@ export interface ImapCredentials { smtpSecure?: boolean // Разрешить самоподписанные сертификаты — только для корпоративных серверов smtpAllowSelfSigned?: boolean + // CalDAV — опционально; если не указан хост, используется IMAP-хост + caldavHost?: string + caldavPort?: number + caldavSecure?: boolean + caldavPath?: string // базовый путь, например /EWS/Calendar/ (если пуст — autodiscovery) + caldavAllowSelfSigned?: boolean // разрешить самоподписанные/недоверенные сертификаты } export type AccountCredentials = ImapCredentials diff --git a/src/shared/types/calendar.ts b/src/shared/types/calendar.ts new file mode 100644 index 0000000..9aafb35 --- /dev/null +++ b/src/shared/types/calendar.ts @@ -0,0 +1,22 @@ +export interface CalendarInfo { + id: string + name: string + color?: string + accountId: string +} + +export interface CalendarEvent { + id: string + uid: string + calendarId: string + accountId: string + title: string + start: string // ISO 8601 + end: string // ISO 8601 + isAllDay: boolean + location?: string + description?: string + organizer?: string + attendees: string[] + status?: 'tentative' | 'confirmed' | 'cancelled' +} diff --git a/src/shared/types/ipc.ts b/src/shared/types/ipc.ts index 3d78f26..7c84ff2 100644 --- a/src/shared/types/ipc.ts +++ b/src/shared/types/ipc.ts @@ -1,6 +1,7 @@ import type { AccountConfig } from './account' import type { FolderListResult, MessageListResult } from './provider' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, ComposeSession } from './message' +import type { CalendarInfo, CalendarEvent } from './calendar' export interface IpcChannelMap { 'accounts:list': [void, AccountConfig[]] @@ -47,6 +48,16 @@ export interface IpcChannelMap { 'app:setZoom': [{ factor: number }, void] 'app:isEncryptionAvailable': [void, boolean] + + 'calendar:list': [{ accountId: string }, CalendarInfo[]] + 'calendar:events': [ + { accountId: string; calendarId: string; start: string; end: string }, + CalendarEvent[] + ] + 'calendar:probe': [ + { accountId: string }, + { path: string; status: number; note: string }[] + ] } export interface IpcEventMap {