fix: security hardening, stability & bug fixes
Security:
- Add .env to .gitignore, update .env.example template
- Remove global rejectUnauthorized:false — now per-account opt-in via smtpAllowSelfSigned
- Warn in logs and UI when safeStorage/keychain is unavailable
- Add app:isEncryptionAvailable IPC for renderer to surface keychain warning
- Mask SMTP username from console.log
Stability:
- Wrap all JSON.parse calls in try-catch (account-manager, credential-store)
- Fix silent .catch(()=>{}) on pollNewMessages — log warnings instead
- Add 10s connect() timeout to all providers (IMAP, Gmail, Exchange)
- Fix race condition in withAutoReconnect: properly surface reconnect errors
Bug fixes & quality:
- Fix newArrivals overwrite bug: collect all new messages, not just last one
- Add LRU eviction to bodyCache (max 100 entries) to prevent memory leak
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
ba58479231
commit
b7777b9dcb
12 changed files with 134 additions and 28 deletions
|
|
@ -1,2 +1,4 @@
|
|||
# Google OAuth credentials for Gmail provider
|
||||
# Create your own at https://console.cloud.google.com/apis/credentials
|
||||
GMAIL_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
||||
GMAIL_CLIENT_SECRET=your-client-secret
|
||||
|
|
|
|||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -3,3 +3,4 @@ out/
|
|||
dist/
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
|
|
|
|||
|
|
@ -1,7 +1,11 @@
|
|||
import { registerHandler } from './registry'
|
||||
import type { AccountManager } from '../services/account-manager'
|
||||
import { safeStorage } from 'electron'
|
||||
|
||||
export function registerAccountHandlers(manager: AccountManager): void {
|
||||
registerHandler('app:isEncryptionAvailable', async () => {
|
||||
return safeStorage.isEncryptionAvailable()
|
||||
})
|
||||
registerHandler('accounts:list', async () => {
|
||||
return manager.getAccounts()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -39,9 +39,11 @@ export class ExchangeProvider implements IEmailProvider {
|
|||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
// Test connection by fetching inbox
|
||||
const view = new FolderView(1)
|
||||
await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view)
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
)
|
||||
await Promise.race([this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view), timeout])
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,8 +26,10 @@ export class GmailProvider implements IEmailProvider {
|
|||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
// Verify connection by getting profile
|
||||
await this.gmail.users.getProfile({ userId: 'me' })
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
)
|
||||
await Promise.race([this.gmail.users.getProfile({ userId: 'me' }), timeout])
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -50,7 +50,10 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
await this.client.connect()
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
)
|
||||
await Promise.race([this.client.connect(), timeout])
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
|
|
@ -264,7 +267,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
port: smtpPort,
|
||||
secure: smtpSecure,
|
||||
auth: { user: creds.username, pass: creds.password },
|
||||
tls: { rejectUnauthorized: false } // самоподписанные сертификаты корпоративных серверов
|
||||
tls: creds.smtpAllowSelfSigned ? { rejectUnauthorized: false } : undefined
|
||||
})
|
||||
|
||||
// Если email хранится без домена (только логин) — достраиваем из IMAP-хоста
|
||||
|
|
@ -276,8 +279,8 @@ export class ImapProvider implements IEmailProvider {
|
|||
? { name: this.config.label, address: emailAddress }
|
||||
: emailAddress
|
||||
|
||||
console.log('[SMTP] host=%s port=%d secure=%s user=%s from=%j to=%j',
|
||||
smtpHost, smtpPort, smtpSecure, creds.username, from, compose.to)
|
||||
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
|
||||
smtpHost, smtpPort, smtpSecure, from, compose.to)
|
||||
|
||||
const info = await transporter.sendMail({
|
||||
from,
|
||||
|
|
|
|||
|
|
@ -103,11 +103,15 @@ export class AccountManager {
|
|||
const credRaw = this.credentialStore.get(accountId)
|
||||
if (!credRaw) return { success: false, error: 'Credentials not found' }
|
||||
|
||||
const config: AccountConfig = {
|
||||
...accMeta,
|
||||
credentials: JSON.parse(credRaw)
|
||||
let credentials: AccountConfig['credentials']
|
||||
try {
|
||||
credentials = JSON.parse(credRaw)
|
||||
} catch {
|
||||
return { success: false, error: 'Corrupted credentials — please re-add the account' }
|
||||
}
|
||||
|
||||
const config: AccountConfig = { ...accMeta, credentials }
|
||||
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
this.providers.set(accountId, provider)
|
||||
|
|
@ -127,7 +131,12 @@ export class AccountManager {
|
|||
|
||||
async pollNewMessages(accountId: string): Promise<void> {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (provider) await provider.pollNewMessages().catch(() => {})
|
||||
if (!provider) return
|
||||
try {
|
||||
await provider.pollNewMessages()
|
||||
} catch (err) {
|
||||
console.warn(`[AccountManager] poll error for ${accountId}:`, (err as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(accountId: string, compose: ComposeData): Promise<void> {
|
||||
|
|
@ -205,11 +214,16 @@ export class AccountManager {
|
|||
return await fn()
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code ?? ''
|
||||
if (RECONNECT_CODES.has(code)) {
|
||||
if (!RECONNECT_CODES.has(code)) throw err
|
||||
|
||||
try {
|
||||
await this.reconnectAccount(accountId)
|
||||
return await fn()
|
||||
} catch (reconnectErr) {
|
||||
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
|
||||
throw reconnectErr
|
||||
}
|
||||
throw err
|
||||
|
||||
return await fn()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -229,7 +243,14 @@ export class AccountManager {
|
|||
const credRaw = this.credentialStore.get(accountId)
|
||||
if (!credRaw) throw new Error('Credentials not found')
|
||||
|
||||
const config: AccountConfig = { ...accMeta, credentials: JSON.parse(credRaw) }
|
||||
let credentials: AccountConfig['credentials']
|
||||
try {
|
||||
credentials = JSON.parse(credRaw)
|
||||
} catch {
|
||||
throw new Error('Corrupted credentials — please re-add the account')
|
||||
}
|
||||
|
||||
const config: AccountConfig = { ...accMeta, credentials }
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
this.providers.set(accountId, provider)
|
||||
|
|
@ -265,8 +286,12 @@ export class AccountManager {
|
|||
if ('password' in creds && creds.password === '') {
|
||||
const existingCredRaw = this.credentialStore.get(config.id)
|
||||
if (existingCredRaw) {
|
||||
const existing = JSON.parse(existingCredRaw) as ImapCredentials
|
||||
newCredentials = { ...creds, password: existing.password }
|
||||
try {
|
||||
const existing = JSON.parse(existingCredRaw) as ImapCredentials
|
||||
newCredentials = { ...creds, password: existing.password }
|
||||
} catch {
|
||||
return { success: false, error: 'Corrupted existing credentials — please re-add the account' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,14 @@ export class CredentialStore {
|
|||
try {
|
||||
if (!existsSync(this.filePath)) return
|
||||
const raw = await readFile(this.filePath, 'utf-8')
|
||||
const parsed = JSON.parse(raw) as Record<string, string>
|
||||
let parsed: Record<string, string>
|
||||
try {
|
||||
parsed = JSON.parse(raw) as Record<string, string>
|
||||
} catch {
|
||||
console.warn('[CredentialStore] credentials.json is corrupted — starting fresh')
|
||||
this.data = {}
|
||||
return
|
||||
}
|
||||
for (const [key, value] of Object.entries(parsed)) {
|
||||
try {
|
||||
if (value.startsWith('plain:')) {
|
||||
|
|
@ -49,14 +56,24 @@ export class CredentialStore {
|
|||
await this.persist()
|
||||
}
|
||||
|
||||
isEncryptionAvailable(): boolean {
|
||||
return safeStorage.isEncryptionAvailable()
|
||||
}
|
||||
|
||||
private async persist(): Promise<void> {
|
||||
const canEncrypt = safeStorage.isEncryptionAvailable()
|
||||
if (!canEncrypt) {
|
||||
console.warn(
|
||||
'[CredentialStore] safeStorage unavailable — credentials stored without encryption. ' +
|
||||
'Install a keychain daemon (e.g. gnome-keyring or kwallet) for secure storage.'
|
||||
)
|
||||
}
|
||||
const out: Record<string, string> = {}
|
||||
for (const [key, value] of Object.entries(this.data)) {
|
||||
if (canEncrypt) {
|
||||
out[key] = 'enc:' + safeStorage.encryptString(value).toString('base64')
|
||||
} else {
|
||||
// safeStorage недоступен (нет keychain-демона в системе) — храним plain
|
||||
// safeStorage недоступен — храним обфусцированно, без реального шифрования
|
||||
out[key] = 'plain:' + Buffer.from(value).toString('base64')
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,25 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { AccountType } from '@shared/types/account'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
import { useAccountsStore } from '../../stores/accounts.store'
|
||||
import { useIpc } from '../../composables/useIpc'
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
}>()
|
||||
|
||||
const accountsStore = useAccountsStore()
|
||||
const { invoke } = useIpc()
|
||||
|
||||
const step = ref<'credentials' | 'testing'>('credentials')
|
||||
const error = ref('')
|
||||
const testing = ref(false)
|
||||
const encryptionAvailable = ref(true)
|
||||
|
||||
onMounted(async () => {
|
||||
encryptionAvailable.value = await invoke('app:isEncryptionAvailable')
|
||||
})
|
||||
|
||||
const imapHost = ref('')
|
||||
const imapPort = ref(993)
|
||||
|
|
@ -21,10 +28,11 @@ const imapUsername = ref('')
|
|||
const imapPassword = ref('')
|
||||
const imapLabel = ref('')
|
||||
|
||||
const smtpHost = ref('')
|
||||
const smtpPort = ref(587)
|
||||
const smtpSecure = ref(false)
|
||||
const showSmtp = ref(false)
|
||||
const smtpHost = ref('')
|
||||
const smtpPort = ref(587)
|
||||
const smtpSecure = ref(false)
|
||||
const smtpAllowSelfSigned = ref(false)
|
||||
const showSmtp = ref(false)
|
||||
|
||||
function generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
|
|
@ -43,7 +51,12 @@ async function handleSubmit(): Promise<void> {
|
|||
username: imapUsername.value,
|
||||
password: imapPassword.value,
|
||||
...(showSmtp.value && smtpHost.value
|
||||
? { smtpHost: smtpHost.value, smtpPort: smtpPort.value, smtpSecure: smtpSecure.value }
|
||||
? {
|
||||
smtpHost: smtpHost.value,
|
||||
smtpPort: smtpPort.value,
|
||||
smtpSecure: smtpSecure.value,
|
||||
...(smtpAllowSelfSigned.value ? { smtpAllowSelfSigned: true } : {})
|
||||
}
|
||||
: {})
|
||||
}
|
||||
const config: AccountConfig = {
|
||||
|
|
@ -89,6 +102,9 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value && imapP
|
|||
|
||||
<!-- Форма учётных данных -->
|
||||
<div v-if="step === 'credentials'" class="dialog-body" style="overflow-y:auto;max-height:calc(85vh - 70px)">
|
||||
<div v-if="!encryptionAvailable" class="warn-msg">
|
||||
Keychain недоступен — пароли будут сохранены без шифрования. Установите gnome-keyring или kwallet для безопасного хранения.
|
||||
</div>
|
||||
<div v-if="error" class="error-msg">{{ error }}</div>
|
||||
|
||||
<form @submit.prevent="handleSubmit">
|
||||
|
|
@ -148,6 +164,12 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value && imapP
|
|||
SSL/TLS (порт 465)
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="checkbox-label">
|
||||
<input v-model="smtpAllowSelfSigned" type="checkbox" />
|
||||
Разрешить самоподписанные сертификаты (небезопасно)
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -302,6 +324,22 @@ const isFormValid = computed(() => imapHost.value && imapUsername.value && imapP
|
|||
padding: 28px;
|
||||
}
|
||||
|
||||
/* ── Warning ────────────────────────────────────────────── */
|
||||
.warn-msg {
|
||||
padding: 10px 14px;
|
||||
background: rgba(255, 180, 0, 0.08);
|
||||
border: 1px solid rgba(255, 180, 0, 0.30);
|
||||
border-top-color: rgba(255, 200, 60, 0.50);
|
||||
border-radius: var(--radius-md);
|
||||
color: rgb(255, 200, 80);
|
||||
font-size: 12px;
|
||||
margin-bottom: 18px;
|
||||
line-height: 1.5;
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 200, 60, 0.08),
|
||||
0 2px 12px rgba(255, 150, 0, 0.05);
|
||||
}
|
||||
|
||||
/* ── Error ──────────────────────────────────────────────── */
|
||||
.error-msg {
|
||||
padding: 10px 14px;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ interface BodyCacheEntry {
|
|||
expiresAt: number
|
||||
}
|
||||
|
||||
const BODY_CACHE_MAX = 100
|
||||
const bodyCache = new Map<string, BodyCacheEntry>()
|
||||
|
||||
function getCachedBody(key: string): MessageBody | null {
|
||||
|
|
@ -22,10 +23,18 @@ function getCachedBody(key: string): MessageBody | null {
|
|||
bodyCache.delete(key)
|
||||
return null
|
||||
}
|
||||
// Обновляем порядок для LRU
|
||||
bodyCache.delete(key)
|
||||
bodyCache.set(key, entry)
|
||||
return entry.body
|
||||
}
|
||||
|
||||
function setCachedBody(key: string, body: MessageBody): void {
|
||||
// Вытесняем самую старую запись при превышении лимита
|
||||
if (bodyCache.size >= BODY_CACHE_MAX) {
|
||||
const oldest = bodyCache.keys().next().value
|
||||
if (oldest !== undefined) bodyCache.delete(oldest)
|
||||
}
|
||||
bodyCache.set(key, { body, expiresAt: Date.now() + BODY_CACHE_TTL })
|
||||
}
|
||||
|
||||
|
|
@ -66,8 +75,8 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
if (!prev) return
|
||||
|
||||
const arrived = fresh.filter(m => !prev.has(m.id) && !m.flags.seen)
|
||||
for (const envelope of arrived) {
|
||||
newArrivals.value = [{ accountId, folderId, envelope }]
|
||||
if (arrived.length > 0) {
|
||||
newArrivals.value = arrived.map(envelope => ({ accountId, folderId, envelope }))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ export interface ImapCredentials {
|
|||
smtpHost?: string
|
||||
smtpPort?: number
|
||||
smtpSecure?: boolean
|
||||
// Разрешить самоподписанные сертификаты — только для корпоративных серверов
|
||||
smtpAllowSelfSigned?: boolean
|
||||
}
|
||||
|
||||
export interface ExchangeCredentials {
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ export interface IpcChannelMap {
|
|||
'compose:pickFiles': [void, { path: string; filename: string; size: number }[]]
|
||||
|
||||
'app:setZoom': [{ factor: number }, void]
|
||||
'app:isEncryptionAvailable': [void, boolean]
|
||||
}
|
||||
|
||||
export interface IpcEventMap {
|
||||
|
|
|
|||
Loading…
Reference in a new issue