Implemented desktop OAuth2 account setup for Google and Microsoft. The flow uses the system browser and PKCE; access and refresh tokens stay in the main process and encrypted account store. OAuth connections use fixed provider endpoints, and existing password-based accounts remain supported. Android remains password-based in this phase.
This commit is contained in:
+24
-4
@@ -16,6 +16,8 @@ function registerMailIpcHandlers(dependencies) {
|
||||
publicAccount,
|
||||
normalizeAccount,
|
||||
connectMail,
|
||||
authorizeOAuthAccount,
|
||||
listOAuthProviders,
|
||||
requestBackgroundSync,
|
||||
CUSTOM_FOLDER_PREFIX,
|
||||
flushMailOutbox,
|
||||
@@ -49,6 +51,8 @@ registerIpcHandler('mail:list-accounts', async () => {
|
||||
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||
});
|
||||
|
||||
registerIpcHandler('mail:list-oauth-providers', async () => listOAuthProviders());
|
||||
|
||||
registerIpcHandler('mail:select-account', async (_event, accountId) => {
|
||||
const account = await updateAccountStore(store => {
|
||||
const selected = store.accounts.find(item => item.id === accountId);
|
||||
@@ -74,8 +78,23 @@ registerIpcHandler('mail:remove-account', async (_event, accountId) => {
|
||||
registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
||||
const existing = await readAccount(accountId);
|
||||
if (!existing) throw new Error('That mail account is no longer available.');
|
||||
const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password });
|
||||
let account = normalizeAccount({
|
||||
...existing,
|
||||
...input,
|
||||
authMethod: input?.authMethod || existing.authMethod || 'password',
|
||||
password: String(input?.password || '') || existing.password || ''
|
||||
});
|
||||
account.id = existing.id;
|
||||
if (account.authMethod === 'oauth2') {
|
||||
if (!input?.reauthorizeOAuth && existing.authMethod === 'oauth2' && existing.oauthProvider === account.oauthProvider && existing.oauthRefreshToken) {
|
||||
account.oauthAccessToken = existing.oauthAccessToken;
|
||||
account.oauthRefreshToken = existing.oauthRefreshToken;
|
||||
account.oauthAccessTokenExpiresAt = existing.oauthAccessTokenExpiresAt;
|
||||
} else {
|
||||
account = await authorizeOAuthAccount(account);
|
||||
account.id = existing.id;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const status = await connectMail(account);
|
||||
const savedAccount = await updateAccountStore(store => {
|
||||
@@ -100,8 +119,9 @@ registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
||||
});
|
||||
|
||||
registerIpcHandler('mail:connect', async (_event, input) => {
|
||||
const account = normalizeAccount(input);
|
||||
let account = normalizeAccount(input);
|
||||
try {
|
||||
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
|
||||
const status = await connectMail(account);
|
||||
const saved = await saveAccount(account);
|
||||
requestBackgroundSync(saved.id);
|
||||
@@ -133,7 +153,7 @@ registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset =
|
||||
registerIpcHandler('mail:list-folders', async () => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before listing folders.');
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
return { folders: await listCustomFolders(client) };
|
||||
@@ -149,7 +169,7 @@ registerIpcHandler('mail:create-folder', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before creating folders.');
|
||||
const name = validFolderName(input?.name);
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const existing = await client.list();
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ function registerPgpIpcHandlers({
|
||||
}) {
|
||||
async function fetchMessageSource(account, folder, uid) {
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
|
||||
+34
-9
@@ -5,14 +5,32 @@ const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'tr
|
||||
|
||||
function normalizeAccount(input, { createId = randomUUID } = {}) {
|
||||
const email = String(input?.email || '').trim();
|
||||
const password = String(input?.password || '');
|
||||
const imapHost = String(input?.imapHost || '').trim();
|
||||
const smtpHost = String(input?.smtpHost || '').trim();
|
||||
const authMethod = input?.authMethod === undefined ? 'password' : String(input.authMethod);
|
||||
if (!['password', 'oauth2'].includes(authMethod)) throw new Error('Choose a supported sign-in method.');
|
||||
const oauthProvider = authMethod === 'oauth2' ? String(input?.oauthProvider || '') : '';
|
||||
if (authMethod === 'oauth2' && !['google', 'microsoft'].includes(oauthProvider)) {
|
||||
throw new Error('Choose Google or Microsoft OAuth2 sign-in.');
|
||||
}
|
||||
const providerDefaults = oauthProvider === 'google'
|
||||
? { imapHost: 'imap.gmail.com', smtpHost: 'smtp.gmail.com', imapPort: 993, smtpPort: 587, imapSecure: true }
|
||||
: oauthProvider === 'microsoft'
|
||||
? { imapHost: 'outlook.office365.com', smtpHost: 'smtp.office365.com', imapPort: 993, smtpPort: 587, imapSecure: true }
|
||||
: { imapHost: '', smtpHost: '', imapPort: 143, smtpPort: 587, imapSecure: false };
|
||||
const password = authMethod === 'password' ? String(input?.password || '') : '';
|
||||
const imapHost = String(oauthProvider ? providerDefaults.imapHost : input?.imapHost || providerDefaults.imapHost).trim();
|
||||
const smtpHost = String(oauthProvider ? providerDefaults.smtpHost : input?.smtpHost || providerDefaults.smtpHost).trim();
|
||||
const displayName = String(input?.displayName || '').trim().slice(0, 80);
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
|
||||
throw new Error('Enter a valid email, password, and both mail server names.');
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !imapHost || !smtpHost || (authMethod === 'password' && !password)) {
|
||||
throw new Error(authMethod === 'password'
|
||||
? 'Enter a valid email, password, and both mail server names.'
|
||||
: 'Enter a valid email and supported OAuth mail servers.');
|
||||
}
|
||||
if (!displayName) throw new Error('Enter a display name for this mail account.');
|
||||
const imapPort = Number(oauthProvider ? providerDefaults.imapPort : input?.imapPort ?? providerDefaults.imapPort);
|
||||
const smtpPort = Number(oauthProvider ? providerDefaults.smtpPort : input?.smtpPort ?? providerDefaults.smtpPort);
|
||||
if (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535)) {
|
||||
throw new Error('Enter valid IMAP and SMTP ports.');
|
||||
}
|
||||
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
|
||||
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
|
||||
throw new Error('Choose a supported mailbox sync interval.');
|
||||
@@ -36,13 +54,14 @@ function normalizeAccount(input, { createId = randomUUID } = {}) {
|
||||
return { id: String(rule.id || createId()), senderContains, subjectContains, action, value };
|
||||
});
|
||||
return {
|
||||
email, password, displayName, imapHost, smtpHost,
|
||||
email, password, authMethod, oauthProvider: oauthProvider || null,
|
||||
displayName, imapHost, smtpHost, imapPort, smtpPort,
|
||||
imapSecure: oauthProvider ? providerDefaults.imapSecure : input?.imapSecure === undefined ? providerDefaults.imapSecure : Boolean(input.imapSecure),
|
||||
smtpSecure: oauthProvider ? false : input?.smtpSecure === undefined ? false : Boolean(input.smtpSecure),
|
||||
signature: String(input?.signature || '').slice(0, 5000),
|
||||
notificationsEnabled: input?.notificationsEnabled !== false,
|
||||
syncIntervalMinutes,
|
||||
rules,
|
||||
imapPort: 143,
|
||||
smtpPort: 587
|
||||
rules
|
||||
};
|
||||
}
|
||||
|
||||
@@ -51,8 +70,14 @@ function publicAccount(account) {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
displayName: account.displayName || '',
|
||||
authMethod: account.authMethod === 'oauth2' ? 'oauth2' : 'password',
|
||||
oauthProvider: account.authMethod === 'oauth2' ? account.oauthProvider || null : null,
|
||||
imapHost: account.imapHost,
|
||||
smtpHost: account.smtpHost,
|
||||
imapPort: Number(account.imapPort) || (account.authMethod === 'oauth2' ? 993 : 143),
|
||||
smtpPort: Number(account.smtpPort) || 587,
|
||||
imapSecure: Boolean(account.imapSecure),
|
||||
smtpSecure: Boolean(account.smtpSecure),
|
||||
signature: account.signature || '',
|
||||
notificationsEnabled: account.notificationsEnabled !== false,
|
||||
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
|
||||
|
||||
@@ -5,7 +5,7 @@ function createMessageActionService({ imapClient, folderPath, findSpecialMailbox
|
||||
const action = String(input?.action || '');
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const sourcePath = await folderPath(client, folder);
|
||||
|
||||
@@ -7,7 +7,7 @@ function createAttachmentService({ imapClient, folderPath, parseForAttachments,
|
||||
const filename = String(input?.filename || 'attachment');
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
function createMailConnections({ ImapFlow, createTransport, oauthTokenManager }) {
|
||||
async function imapClient(account, options = {}) {
|
||||
const isOAuth = account.authMethod === 'oauth2';
|
||||
const auth = isOAuth
|
||||
? { user: account.email, accessToken: await oauthTokenManager.getAccessToken(account) }
|
||||
: { user: account.email, pass: account.password };
|
||||
return new ImapFlow({
|
||||
host: account.imapHost,
|
||||
port: account.imapPort,
|
||||
secure: Boolean(account.imapSecure),
|
||||
doSTARTTLS: !account.imapSecure,
|
||||
auth,
|
||||
tls: { rejectUnauthorized: true },
|
||||
logger: false,
|
||||
connectionTimeout: 15000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000,
|
||||
...options
|
||||
});
|
||||
}
|
||||
|
||||
async function smtpTransport(account) {
|
||||
const isOAuth = account.authMethod === 'oauth2';
|
||||
const auth = isOAuth
|
||||
? {
|
||||
type: 'OAuth2',
|
||||
user: account.email,
|
||||
accessToken: await oauthTokenManager.getAccessToken(account),
|
||||
expires: account.oauthAccessTokenExpiresAt
|
||||
}
|
||||
: { user: account.email, pass: account.password };
|
||||
const secure = Boolean(account.smtpSecure);
|
||||
return createTransport({
|
||||
host: account.smtpHost,
|
||||
port: account.smtpPort,
|
||||
secure,
|
||||
requireTLS: !secure,
|
||||
auth,
|
||||
tls: { rejectUnauthorized: true, servername: account.smtpHost },
|
||||
connectionTimeout: 15000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000
|
||||
});
|
||||
}
|
||||
|
||||
return Object.freeze({ imapClient, smtpTransport });
|
||||
}
|
||||
|
||||
module.exports = { createMailConnections };
|
||||
@@ -45,7 +45,7 @@ function createIdleWatcherManager({
|
||||
try {
|
||||
const account = await readAccount(accountId);
|
||||
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||
client = imapClient(account, {
|
||||
client = await imapClient(account, {
|
||||
autoIdleDelay: 10_000,
|
||||
maxIdleTime: 25 * 60 * 1000,
|
||||
socketTimeout: 30 * 60 * 1000
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
function createOAuthTokenManager({ oauth2Service, persistTokens, now = Date.now }) {
|
||||
const refreshOperations = new Map();
|
||||
|
||||
async function getAccessToken(account) {
|
||||
if (account?.authMethod !== 'oauth2') throw new Error('This account does not use OAuth2.');
|
||||
if (account.oauthAccessToken && Number(account.oauthAccessTokenExpiresAt) > now() + 60_000) {
|
||||
return account.oauthAccessToken;
|
||||
}
|
||||
if (!account.oauthRefreshToken) {
|
||||
throw new Error('Reconnect this OAuth2 account to continue.');
|
||||
}
|
||||
|
||||
const key = String(account.id || `${account.oauthProvider}:${account.email}`);
|
||||
let pending = refreshOperations.get(key);
|
||||
if (!pending) {
|
||||
pending = (async () => {
|
||||
const tokens = await oauth2Service.refresh(account.oauthProvider, account.oauthRefreshToken);
|
||||
await persistTokens(account.id, tokens);
|
||||
return tokens;
|
||||
})();
|
||||
refreshOperations.set(key, pending);
|
||||
pending.finally(() => {
|
||||
if (refreshOperations.get(key) === pending) refreshOperations.delete(key);
|
||||
}).catch(() => {});
|
||||
}
|
||||
const tokens = await pending;
|
||||
Object.assign(account, tokens);
|
||||
return tokens.oauthAccessToken;
|
||||
}
|
||||
|
||||
return Object.freeze({ getAccessToken });
|
||||
}
|
||||
|
||||
module.exports = { createOAuthTokenManager };
|
||||
@@ -0,0 +1,212 @@
|
||||
const { createHash, randomBytes, timingSafeEqual } = require('node:crypto');
|
||||
const http = require('node:http');
|
||||
|
||||
const GOOGLE_SCOPE = 'https://mail.google.com/';
|
||||
const MICROSOFT_SCOPES = [
|
||||
'offline_access',
|
||||
'https://outlook.office.com/IMAP.AccessAsUser.All',
|
||||
'https://outlook.office.com/SMTP.Send'
|
||||
].join(' ');
|
||||
|
||||
function loadOAuthProviderConfig(environment = process.env) {
|
||||
const googleClientId = String(environment.EP_MAIL_GOOGLE_OAUTH_CLIENT_ID || '').trim();
|
||||
const microsoftClientId = String(environment.EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID || '').trim();
|
||||
const microsoftTenant = String(environment.EP_MAIL_MICROSOFT_OAUTH_TENANT_ID || 'common').trim();
|
||||
if (microsoftTenant && !/^(?:common|organizations|consumers|[a-f0-9-]{36})$/i.test(microsoftTenant)) {
|
||||
throw new Error('The Microsoft OAuth tenant ID is invalid.');
|
||||
}
|
||||
return {
|
||||
...(googleClientId ? {
|
||||
google: {
|
||||
clientId: googleClientId,
|
||||
clientSecret: String(environment.EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET || '').trim(),
|
||||
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
|
||||
tokenEndpoint: 'https://oauth2.googleapis.com/token',
|
||||
scope: GOOGLE_SCOPE,
|
||||
redirectHost: 'localhost'
|
||||
}
|
||||
} : {}),
|
||||
...(microsoftClientId ? {
|
||||
microsoft: {
|
||||
clientId: microsoftClientId,
|
||||
tenant: microsoftTenant || 'common',
|
||||
authorizationEndpoint: `https://login.microsoftonline.com/${microsoftTenant || 'common'}/oauth2/v2.0/authorize`,
|
||||
tokenEndpoint: `https://login.microsoftonline.com/${microsoftTenant || 'common'}/oauth2/v2.0/token`,
|
||||
scope: MICROSOFT_SCOPES,
|
||||
redirectHost: 'localhost'
|
||||
}
|
||||
} : {})
|
||||
};
|
||||
}
|
||||
|
||||
function createOAuth2Service({
|
||||
providers,
|
||||
openExternal,
|
||||
fetchImpl = globalThis.fetch,
|
||||
createServer = http.createServer,
|
||||
timeoutMs = 3 * 60 * 1000
|
||||
}) {
|
||||
function listProviders() {
|
||||
return [
|
||||
{ id: 'google', label: 'Google', configured: Boolean(providers.google?.clientId) },
|
||||
{ id: 'microsoft', label: 'Microsoft', configured: Boolean(providers.microsoft?.clientId) }
|
||||
];
|
||||
}
|
||||
|
||||
function providerConfig(provider) {
|
||||
const config = providers[provider];
|
||||
if (!['google', 'microsoft'].includes(provider) || !config?.clientId) {
|
||||
throw new Error(`OAuth2 sign-in for ${provider} is not configured on this desktop build.`);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
async function requestTokens(config, parameters) {
|
||||
const body = new URLSearchParams({ client_id: config.clientId, ...parameters });
|
||||
if (config.clientSecret) body.set('client_secret', config.clientSecret);
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(config.tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
redirect: 'error'
|
||||
});
|
||||
} catch {
|
||||
throw new Error('Could not contact the OAuth2 provider. Check your network and try again.');
|
||||
}
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const detail = String(data.error_description || data.error || '').slice(0, 240).replace(/\s+/g, ' ');
|
||||
throw new Error(detail ? `OAuth2 sign-in failed: ${detail}` : 'OAuth2 sign-in failed. Try again.');
|
||||
}
|
||||
if (typeof data.access_token !== 'string' || !data.access_token || !Number.isFinite(Number(data.expires_in))) {
|
||||
throw new Error('The OAuth2 provider returned an invalid token response.');
|
||||
}
|
||||
return {
|
||||
oauthAccessToken: data.access_token,
|
||||
oauthRefreshToken: typeof data.refresh_token === 'string' && data.refresh_token
|
||||
? data.refresh_token : parameters.refresh_token || '',
|
||||
oauthAccessTokenExpiresAt: Date.now() + Math.max(0, Number(data.expires_in)) * 1000
|
||||
};
|
||||
}
|
||||
|
||||
async function authorize(provider, email) {
|
||||
const config = providerConfig(provider);
|
||||
if (typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
||||
throw new Error('Enter a valid email address before authorizing OAuth2.');
|
||||
}
|
||||
if (typeof openExternal !== 'function' || typeof fetchImpl !== 'function') {
|
||||
throw new Error('Desktop OAuth2 sign-in is unavailable.');
|
||||
}
|
||||
|
||||
const state = randomBytes(32).toString('base64url');
|
||||
const verifier = randomBytes(48).toString('base64url');
|
||||
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
||||
let settleCallback;
|
||||
let callbackComplete = false;
|
||||
const callback = new Promise((resolve, reject) => {
|
||||
settleCallback = { resolve, reject };
|
||||
});
|
||||
callback.catch(() => {});
|
||||
const server = createServer((request, response) => {
|
||||
if (request.method !== 'GET') {
|
||||
response.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' }).end('Method not allowed');
|
||||
return;
|
||||
}
|
||||
const callbackUrl = new URL(request.url || '/', 'http://localhost');
|
||||
if (callbackUrl.pathname !== '/') {
|
||||
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found');
|
||||
return;
|
||||
}
|
||||
const returnedState = callbackUrl.searchParams.get('state') || '';
|
||||
const expected = Buffer.from(state);
|
||||
const received = Buffer.from(returnedState);
|
||||
if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
|
||||
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('OAuth2 state validation failed. You can close this window.');
|
||||
if (!callbackComplete) {
|
||||
callbackComplete = true;
|
||||
settleCallback.reject(new Error('OAuth2 state validation failed. Please try again.'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const error = callbackUrl.searchParams.get('error');
|
||||
if (error) {
|
||||
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('Sign-in was not completed. You can close this window.');
|
||||
if (!callbackComplete) {
|
||||
callbackComplete = true;
|
||||
settleCallback.reject(new Error('OAuth2 authorization was cancelled or denied.'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const code = callbackUrl.searchParams.get('code');
|
||||
if (!code) {
|
||||
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('The authorization response was incomplete. You can close this window.');
|
||||
return;
|
||||
}
|
||||
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
||||
.end('<!doctype html><title>ep-mail</title><p>Sign-in complete. You may close this browser window and return to ep-mail.</p>');
|
||||
if (!callbackComplete) {
|
||||
callbackComplete = true;
|
||||
settleCallback.resolve(code);
|
||||
}
|
||||
});
|
||||
let timeout;
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, 'localhost', resolve);
|
||||
});
|
||||
const port = server.address().port;
|
||||
const redirectUri = `http://${config.redirectHost}:${port}`;
|
||||
const authorizationUrl = new URL(config.authorizationEndpoint);
|
||||
authorizationUrl.search = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: redirectUri,
|
||||
response_type: 'code',
|
||||
response_mode: 'query',
|
||||
scope: config.scope,
|
||||
state,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: 'S256',
|
||||
login_hint: email,
|
||||
...(provider === 'google' ? { access_type: 'offline', prompt: 'consent' } : {})
|
||||
}).toString();
|
||||
timeout = setTimeout(() => {
|
||||
if (!callbackComplete) {
|
||||
callbackComplete = true;
|
||||
settleCallback.reject(new Error('OAuth2 sign-in timed out. Try again.'));
|
||||
}
|
||||
}, timeoutMs);
|
||||
await openExternal(authorizationUrl.href);
|
||||
const code = await callback;
|
||||
return await requestTokens(config, {
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: verifier,
|
||||
scope: config.scope
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
await new Promise(resolve => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh(provider, refreshToken) {
|
||||
const config = providerConfig(provider);
|
||||
if (typeof refreshToken !== 'string' || !refreshToken) {
|
||||
throw new Error(`Reconnect this ${provider === 'google' ? 'Google' : 'Microsoft'} account to continue.`);
|
||||
}
|
||||
return requestTokens(config, {
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
scope: config.scope
|
||||
});
|
||||
}
|
||||
|
||||
return Object.freeze({ listProviders, authorize, refresh });
|
||||
}
|
||||
|
||||
module.exports = { createOAuth2Service, loadOAuthProviderConfig };
|
||||
@@ -8,7 +8,7 @@ function createMailReader({
|
||||
}) {
|
||||
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
|
||||
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
|
||||
@@ -7,7 +7,7 @@ function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTr
|
||||
const to = String(message?.to || '').trim();
|
||||
if (!to) throw new Error('Add at least one recipient.');
|
||||
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
||||
const transport = smtpTransport(account);
|
||||
const transport = await smtpTransport(account);
|
||||
const sentMessageId = String(message.messageId || `<${randomUUID()}@ep-mail.local>`);
|
||||
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||
const body = String(message?.text || '').slice(0, 500000);
|
||||
@@ -37,7 +37,7 @@ function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTr
|
||||
const copy = createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
|
||||
try {
|
||||
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const sentPath = await findSentMailbox(client, true);
|
||||
|
||||
@@ -25,7 +25,7 @@ function createMailboxSyncService({
|
||||
async function syncAccountMailboxes(account) {
|
||||
await flushMailOutbox(account);
|
||||
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxes = await client.list();
|
||||
|
||||
+36
-32
@@ -32,6 +32,9 @@ const { createMailboxSyncService } = require('./mail/sync-service.cjs');
|
||||
const { createBackgroundSyncCoordinator } = require('./mail/sync-coordinator.cjs');
|
||||
const { createIdleWatcherManager } = require('./mail/idle-watcher-manager.cjs');
|
||||
const { createSnoozeReminderService } = require('./mail/snooze-reminder-service.cjs');
|
||||
const { createOAuth2Service, loadOAuthProviderConfig } = require('./mail/oauth2-service.cjs');
|
||||
const { createOAuthTokenManager } = require('./mail/oauth-token-manager.cjs');
|
||||
const { createMailConnections } = require('./mail/connection-factory.cjs');
|
||||
const { isConnectivityFailure } = require('./mail/connectivity.cjs');
|
||||
const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs');
|
||||
const { validateIpcArguments } = require('./security/ipc-arguments.cjs');
|
||||
@@ -98,6 +101,29 @@ function updateAccountStore(update) {
|
||||
return operation;
|
||||
}
|
||||
|
||||
const oauth2Service = createOAuth2Service({
|
||||
providers: loadOAuthProviderConfig(),
|
||||
openExternal: url => shell.openExternal(url)
|
||||
});
|
||||
const oauthTokenManager = createOAuthTokenManager({
|
||||
oauth2Service,
|
||||
async persistTokens(accountId, tokens) {
|
||||
if (!accountId) return;
|
||||
await updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
if (account?.authMethod === 'oauth2') Object.assign(account, tokens);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
async function authorizeOAuthAccount(account) {
|
||||
return { ...account, ...await oauth2Service.authorize(account.oauthProvider, account.email) };
|
||||
}
|
||||
|
||||
function listOAuthProviders() {
|
||||
return oauth2Service.listProviders();
|
||||
}
|
||||
|
||||
function sendMailSyncUpdate(update) {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
|
||||
@@ -170,35 +196,11 @@ function activeDavConfig(store, type, id = null) {
|
||||
return store[key].find(item => item.id === (id || store[activeKey])) || null;
|
||||
}
|
||||
|
||||
function imapClient(account, options = {}) {
|
||||
return new ImapFlow({
|
||||
host: account.imapHost,
|
||||
port: account.imapPort,
|
||||
secure: false,
|
||||
doSTARTTLS: true,
|
||||
auth: { user: account.email, pass: account.password },
|
||||
tls: { rejectUnauthorized: true },
|
||||
logger: false,
|
||||
connectionTimeout: 15000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000,
|
||||
...options
|
||||
});
|
||||
}
|
||||
|
||||
function smtpTransport(account) {
|
||||
return nodemailer.createTransport({
|
||||
host: account.smtpHost,
|
||||
port: account.smtpPort,
|
||||
secure: false,
|
||||
requireTLS: true,
|
||||
auth: { user: account.email, pass: account.password },
|
||||
tls: { rejectUnauthorized: true, servername: account.smtpHost },
|
||||
connectionTimeout: 15000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000
|
||||
});
|
||||
}
|
||||
const { imapClient, smtpTransport } = createMailConnections({
|
||||
ImapFlow,
|
||||
createTransport: nodemailer.createTransport,
|
||||
oauthTokenManager
|
||||
});
|
||||
|
||||
function assertSecureStorage() {
|
||||
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
||||
@@ -235,12 +237,12 @@ async function saveAccount(account) {
|
||||
}
|
||||
|
||||
async function connectMail(account) {
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
let transport;
|
||||
try {
|
||||
await client.connect();
|
||||
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
||||
transport = smtpTransport(account);
|
||||
transport = await smtpTransport(account);
|
||||
await transport.verify();
|
||||
return { mailbox: mailbox.name, messages: mailbox.exists };
|
||||
} finally {
|
||||
@@ -317,7 +319,7 @@ async function fetchSnoozedMailbox(account, offset, limit) {
|
||||
.filter(item => Number(item.dueAt) > now)
|
||||
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
||||
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||
const client = imapClient(account);
|
||||
const client = await imapClient(account);
|
||||
const messages = [];
|
||||
try {
|
||||
await client.connect();
|
||||
@@ -462,6 +464,8 @@ registerMailIpcHandlers({
|
||||
publicAccount,
|
||||
normalizeAccount,
|
||||
connectMail,
|
||||
authorizeOAuthAccount,
|
||||
listOAuthProviders,
|
||||
requestBackgroundSync,
|
||||
CUSTOM_FOLDER_PREFIX,
|
||||
flushMailOutbox,
|
||||
|
||||
@@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
|
||||
getAccount: () => ipcRenderer.invoke('mail:get-account'),
|
||||
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
|
||||
listOAuthProviders: () => ipcRenderer.invoke('mail:list-oauth-providers'),
|
||||
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
|
||||
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
|
||||
connect: details => ipcRenderer.invoke('mail:connect', details),
|
||||
|
||||
@@ -31,13 +31,18 @@ const davRemoteFields = {
|
||||
};
|
||||
|
||||
const objectFieldSchemas = {
|
||||
'mail:update-account': [{
|
||||
'mail:update-account': [null, {
|
||||
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
||||
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
|
||||
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
|
||||
reauthorizeOAuth: bool(),
|
||||
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
|
||||
rules: array(record(ruleFields), 50)
|
||||
}],
|
||||
'mail:connect': [{
|
||||
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
||||
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
|
||||
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
|
||||
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
|
||||
rules: array(record(ruleFields), 50)
|
||||
}],
|
||||
@@ -116,6 +121,7 @@ const schemas = {
|
||||
'app:get-version': [],
|
||||
'mail:get-account': [],
|
||||
'mail:list-accounts': [],
|
||||
'mail:list-oauth-providers': [],
|
||||
'mail:select-account': ['string'],
|
||||
'mail:remove-account': ['string'],
|
||||
'mail:update-account': ['string', 'object'],
|
||||
|
||||
Reference in New Issue
Block a user