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:
+1
-1
@@ -34,7 +34,7 @@ The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.c
|
|||||||
|
|
||||||
The main process owns the canonical account model and persists it in an encrypted store:
|
The main process owns the canonical account model and persists it in an encrypted store:
|
||||||
|
|
||||||
- `mail-account.enc` stores connected IMAP/SMTP accounts and their settings.
|
- `mail-account.enc` stores connected IMAP/SMTP accounts, settings, and desktop OAuth tokens; OAuth refresh tokens never enter the renderer API.
|
||||||
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
|
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
|
||||||
- `pgp-keys.enc` stores OpenPGP keys and trust data.
|
- `pgp-keys.enc` stores OpenPGP keys and trust data.
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ The Electron app runs in its own window. On Windows, ep-mail also shows its icon
|
|||||||
|
|
||||||
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
||||||
|
|
||||||
|
### Google and Microsoft OAuth2
|
||||||
|
|
||||||
|
Desktop account setup supports Google and Microsoft OAuth2 when provider client configuration is supplied to the Electron process. Set `EP_MAIL_GOOGLE_OAUTH_CLIENT_ID` (and `EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET` if issued for the desktop client) and/or `EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID`; `EP_MAIL_MICROSOFT_OAUTH_TENANT_ID` is optional and defaults to `common`. Register the corresponding native/desktop public client with a loopback redirect URI. Microsoft app registrations must allow public-client authorization and delegated IMAP/SMTP permissions. Google's full Gmail mail scope is restricted; production use may require app verification, and unverified projects may need the account added as a test user. OAuth sign-in opens the system browser, uses PKCE, and stores refresh/access tokens only in the encrypted account store. Android continues to use its existing password-based account setup.
|
||||||
|
|
||||||
On packaged Windows builds, startup repairs an existing per-user Start Menu shortcut to point to the launched installed or portable executable and use its icon and AppUserModelID. Windows may keep a cached icon for an existing taskbar pin; if so, unpin and pin ep-mail again after launching the updated build.
|
On packaged Windows builds, startup repairs an existing per-user Start Menu shortcut to point to the launched installed or portable executable and use its icon and AppUserModelID. Windows may keep a cached icon for an existing taskbar pin; if so, unpin and pin ep-mail again after launching the updated build.
|
||||||
|
|
||||||
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
||||||
|
|||||||
+2
-1
@@ -171,7 +171,7 @@ IPC modules should validate and translate renderer requests, then call services.
|
|||||||
- Electron Builder and the desktop Actions artifact name derive from `package.json`.
|
- Electron Builder and the desktop Actions artifact name derive from `package.json`.
|
||||||
- Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions.
|
- Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions.
|
||||||
- `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump.
|
- `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump.
|
||||||
- Latest version check: `package.json` and both lockfile version fields are `0.4.38`; Android derives `versionName 0.4.38` and `versionCode 438`. The user confirms the previous artifact works; this bump is for the next build.
|
- Latest version check: `package.json` and both lockfile version fields are `0.4.39`; Android derives `versionName 0.4.39` and `versionCode 439`. OAuth2 desktop support is in this source version; the artifact still needs to be built and verified.
|
||||||
|
|
||||||
## Progress log
|
## Progress log
|
||||||
|
|
||||||
@@ -212,6 +212,7 @@ IPC modules should validate and translate renderer requests, then call services.
|
|||||||
- Step 6 at version `0.4.36` consolidates the HTML sanitization and remote-image policy API under `window.epMailFeatures.contentSecurity`.
|
- Step 6 at version `0.4.36` consolidates the HTML sanitization and remote-image policy API under `window.epMailFeatures.contentSecurity`.
|
||||||
- Step 7 at version `0.4.37` adds focused sanitizer coverage for dangerous DOM nodes/attributes and verifies that remote images remain data-only pending explicit loading.
|
- Step 7 at version `0.4.37` adds focused sanitizer coverage for dangerous DOM nodes/attributes and verifies that remote images remain data-only pending explicit loading.
|
||||||
- Step 7 at version `0.4.38` tests main-process native confirmation for OpenPGP key replacement and trust elevation; cancellation must not mutate stored key state.
|
- Step 7 at version `0.4.38` tests main-process native confirmation for OpenPGP key replacement and trust elevation; cancellation must not mutate stored key state.
|
||||||
|
- Desktop OAuth2 support for Google and Microsoft was added after the `0.4.38` artifact; `0.4.39` uses configurable OAuth client IDs, PKCE, encrypted token persistence, and provider-fixed mail endpoints.
|
||||||
- Step 7 coverage status: sanitizer/remote-image, DAV reference/ETag, and OpenPGP trust/replacement paths have regression coverage. A direct plaintext-send IPC confirmation test and the documented human/security review remain open.
|
- Step 7 coverage status: sanitizer/remote-image, DAV reference/ETag, and OpenPGP trust/replacement paths have regression coverage. A direct plaintext-send IPC confirmation test and the documented human/security review remain open.
|
||||||
- Renderer modularization step 6 is complete: feature modules are scoped, legacy renderer-state aliases are removed, public cross-feature interfaces are namespaced, and root/`www/` parity plus classic-script ordering are tested. Native ES module conversion remains a deferred follow-up.
|
- Renderer modularization step 6 is complete: feature modules are scoped, legacy renderer-state aliases are removed, public cross-feature interfaces are namespaced, and root/`www/` parity plus classic-script ordering are tested. Native ES module conversion remains a deferred follow-up.
|
||||||
- The current IPC/DAV validation changes pass the full suite: 108 tests.
|
- The current IPC/DAV validation changes pass the full suite: 108 tests.
|
||||||
|
|||||||
@@ -49,7 +49,7 @@
|
|||||||
|
|
||||||
## Account settings
|
## Account settings
|
||||||
|
|
||||||
- [ ] Add OAuth2 account setup for Google and Microsoft mail accounts.
|
- [x] Add desktop OAuth2 account setup for Google and Microsoft. Configure provider client IDs with the environment variables documented in `README.md`; Android remains password-based.
|
||||||
- [ ] Fix the mailbox space indicator; it is not working.
|
- [ ] Fix the mailbox space indicator; it is not working.
|
||||||
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
||||||
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
||||||
|
|||||||
+24
-4
@@ -16,6 +16,8 @@ function registerMailIpcHandlers(dependencies) {
|
|||||||
publicAccount,
|
publicAccount,
|
||||||
normalizeAccount,
|
normalizeAccount,
|
||||||
connectMail,
|
connectMail,
|
||||||
|
authorizeOAuthAccount,
|
||||||
|
listOAuthProviders,
|
||||||
requestBackgroundSync,
|
requestBackgroundSync,
|
||||||
CUSTOM_FOLDER_PREFIX,
|
CUSTOM_FOLDER_PREFIX,
|
||||||
flushMailOutbox,
|
flushMailOutbox,
|
||||||
@@ -49,6 +51,8 @@ registerIpcHandler('mail:list-accounts', async () => {
|
|||||||
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:list-oauth-providers', async () => listOAuthProviders());
|
||||||
|
|
||||||
registerIpcHandler('mail:select-account', async (_event, accountId) => {
|
registerIpcHandler('mail:select-account', async (_event, accountId) => {
|
||||||
const account = await updateAccountStore(store => {
|
const account = await updateAccountStore(store => {
|
||||||
const selected = store.accounts.find(item => item.id === accountId);
|
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) => {
|
registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
||||||
const existing = await readAccount(accountId);
|
const existing = await readAccount(accountId);
|
||||||
if (!existing) throw new Error('That mail account is no longer available.');
|
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;
|
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 {
|
try {
|
||||||
const status = await connectMail(account);
|
const status = await connectMail(account);
|
||||||
const savedAccount = await updateAccountStore(store => {
|
const savedAccount = await updateAccountStore(store => {
|
||||||
@@ -100,8 +119,9 @@ registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:connect', async (_event, input) => {
|
registerIpcHandler('mail:connect', async (_event, input) => {
|
||||||
const account = normalizeAccount(input);
|
let account = normalizeAccount(input);
|
||||||
try {
|
try {
|
||||||
|
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
|
||||||
const status = await connectMail(account);
|
const status = await connectMail(account);
|
||||||
const saved = await saveAccount(account);
|
const saved = await saveAccount(account);
|
||||||
requestBackgroundSync(saved.id);
|
requestBackgroundSync(saved.id);
|
||||||
@@ -133,7 +153,7 @@ registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset =
|
|||||||
registerIpcHandler('mail:list-folders', async () => {
|
registerIpcHandler('mail:list-folders', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before listing folders.');
|
if (!account) throw new Error('Add a mail account before listing folders.');
|
||||||
const client = imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
return { folders: await listCustomFolders(client) };
|
return { folders: await listCustomFolders(client) };
|
||||||
@@ -149,7 +169,7 @@ registerIpcHandler('mail:create-folder', async (_event, input) => {
|
|||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before creating folders.');
|
if (!account) throw new Error('Add a mail account before creating folders.');
|
||||||
const name = validFolderName(input?.name);
|
const name = validFolderName(input?.name);
|
||||||
const client = imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const existing = await client.list();
|
const existing = await client.list();
|
||||||
|
|||||||
+1
-1
@@ -32,7 +32,7 @@ function registerPgpIpcHandlers({
|
|||||||
}) {
|
}) {
|
||||||
async function fetchMessageSource(account, folder, uid) {
|
async function fetchMessageSource(account, folder, uid) {
|
||||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
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 {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailboxPath = await folderPath(client, folder);
|
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 } = {}) {
|
function normalizeAccount(input, { createId = randomUUID } = {}) {
|
||||||
const email = String(input?.email || '').trim();
|
const email = String(input?.email || '').trim();
|
||||||
const password = String(input?.password || '');
|
const authMethod = input?.authMethod === undefined ? 'password' : String(input.authMethod);
|
||||||
const imapHost = String(input?.imapHost || '').trim();
|
if (!['password', 'oauth2'].includes(authMethod)) throw new Error('Choose a supported sign-in method.');
|
||||||
const smtpHost = String(input?.smtpHost || '').trim();
|
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);
|
const displayName = String(input?.displayName || '').trim().slice(0, 80);
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !imapHost || !smtpHost || (authMethod === 'password' && !password)) {
|
||||||
throw new Error('Enter a valid email, password, and both mail server names.');
|
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.');
|
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);
|
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
|
||||||
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
|
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
|
||||||
throw new Error('Choose a supported mailbox sync interval.');
|
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 { id: String(rule.id || createId()), senderContains, subjectContains, action, value };
|
||||||
});
|
});
|
||||||
return {
|
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),
|
signature: String(input?.signature || '').slice(0, 5000),
|
||||||
notificationsEnabled: input?.notificationsEnabled !== false,
|
notificationsEnabled: input?.notificationsEnabled !== false,
|
||||||
syncIntervalMinutes,
|
syncIntervalMinutes,
|
||||||
rules,
|
rules
|
||||||
imapPort: 143,
|
|
||||||
smtpPort: 587
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,8 +70,14 @@ function publicAccount(account) {
|
|||||||
id: account.id,
|
id: account.id,
|
||||||
email: account.email,
|
email: account.email,
|
||||||
displayName: account.displayName || '',
|
displayName: account.displayName || '',
|
||||||
|
authMethod: account.authMethod === 'oauth2' ? 'oauth2' : 'password',
|
||||||
|
oauthProvider: account.authMethod === 'oauth2' ? account.oauthProvider || null : null,
|
||||||
imapHost: account.imapHost,
|
imapHost: account.imapHost,
|
||||||
smtpHost: account.smtpHost,
|
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 || '',
|
signature: account.signature || '',
|
||||||
notificationsEnabled: account.notificationsEnabled !== false,
|
notificationsEnabled: account.notificationsEnabled !== false,
|
||||||
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
|
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ function createMessageActionService({ imapClient, folderPath, findSpecialMailbox
|
|||||||
const action = String(input?.action || '');
|
const action = String(input?.action || '');
|
||||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
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.');
|
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 {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const sourcePath = await folderPath(client, folder);
|
const sourcePath = await folderPath(client, folder);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ function createAttachmentService({ imapClient, folderPath, parseForAttachments,
|
|||||||
const filename = String(input?.filename || 'attachment');
|
const filename = String(input?.filename || 'attachment');
|
||||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
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 {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailboxPath = await folderPath(client, folder);
|
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 {
|
try {
|
||||||
const account = await readAccount(accountId);
|
const account = await readAccount(accountId);
|
||||||
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
client = imapClient(account, {
|
client = await imapClient(account, {
|
||||||
autoIdleDelay: 10_000,
|
autoIdleDelay: 10_000,
|
||||||
maxIdleTime: 25 * 60 * 1000,
|
maxIdleTime: 25 * 60 * 1000,
|
||||||
socketTimeout: 30 * 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 = {}) {
|
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
|
||||||
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
||||||
const client = imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailboxPath = await folderPath(client, folder);
|
const mailboxPath = await folderPath(client, folder);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTr
|
|||||||
const to = String(message?.to || '').trim();
|
const to = String(message?.to || '').trim();
|
||||||
if (!to) throw new Error('Add at least one recipient.');
|
if (!to) throw new Error('Add at least one recipient.');
|
||||||
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
||||||
const transport = smtpTransport(account);
|
const transport = await smtpTransport(account);
|
||||||
const sentMessageId = String(message.messageId || `<${randomUUID()}@ep-mail.local>`);
|
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 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);
|
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' });
|
const copy = createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
|
||||||
try {
|
try {
|
||||||
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
|
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
|
||||||
const client = imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const sentPath = await findSentMailbox(client, true);
|
const sentPath = await findSentMailbox(client, true);
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ function createMailboxSyncService({
|
|||||||
async function syncAccountMailboxes(account) {
|
async function syncAccountMailboxes(account) {
|
||||||
await flushMailOutbox(account);
|
await flushMailOutbox(account);
|
||||||
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||||
const client = imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailboxes = await client.list();
|
const mailboxes = await client.list();
|
||||||
|
|||||||
+35
-31
@@ -32,6 +32,9 @@ const { createMailboxSyncService } = require('./mail/sync-service.cjs');
|
|||||||
const { createBackgroundSyncCoordinator } = require('./mail/sync-coordinator.cjs');
|
const { createBackgroundSyncCoordinator } = require('./mail/sync-coordinator.cjs');
|
||||||
const { createIdleWatcherManager } = require('./mail/idle-watcher-manager.cjs');
|
const { createIdleWatcherManager } = require('./mail/idle-watcher-manager.cjs');
|
||||||
const { createSnoozeReminderService } = require('./mail/snooze-reminder-service.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 { isConnectivityFailure } = require('./mail/connectivity.cjs');
|
||||||
const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs');
|
const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs');
|
||||||
const { validateIpcArguments } = require('./security/ipc-arguments.cjs');
|
const { validateIpcArguments } = require('./security/ipc-arguments.cjs');
|
||||||
@@ -98,6 +101,29 @@ function updateAccountStore(update) {
|
|||||||
return operation;
|
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) {
|
function sendMailSyncUpdate(update) {
|
||||||
for (const window of BrowserWindow.getAllWindows()) {
|
for (const window of BrowserWindow.getAllWindows()) {
|
||||||
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
|
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;
|
return store[key].find(item => item.id === (id || store[activeKey])) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function imapClient(account, options = {}) {
|
const { imapClient, smtpTransport } = createMailConnections({
|
||||||
return new ImapFlow({
|
ImapFlow,
|
||||||
host: account.imapHost,
|
createTransport: nodemailer.createTransport,
|
||||||
port: account.imapPort,
|
oauthTokenManager
|
||||||
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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertSecureStorage() {
|
function assertSecureStorage() {
|
||||||
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
||||||
@@ -235,12 +237,12 @@ async function saveAccount(account) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function connectMail(account) {
|
async function connectMail(account) {
|
||||||
const client = imapClient(account);
|
const client = await imapClient(account);
|
||||||
let transport;
|
let transport;
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
||||||
transport = smtpTransport(account);
|
transport = await smtpTransport(account);
|
||||||
await transport.verify();
|
await transport.verify();
|
||||||
return { mailbox: mailbox.name, messages: mailbox.exists };
|
return { mailbox: mailbox.name, messages: mailbox.exists };
|
||||||
} finally {
|
} finally {
|
||||||
@@ -317,7 +319,7 @@ async function fetchSnoozedMailbox(account, offset, limit) {
|
|||||||
.filter(item => Number(item.dueAt) > now)
|
.filter(item => Number(item.dueAt) > now)
|
||||||
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
.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 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 = [];
|
const messages = [];
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
@@ -462,6 +464,8 @@ registerMailIpcHandlers({
|
|||||||
publicAccount,
|
publicAccount,
|
||||||
normalizeAccount,
|
normalizeAccount,
|
||||||
connectMail,
|
connectMail,
|
||||||
|
authorizeOAuthAccount,
|
||||||
|
listOAuthProviders,
|
||||||
requestBackgroundSync,
|
requestBackgroundSync,
|
||||||
CUSTOM_FOLDER_PREFIX,
|
CUSTOM_FOLDER_PREFIX,
|
||||||
flushMailOutbox,
|
flushMailOutbox,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
|||||||
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
|
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
|
||||||
getAccount: () => ipcRenderer.invoke('mail:get-account'),
|
getAccount: () => ipcRenderer.invoke('mail:get-account'),
|
||||||
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
|
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
|
||||||
|
listOAuthProviders: () => ipcRenderer.invoke('mail:list-oauth-providers'),
|
||||||
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
|
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
|
||||||
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
|
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
|
||||||
connect: details => ipcRenderer.invoke('mail:connect', details),
|
connect: details => ipcRenderer.invoke('mail:connect', details),
|
||||||
|
|||||||
@@ -31,13 +31,18 @@ const davRemoteFields = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const objectFieldSchemas = {
|
const objectFieldSchemas = {
|
||||||
'mail:update-account': [{
|
'mail:update-account': [null, {
|
||||||
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
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(),
|
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
|
||||||
rules: array(record(ruleFields), 50)
|
rules: array(record(ruleFields), 50)
|
||||||
}],
|
}],
|
||||||
'mail:connect': [{
|
'mail:connect': [{
|
||||||
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
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(),
|
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
|
||||||
rules: array(record(ruleFields), 50)
|
rules: array(record(ruleFields), 50)
|
||||||
}],
|
}],
|
||||||
@@ -116,6 +121,7 @@ const schemas = {
|
|||||||
'app:get-version': [],
|
'app:get-version': [],
|
||||||
'mail:get-account': [],
|
'mail:get-account': [],
|
||||||
'mail:list-accounts': [],
|
'mail:list-accounts': [],
|
||||||
|
'mail:list-oauth-providers': [],
|
||||||
'mail:select-account': ['string'],
|
'mail:select-account': ['string'],
|
||||||
'mail:remove-account': ['string'],
|
'mail:remove-account': ['string'],
|
||||||
'mail:update-account': ['string', 'object'],
|
'mail:update-account': ['string', 'object'],
|
||||||
|
|||||||
+80
-5
@@ -229,6 +229,73 @@ function openMailAccount(existingAccount = null) {
|
|||||||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||||||
</div>`).join('');
|
</div>`).join('');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||||||
|
const authMethodRow = document.createElement('label');
|
||||||
|
authMethodRow.className = 'compose-line';
|
||||||
|
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
|
||||||
|
const emailRow = selectMailUi('#mail-account-email').closest('.compose-line');
|
||||||
|
emailRow.after(authMethodRow);
|
||||||
|
const oauthProviderRow = document.createElement('label');
|
||||||
|
oauthProviderRow.className = 'compose-line';
|
||||||
|
oauthProviderRow.innerHTML = '<span>Provider</span><select id="mail-account-oauth-provider" class="settings-select"><option value="google">Google</option><option value="microsoft">Microsoft</option></select>';
|
||||||
|
authMethodRow.after(oauthProviderRow);
|
||||||
|
const reauthorizeRow = document.createElement('label');
|
||||||
|
reauthorizeRow.className = 'compose-line';
|
||||||
|
reauthorizeRow.innerHTML = '<span>Sign in again</span><input id="mail-account-reauthorize" type="checkbox">';
|
||||||
|
oauthProviderRow.after(reauthorizeRow);
|
||||||
|
const authMethodSelect = selectMailUi('#mail-account-auth-method');
|
||||||
|
const oauthProviderSelect = selectMailUi('#mail-account-oauth-provider');
|
||||||
|
let configuredOAuthProviders = null;
|
||||||
|
const oauthMethodOption = [...authMethodSelect.options].find(option => option.value === 'oauth2');
|
||||||
|
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
|
||||||
|
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
|
||||||
|
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
|
||||||
|
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
|
||||||
|
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
|
||||||
|
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
|
||||||
|
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
|
||||||
|
const setProviderServers = () => {
|
||||||
|
const servers = oauthProviderSelect.value === 'google'
|
||||||
|
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
|
||||||
|
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
|
||||||
|
selectMailUi('#mail-account-imap').value = servers.imap;
|
||||||
|
selectMailUi('#mail-account-smtp').value = servers.smtp;
|
||||||
|
};
|
||||||
|
const updateAuthFields = () => {
|
||||||
|
const oauth = authMethodSelect.value === 'oauth2';
|
||||||
|
if (oauth) setProviderServers();
|
||||||
|
oauthProviderRow.hidden = !oauth;
|
||||||
|
reauthorizeRow.hidden = !oauth || !editing;
|
||||||
|
passwordRow.hidden = oauth;
|
||||||
|
imapRow.hidden = oauth;
|
||||||
|
smtpRow.hidden = oauth;
|
||||||
|
authNote.textContent = oauth
|
||||||
|
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
|
||||||
|
: configuredOAuthProviders && configuredOAuthProviders.size === 0
|
||||||
|
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
|
||||||
|
: 'Your password is encrypted with this computer\'s credential storage. Connections require TLS.';
|
||||||
|
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
|
||||||
|
? 'Leave blank to keep current password' : 'Enter mailbox password';
|
||||||
|
};
|
||||||
|
authMethodSelect.onchange = updateAuthFields;
|
||||||
|
oauthProviderSelect.onchange = setProviderServers;
|
||||||
|
updateAuthFields();
|
||||||
|
if (typeof window.daybreakMail?.listOAuthProviders === 'function') {
|
||||||
|
window.daybreakMail.listOAuthProviders().then(providers => {
|
||||||
|
const configured = new Set((providers || []).filter(provider => provider.configured).map(provider => provider.id));
|
||||||
|
configuredOAuthProviders = configured;
|
||||||
|
for (const option of oauthProviderSelect.options) option.disabled = !configured.has(option.value) && !(editing && existingAccount?.oauthProvider === option.value);
|
||||||
|
if (oauthMethodOption) oauthMethodOption.disabled = configured.size === 0 && !(editing && existingAccount?.authMethod === 'oauth2');
|
||||||
|
if (!existingAccount?.oauthProvider && !configured.has(oauthProviderSelect.value)) {
|
||||||
|
const available = [...configured][0];
|
||||||
|
if (available) oauthProviderSelect.value = available;
|
||||||
|
}
|
||||||
|
if (authMethodSelect.value === 'oauth2' && oauthProviderSelect.selectedOptions[0]?.disabled) authMethodSelect.value = 'password';
|
||||||
|
updateAuthFields();
|
||||||
|
}).catch(() => {});
|
||||||
|
} else {
|
||||||
|
authMethodRow.hidden = true;
|
||||||
|
oauthProviderRow.hidden = true;
|
||||||
|
}
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
selectAllMailUi('.modal-close').forEach(button => button.onclick = close);
|
selectAllMailUi('.modal-close').forEach(button => button.onclick = close);
|
||||||
selectMailUi('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
|
selectMailUi('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
|
||||||
@@ -260,16 +327,24 @@ function openMailAccount(existingAccount = null) {
|
|||||||
const button = selectMailUi('#connect-mail');
|
const button = selectMailUi('#connect-mail');
|
||||||
const status = selectMailUi('#mail-account-status');
|
const status = selectMailUi('#mail-account-status');
|
||||||
const password = selectMailUi('#mail-account-password').value;
|
const password = selectMailUi('#mail-account-password').value;
|
||||||
|
const authMethod = authMethodSelect.value;
|
||||||
|
const oauthProvider = oauthProviderSelect.value;
|
||||||
const name = selectMailUi('#mail-account-display-name').value.trim();
|
const name = selectMailUi('#mail-account-display-name').value.trim();
|
||||||
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
||||||
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
|
||||||
status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
|
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
||||||
|
status.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth)
|
||||||
|
? 'Opening your browser for secure provider sign-in…'
|
||||||
|
: editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
|
||||||
try {
|
try {
|
||||||
const details = {
|
const details = {
|
||||||
email: selectMailUi('#mail-account-email').value,
|
email: selectMailUi('#mail-account-email').value,
|
||||||
password,
|
password,
|
||||||
|
authMethod,
|
||||||
|
...(authMethod === 'oauth2' ? { oauthProvider } : {}),
|
||||||
|
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
|
||||||
displayName: name,
|
displayName: name,
|
||||||
imapHost: selectMailUi('#mail-account-imap').value,
|
imapHost: selectMailUi('#mail-account-imap').value,
|
||||||
smtpHost: selectMailUi('#mail-account-smtp').value,
|
smtpHost: selectMailUi('#mail-account-smtp').value,
|
||||||
@@ -302,13 +377,13 @@ function openMailAccount(existingAccount = null) {
|
|||||||
mailFeatureState.connectedAccount = account;
|
mailFeatureState.connectedAccount = account;
|
||||||
updateAccountCard(account);
|
updateAccountCard(account);
|
||||||
close();
|
close();
|
||||||
toastMailUi('Mailbox connected securely');
|
toastMailUi(authMethod === 'oauth2' ? 'OAuth2 mailbox connected securely' : 'Mailbox connected securely');
|
||||||
await syncMailbox(true);
|
await syncMailbox(true);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
|
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = editing ? 'Save & reconnect' : 'Test & connect';
|
button.textContent = authMethod === 'oauth2' ? 'Authorize & connect' : editing ? 'Save & reconnect' : 'Test & connect';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
selectMailUi('#mail-account-email').focus();
|
selectMailUi('#mail-account-email').focus();
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.4.38",
|
"version": "0.4.39",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.4.38",
|
"version": "0.4.39",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
"@capacitor/core": "^8.5.2",
|
"@capacitor/core": "^8.5.2",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.4.38",
|
"version": "0.4.39",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Eternity Project mail client",
|
"description": "Eternity Project mail client",
|
||||||
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { hasIpcSchema, validateIpcArguments } = require('../desktop/security/ipc-
|
|||||||
|
|
||||||
test('validates supported IPC channels and their positional argument types', () => {
|
test('validates supported IPC channels and their positional argument types', () => {
|
||||||
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{ email: 'a@example.com' }]));
|
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{ email: 'a@example.com' }]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:list-oauth-providers', []));
|
||||||
assert.doesNotThrow(() => validateIpcArguments('mail:sync-folder', ['Inbox', 0, { hasAttachments: true }]));
|
assert.doesNotThrow(() => validateIpcArguments('mail:sync-folder', ['Inbox', 0, { hasAttachments: true }]));
|
||||||
assert.doesNotThrow(() => validateIpcArguments('mail:disconnect', []));
|
assert.doesNotThrow(() => validateIpcArguments('mail:disconnect', []));
|
||||||
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{ to: 'a@example.com', attachments: [] }]));
|
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{ to: 'a@example.com', attachments: [] }]));
|
||||||
@@ -50,6 +51,16 @@ test('validates channel-specific field shapes, limits, and enums', () => {
|
|||||||
imapHost: 'imap.example.test', smtpHost: 'smtp.example.test',
|
imapHost: 'imap.example.test', smtpHost: 'smtp.example.test',
|
||||||
rules: [{ senderContains: 'alerts', action: 'flag', value: '' }]
|
rules: [{ senderContains: 'alerts', action: 'flag', value: '' }]
|
||||||
}]));
|
}]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
}]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:update-account', ['account-1', {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'microsoft', reauthorizeOAuth: true
|
||||||
|
}]));
|
||||||
|
assert.throws(() => validateIpcArguments('mail:connect', [{ authMethod: 'oauth2', oauthProvider: 'other' }]), /oauthProvider/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:connect', [{
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'unknown'
|
||||||
|
}]), /oauthProvider/);
|
||||||
assert.throws(() => validateIpcArguments('mail:connect', [{ rules: Array(51).fill({ action: 'flag' }) }]), /Invalid argument 1/);
|
assert.throws(() => validateIpcArguments('mail:connect', [{ rules: Array(51).fill({ action: 'flag' }) }]), /Invalid argument 1/);
|
||||||
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: '4', action: 'star' }]), /uid/);
|
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: '4', action: 'star' }]), /uid/);
|
||||||
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: 4, action: 'delete-anything' }]), /action/);
|
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: 4, action: 'delete-anything' }]), /action/);
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ test('registers mail/account IPC handlers through the shared boundary', () => {
|
|||||||
|
|
||||||
assert.deepEqual(registered.map(item => item.channel).sort(), [
|
assert.deepEqual(registered.map(item => item.channel).sort(), [
|
||||||
'mail:connect', 'mail:create-folder', 'mail:delete-draft', 'mail:disconnect',
|
'mail:connect', 'mail:create-folder', 'mail:delete-draft', 'mail:disconnect',
|
||||||
'mail:get-account', 'mail:list-accounts', 'mail:list-drafts', 'mail:list-folders',
|
'mail:get-account', 'mail:list-accounts', 'mail:list-drafts', 'mail:list-folders', 'mail:list-oauth-providers',
|
||||||
'mail:open-external', 'mail:preview-attachment', 'mail:remove-account', 'mail:save-attachment',
|
'mail:open-external', 'mail:preview-attachment', 'mail:remove-account', 'mail:save-attachment',
|
||||||
'mail:save-draft', 'mail:select-account', 'mail:send', 'mail:set-snooze',
|
'mail:save-draft', 'mail:select-account', 'mail:send', 'mail:set-snooze',
|
||||||
'mail:sync-folder', 'mail:sync-inbox', 'mail:update-account', 'mail:update-message'
|
'mail:sync-folder', 'mail:sync-inbox', 'mail:update-account', 'mail:update-message'
|
||||||
|
|||||||
@@ -43,6 +43,34 @@ test('rejects invalid account fields and malformed mail rules', () => {
|
|||||||
}), /must move messages/);
|
}), /must move messages/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('normalizes OAuth2 accounts to provider servers without requiring a password', () => {
|
||||||
|
const google = normalizeAccount({
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(google.password, '');
|
||||||
|
assert.equal(google.authMethod, 'oauth2');
|
||||||
|
assert.equal(google.oauthProvider, 'google');
|
||||||
|
assert.equal(google.imapHost, 'imap.gmail.com');
|
||||||
|
assert.equal(google.imapPort, 993);
|
||||||
|
assert.equal(google.imapSecure, true);
|
||||||
|
assert.equal(google.smtpHost, 'smtp.gmail.com');
|
||||||
|
const untrustedEndpoints = normalizeAccount({
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User',
|
||||||
|
imapHost: 'attacker.example.test', smtpHost: 'attacker.example.test', imapPort: 143
|
||||||
|
});
|
||||||
|
assert.equal(untrustedEndpoints.imapHost, 'imap.gmail.com');
|
||||||
|
assert.equal(untrustedEndpoints.smtpHost, 'smtp.gmail.com');
|
||||||
|
assert.equal(untrustedEndpoints.imapPort, 993);
|
||||||
|
|
||||||
|
const microsoft = normalizeAccount({
|
||||||
|
email: 'user@outlook.com', authMethod: 'oauth2', oauthProvider: 'microsoft', displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(microsoft.imapHost, 'outlook.office365.com');
|
||||||
|
assert.equal(microsoft.smtpHost, 'smtp.office365.com');
|
||||||
|
assert.throws(() => normalizeAccount({ email: 'user@example.test', authMethod: 'oauth2', displayName: 'User' }), /Choose Google or Microsoft/);
|
||||||
|
assert.throws(() => normalizeAccount({ email: 'user@example.test', authMethod: 'oauth', password: 'secret', displayName: 'User' }), /supported sign-in method/);
|
||||||
|
});
|
||||||
|
|
||||||
test('public account projection does not expose the password or private mailbox state', () => {
|
test('public account projection does not expose the password or private mailbox state', () => {
|
||||||
const account = normalizeAccount(accountInput);
|
const account = normalizeAccount(accountInput);
|
||||||
const result = publicAccount({
|
const result = publicAccount({
|
||||||
@@ -54,6 +82,8 @@ test('public account projection does not expose the password or private mailbox
|
|||||||
assert.equal(result.id, 'account-1');
|
assert.equal(result.id, 'account-1');
|
||||||
assert.equal(result.email, 'user@example.com');
|
assert.equal(result.email, 'user@example.com');
|
||||||
assert.equal('password' in result, false);
|
assert.equal('password' in result, false);
|
||||||
|
assert.equal('oauthRefreshToken' in result, false);
|
||||||
|
assert.equal('oauthAccessToken' in result, false);
|
||||||
assert.equal('drafts' in result, false);
|
assert.equal('drafts' in result, false);
|
||||||
assert.equal('mailOutbox' in result, false);
|
assert.equal('mailOutbox' in result, false);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { normalizeAccount, publicAccount } = require('../desktop/mail-model.cjs');
|
||||||
|
const { registerMailIpcHandlers } = require('../desktop/ipc/mail.cjs');
|
||||||
|
|
||||||
|
function registerOAuthMailHandlers(overrides = {}) {
|
||||||
|
const handlers = new Map();
|
||||||
|
registerMailIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { handlers.set(channel, handler); },
|
||||||
|
normalizeAccount,
|
||||||
|
publicAccount,
|
||||||
|
async connectMail() { return { mailbox: 'INBOX', messages: 0 }; },
|
||||||
|
async authorizeOAuthAccount(account) {
|
||||||
|
return {
|
||||||
|
...account,
|
||||||
|
oauthAccessToken: 'private-access-token',
|
||||||
|
oauthRefreshToken: 'private-refresh-token',
|
||||||
|
oauthAccessTokenExpiresAt: Date.now() + 3600_000
|
||||||
|
};
|
||||||
|
},
|
||||||
|
listOAuthProviders() { return [{ id: 'google', label: 'Google', configured: true }, { id: 'microsoft', label: 'Microsoft', configured: false }]; },
|
||||||
|
async saveAccount(account) { return { ...account, id: 'oauth-account' }; },
|
||||||
|
requestBackgroundSync() {},
|
||||||
|
randomUUID: () => 'generated-account-id',
|
||||||
|
...overrides
|
||||||
|
});
|
||||||
|
return handlers;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('OAuth account setup authorizes in the main process and never returns tokens to the renderer', async () => {
|
||||||
|
const calls = [];
|
||||||
|
const handlers = registerOAuthMailHandlers({
|
||||||
|
async authorizeOAuthAccount(account) {
|
||||||
|
calls.push(['authorize', account.oauthProvider]);
|
||||||
|
return { ...account, oauthAccessToken: 'private-access-token', oauthRefreshToken: 'private-refresh-token', oauthAccessTokenExpiresAt: Date.now() + 3600_000 };
|
||||||
|
},
|
||||||
|
async connectMail(account) {
|
||||||
|
calls.push(['connect', account.authMethod, account.oauthRefreshToken]);
|
||||||
|
return { mailbox: 'INBOX', messages: 0 };
|
||||||
|
},
|
||||||
|
async saveAccount(account) {
|
||||||
|
calls.push(['save', account.oauthRefreshToken]);
|
||||||
|
return { ...account, id: 'oauth-account' };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await handlers.get('mail:connect')({}, {
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(calls.map(call => call[0]), ['authorize', 'connect', 'save']);
|
||||||
|
assert.deepEqual(calls[1], ['connect', 'oauth2', 'private-refresh-token']);
|
||||||
|
assert.equal(result.authMethod, 'oauth2');
|
||||||
|
assert.equal(result.oauthProvider, 'google');
|
||||||
|
assert.equal('oauthAccessToken' in result, false);
|
||||||
|
assert.equal('oauthRefreshToken' in result, false);
|
||||||
|
assert.equal('password' in result, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OAuth provider discovery reports configured status without exposing client credentials', async () => {
|
||||||
|
const handlers = registerOAuthMailHandlers();
|
||||||
|
assert.deepEqual(await handlers.get('mail:list-oauth-providers')(), [
|
||||||
|
{ id: 'google', label: 'Google', configured: true },
|
||||||
|
{ id: 'microsoft', label: 'Microsoft', configured: false }
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('editing an OAuth account preserves its token unless the user requests reauthorization', async () => {
|
||||||
|
const existing = {
|
||||||
|
...normalizeAccount({ email: 'user@gmail.com', displayName: 'User', authMethod: 'oauth2', oauthProvider: 'google' }),
|
||||||
|
id: 'oauth-account', oauthAccessToken: 'old-access', oauthRefreshToken: 'old-refresh', oauthAccessTokenExpiresAt: 10
|
||||||
|
};
|
||||||
|
const store = { accounts: [existing] };
|
||||||
|
let authorizations = 0;
|
||||||
|
const handlers = new Map();
|
||||||
|
registerMailIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { handlers.set(channel, handler); },
|
||||||
|
normalizeAccount,
|
||||||
|
publicAccount,
|
||||||
|
async readAccount(id) { return store.accounts.find(account => account.id === id); },
|
||||||
|
async updateAccountStore(update) { return update(store); },
|
||||||
|
async connectMail() { return { mailbox: 'INBOX', messages: 0 }; },
|
||||||
|
async authorizeOAuthAccount(account) {
|
||||||
|
authorizations += 1;
|
||||||
|
return { ...account, oauthAccessToken: 'new-access', oauthRefreshToken: 'new-refresh', oauthAccessTokenExpiresAt: Date.now() + 3600_000 };
|
||||||
|
},
|
||||||
|
requestBackgroundSync() {}
|
||||||
|
});
|
||||||
|
const event = {};
|
||||||
|
|
||||||
|
await handlers.get('mail:update-account')(event, 'oauth-account', {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(authorizations, 0);
|
||||||
|
assert.equal(store.accounts[0].oauthRefreshToken, 'old-refresh');
|
||||||
|
|
||||||
|
const result = await handlers.get('mail:update-account')(event, 'oauth-account', {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'google', reauthorizeOAuth: true, displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(authorizations, 1);
|
||||||
|
assert.equal(store.accounts[0].oauthRefreshToken, 'new-refresh');
|
||||||
|
assert.equal('oauthRefreshToken' in result, false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createOAuthTokenManager } = require('../desktop/mail/oauth-token-manager.cjs');
|
||||||
|
const { createMailConnections } = require('../desktop/mail/connection-factory.cjs');
|
||||||
|
|
||||||
|
test('uses a fresh OAuth access token without refreshing it', async () => {
|
||||||
|
let refreshes = 0;
|
||||||
|
const manager = createOAuthTokenManager({
|
||||||
|
oauth2Service: { async refresh() { refreshes += 1; } },
|
||||||
|
async persistTokens() {},
|
||||||
|
now: () => 1_000
|
||||||
|
});
|
||||||
|
const account = {
|
||||||
|
id: 'account-1', authMethod: 'oauth2', oauthProvider: 'google',
|
||||||
|
oauthAccessToken: 'fresh-token', oauthRefreshToken: 'refresh-token', oauthAccessTokenExpiresAt: 120_000
|
||||||
|
};
|
||||||
|
assert.equal(await manager.getAccessToken(account), 'fresh-token');
|
||||||
|
assert.equal(refreshes, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refreshes expired OAuth tokens once and persists the encrypted-store fields', async () => {
|
||||||
|
let refreshes = 0;
|
||||||
|
const persisted = [];
|
||||||
|
const manager = createOAuthTokenManager({
|
||||||
|
oauth2Service: {
|
||||||
|
async refresh(provider, refreshToken) {
|
||||||
|
refreshes += 1;
|
||||||
|
assert.equal(provider, 'microsoft');
|
||||||
|
assert.equal(refreshToken, 'old-refresh');
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
return { oauthAccessToken: 'fresh-token', oauthRefreshToken: 'new-refresh', oauthAccessTokenExpiresAt: 200_000 };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async persistTokens(id, tokens) { persisted.push({ id, tokens }); },
|
||||||
|
now: () => 1_000
|
||||||
|
});
|
||||||
|
const first = { id: 'account-2', authMethod: 'oauth2', oauthProvider: 'microsoft', oauthRefreshToken: 'old-refresh', oauthAccessTokenExpiresAt: 0 };
|
||||||
|
const second = { ...first };
|
||||||
|
|
||||||
|
assert.deepEqual(await Promise.all([manager.getAccessToken(first), manager.getAccessToken(second)]), ['fresh-token', 'fresh-token']);
|
||||||
|
assert.equal(refreshes, 1);
|
||||||
|
assert.equal(persisted.length, 1);
|
||||||
|
assert.equal(persisted[0].id, 'account-2');
|
||||||
|
assert.equal(first.oauthRefreshToken, 'new-refresh');
|
||||||
|
assert.equal(second.oauthAccessToken, 'fresh-token');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects expired OAuth accounts without a refresh token', async () => {
|
||||||
|
const manager = createOAuthTokenManager({
|
||||||
|
oauth2Service: { async refresh() { assert.fail('must not refresh without a token'); } },
|
||||||
|
async persistTokens() {},
|
||||||
|
now: () => 100_000
|
||||||
|
});
|
||||||
|
await assert.rejects(manager.getAccessToken({ authMethod: 'oauth2', oauthProvider: 'google' }), /Reconnect this OAuth2 account/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mail connection factory uses OAuth bearer tokens and TLS provider defaults', async () => {
|
||||||
|
const imapOptions = [];
|
||||||
|
const smtpOptions = [];
|
||||||
|
const manager = { async getAccessToken(account) { return `token:${account.email}`; } };
|
||||||
|
const connections = createMailConnections({
|
||||||
|
ImapFlow: class { constructor(options) { imapOptions.push(options); } },
|
||||||
|
createTransport(options) { smtpOptions.push(options); return { options }; },
|
||||||
|
oauthTokenManager: manager
|
||||||
|
});
|
||||||
|
const oauthAccount = {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'google', email: 'user@gmail.com',
|
||||||
|
imapHost: 'imap.gmail.com', imapPort: 993, imapSecure: true,
|
||||||
|
smtpHost: 'smtp.gmail.com', smtpPort: 587, smtpSecure: false,
|
||||||
|
oauthAccessTokenExpiresAt: 123456
|
||||||
|
};
|
||||||
|
|
||||||
|
await connections.imapClient(oauthAccount, { autoIdleDelay: 10 });
|
||||||
|
await connections.smtpTransport(oauthAccount);
|
||||||
|
assert.deepEqual(imapOptions[0].auth, { user: 'user@gmail.com', accessToken: 'token:user@gmail.com' });
|
||||||
|
assert.equal(imapOptions[0].secure, true);
|
||||||
|
assert.equal(imapOptions[0].doSTARTTLS, false);
|
||||||
|
assert.equal(imapOptions[0].autoIdleDelay, 10);
|
||||||
|
assert.deepEqual(smtpOptions[0].auth, {
|
||||||
|
type: 'OAuth2', user: 'user@gmail.com', accessToken: 'token:user@gmail.com', expires: 123456
|
||||||
|
});
|
||||||
|
assert.equal(smtpOptions[0].requireTLS, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mail connection factory retains password and STARTTLS behavior for existing accounts', async () => {
|
||||||
|
let imapOptions;
|
||||||
|
let smtpOptions;
|
||||||
|
const connections = createMailConnections({
|
||||||
|
ImapFlow: class { constructor(options) { imapOptions = options; } },
|
||||||
|
createTransport(options) { smtpOptions = options; return {}; },
|
||||||
|
oauthTokenManager: { async getAccessToken() { assert.fail('password accounts must not request OAuth tokens'); } }
|
||||||
|
});
|
||||||
|
const account = {
|
||||||
|
email: 'user@example.test', password: 'mail-password', imapHost: 'imap.example.test', imapPort: 143,
|
||||||
|
smtpHost: 'smtp.example.test', smtpPort: 587
|
||||||
|
};
|
||||||
|
await connections.imapClient(account);
|
||||||
|
await connections.smtpTransport(account);
|
||||||
|
assert.deepEqual(imapOptions.auth, { user: account.email, pass: account.password });
|
||||||
|
assert.equal(imapOptions.secure, false);
|
||||||
|
assert.equal(imapOptions.doSTARTTLS, true);
|
||||||
|
assert.deepEqual(smtpOptions.auth, { user: account.email, pass: account.password });
|
||||||
|
assert.equal(smtpOptions.requireTLS, true);
|
||||||
|
});
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createOAuth2Service, loadOAuthProviderConfig } = require('../desktop/mail/oauth2-service.cjs');
|
||||||
|
|
||||||
|
test('loads only externally configured OAuth client identifiers', () => {
|
||||||
|
assert.deepEqual(loadOAuthProviderConfig({}), {});
|
||||||
|
const providers = loadOAuthProviderConfig({
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_ID: 'google-client.apps.example',
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET: 'google-desktop-secret',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_TENANT_ID: 'organizations'
|
||||||
|
});
|
||||||
|
assert.equal(providers.google.clientId, 'google-client.apps.example');
|
||||||
|
assert.equal(providers.microsoft.tenant, 'organizations');
|
||||||
|
assert.throws(() => loadOAuthProviderConfig({
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_TENANT_ID: 'https://attacker.example'
|
||||||
|
}), /tenant ID is invalid/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('authorizes Google and Microsoft with PKCE, state validation, and loopback redirects', async () => {
|
||||||
|
const providers = loadOAuthProviderConfig({
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_ID: 'google-client',
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET: 'google-secret',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_TENANT_ID: 'common'
|
||||||
|
});
|
||||||
|
const authorizationUrls = [];
|
||||||
|
const tokenRequests = [];
|
||||||
|
const service = createOAuth2Service({
|
||||||
|
providers,
|
||||||
|
async openExternal(value) {
|
||||||
|
const authorization = new URL(value);
|
||||||
|
authorizationUrls.push(authorization);
|
||||||
|
const callback = new URL(authorization.searchParams.get('redirect_uri'));
|
||||||
|
callback.searchParams.set('code', 'authorization-code');
|
||||||
|
callback.searchParams.set('state', authorization.searchParams.get('state'));
|
||||||
|
const result = await fetch(callback);
|
||||||
|
assert.equal(result.status, 200);
|
||||||
|
},
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
tokenRequests.push({ url, body: new URLSearchParams(options.body) });
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
async json() {
|
||||||
|
return { access_token: 'access-token', refresh_token: 'refresh-token', expires_in: 3600 };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const provider of ['google', 'microsoft']) {
|
||||||
|
const tokens = await service.authorize(provider, 'user@example.test');
|
||||||
|
assert.deepEqual(Object.keys(tokens).sort(), [
|
||||||
|
'oauthAccessToken', 'oauthAccessTokenExpiresAt', 'oauthRefreshToken'
|
||||||
|
]);
|
||||||
|
assert.equal(tokens.oauthAccessToken, 'access-token');
|
||||||
|
assert.equal(tokens.oauthRefreshToken, 'refresh-token');
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(authorizationUrls.length, 2);
|
||||||
|
for (const authorization of authorizationUrls) {
|
||||||
|
assert.match(authorization.searchParams.get('code_challenge'), /^[A-Za-z0-9_-]{43}$/);
|
||||||
|
assert.equal(authorization.searchParams.get('code_challenge_method'), 'S256');
|
||||||
|
assert.equal(authorization.searchParams.get('login_hint'), 'user@example.test');
|
||||||
|
assert.ok(authorization.searchParams.get('state').length >= 40);
|
||||||
|
assert.match(authorization.searchParams.get('redirect_uri'), /^http:\/\/(?:127\.0\.0\.1|localhost):\d+$/);
|
||||||
|
}
|
||||||
|
assert.equal(authorizationUrls[0].searchParams.get('scope'), 'https://mail.google.com/');
|
||||||
|
assert.match(authorizationUrls[1].searchParams.get('scope'), /IMAP\.AccessAsUser\.All/);
|
||||||
|
assert.match(authorizationUrls[1].searchParams.get('scope'), /SMTP\.Send/);
|
||||||
|
assert.equal(tokenRequests.length, 2);
|
||||||
|
assert.equal(tokenRequests[0].body.get('code_verifier').length, 64);
|
||||||
|
assert.equal(tokenRequests[0].body.get('client_secret'), 'google-secret');
|
||||||
|
assert.equal(tokenRequests[1].body.has('client_secret'), false);
|
||||||
|
assert.equal(tokenRequests[0].body.get('code'), 'authorization-code');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refreshes OAuth tokens and preserves the current refresh token if omitted by provider', async () => {
|
||||||
|
let posted;
|
||||||
|
const service = createOAuth2Service({
|
||||||
|
providers: loadOAuthProviderConfig({ EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client' }),
|
||||||
|
async openExternal() {},
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
posted = { url, body: new URLSearchParams(options.body) };
|
||||||
|
return { ok: true, async json() { return { access_token: 'new-access-token', expires_in: 1800 }; } };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const tokens = await service.refresh('microsoft', 'stored-refresh-token');
|
||||||
|
assert.equal(posted.body.get('grant_type'), 'refresh_token');
|
||||||
|
assert.equal(posted.body.get('refresh_token'), 'stored-refresh-token');
|
||||||
|
assert.equal(tokens.oauthAccessToken, 'new-access-token');
|
||||||
|
assert.equal(tokens.oauthRefreshToken, 'stored-refresh-token');
|
||||||
|
assert.ok(tokens.oauthAccessTokenExpiresAt > Date.now());
|
||||||
|
await assert.rejects(service.refresh('microsoft', ''), /Reconnect this Microsoft account/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects a loopback callback with an invalid OAuth state before exchanging its code', async () => {
|
||||||
|
let tokenRequests = 0;
|
||||||
|
const service = createOAuth2Service({
|
||||||
|
providers: loadOAuthProviderConfig({ EP_MAIL_GOOGLE_OAUTH_CLIENT_ID: 'google-client' }),
|
||||||
|
async openExternal(value) {
|
||||||
|
const authorization = new URL(value);
|
||||||
|
const callback = new URL(authorization.searchParams.get('redirect_uri'));
|
||||||
|
callback.searchParams.set('code', 'attacker-code');
|
||||||
|
callback.searchParams.set('state', 'wrong-state');
|
||||||
|
const response = await fetch(callback);
|
||||||
|
assert.equal(response.status, 400);
|
||||||
|
},
|
||||||
|
async fetchImpl() {
|
||||||
|
tokenRequests += 1;
|
||||||
|
throw new Error('must not exchange an untrusted code');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await assert.rejects(service.authorize('google', 'user@gmail.com'), /state validation failed/);
|
||||||
|
assert.equal(tokenRequests, 0);
|
||||||
|
});
|
||||||
+80
-5
@@ -229,6 +229,73 @@ function openMailAccount(existingAccount = null) {
|
|||||||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||||||
</div>`).join('');
|
</div>`).join('');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||||||
|
const authMethodRow = document.createElement('label');
|
||||||
|
authMethodRow.className = 'compose-line';
|
||||||
|
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
|
||||||
|
const emailRow = selectMailUi('#mail-account-email').closest('.compose-line');
|
||||||
|
emailRow.after(authMethodRow);
|
||||||
|
const oauthProviderRow = document.createElement('label');
|
||||||
|
oauthProviderRow.className = 'compose-line';
|
||||||
|
oauthProviderRow.innerHTML = '<span>Provider</span><select id="mail-account-oauth-provider" class="settings-select"><option value="google">Google</option><option value="microsoft">Microsoft</option></select>';
|
||||||
|
authMethodRow.after(oauthProviderRow);
|
||||||
|
const reauthorizeRow = document.createElement('label');
|
||||||
|
reauthorizeRow.className = 'compose-line';
|
||||||
|
reauthorizeRow.innerHTML = '<span>Sign in again</span><input id="mail-account-reauthorize" type="checkbox">';
|
||||||
|
oauthProviderRow.after(reauthorizeRow);
|
||||||
|
const authMethodSelect = selectMailUi('#mail-account-auth-method');
|
||||||
|
const oauthProviderSelect = selectMailUi('#mail-account-oauth-provider');
|
||||||
|
let configuredOAuthProviders = null;
|
||||||
|
const oauthMethodOption = [...authMethodSelect.options].find(option => option.value === 'oauth2');
|
||||||
|
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
|
||||||
|
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
|
||||||
|
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
|
||||||
|
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
|
||||||
|
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
|
||||||
|
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
|
||||||
|
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
|
||||||
|
const setProviderServers = () => {
|
||||||
|
const servers = oauthProviderSelect.value === 'google'
|
||||||
|
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
|
||||||
|
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
|
||||||
|
selectMailUi('#mail-account-imap').value = servers.imap;
|
||||||
|
selectMailUi('#mail-account-smtp').value = servers.smtp;
|
||||||
|
};
|
||||||
|
const updateAuthFields = () => {
|
||||||
|
const oauth = authMethodSelect.value === 'oauth2';
|
||||||
|
if (oauth) setProviderServers();
|
||||||
|
oauthProviderRow.hidden = !oauth;
|
||||||
|
reauthorizeRow.hidden = !oauth || !editing;
|
||||||
|
passwordRow.hidden = oauth;
|
||||||
|
imapRow.hidden = oauth;
|
||||||
|
smtpRow.hidden = oauth;
|
||||||
|
authNote.textContent = oauth
|
||||||
|
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
|
||||||
|
: configuredOAuthProviders && configuredOAuthProviders.size === 0
|
||||||
|
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
|
||||||
|
: 'Your password is encrypted with this computer\'s credential storage. Connections require TLS.';
|
||||||
|
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
|
||||||
|
? 'Leave blank to keep current password' : 'Enter mailbox password';
|
||||||
|
};
|
||||||
|
authMethodSelect.onchange = updateAuthFields;
|
||||||
|
oauthProviderSelect.onchange = setProviderServers;
|
||||||
|
updateAuthFields();
|
||||||
|
if (typeof window.daybreakMail?.listOAuthProviders === 'function') {
|
||||||
|
window.daybreakMail.listOAuthProviders().then(providers => {
|
||||||
|
const configured = new Set((providers || []).filter(provider => provider.configured).map(provider => provider.id));
|
||||||
|
configuredOAuthProviders = configured;
|
||||||
|
for (const option of oauthProviderSelect.options) option.disabled = !configured.has(option.value) && !(editing && existingAccount?.oauthProvider === option.value);
|
||||||
|
if (oauthMethodOption) oauthMethodOption.disabled = configured.size === 0 && !(editing && existingAccount?.authMethod === 'oauth2');
|
||||||
|
if (!existingAccount?.oauthProvider && !configured.has(oauthProviderSelect.value)) {
|
||||||
|
const available = [...configured][0];
|
||||||
|
if (available) oauthProviderSelect.value = available;
|
||||||
|
}
|
||||||
|
if (authMethodSelect.value === 'oauth2' && oauthProviderSelect.selectedOptions[0]?.disabled) authMethodSelect.value = 'password';
|
||||||
|
updateAuthFields();
|
||||||
|
}).catch(() => {});
|
||||||
|
} else {
|
||||||
|
authMethodRow.hidden = true;
|
||||||
|
oauthProviderRow.hidden = true;
|
||||||
|
}
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
selectAllMailUi('.modal-close').forEach(button => button.onclick = close);
|
selectAllMailUi('.modal-close').forEach(button => button.onclick = close);
|
||||||
selectMailUi('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
|
selectMailUi('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
|
||||||
@@ -260,16 +327,24 @@ function openMailAccount(existingAccount = null) {
|
|||||||
const button = selectMailUi('#connect-mail');
|
const button = selectMailUi('#connect-mail');
|
||||||
const status = selectMailUi('#mail-account-status');
|
const status = selectMailUi('#mail-account-status');
|
||||||
const password = selectMailUi('#mail-account-password').value;
|
const password = selectMailUi('#mail-account-password').value;
|
||||||
|
const authMethod = authMethodSelect.value;
|
||||||
|
const oauthProvider = oauthProviderSelect.value;
|
||||||
const name = selectMailUi('#mail-account-display-name').value.trim();
|
const name = selectMailUi('#mail-account-display-name').value.trim();
|
||||||
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
||||||
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
|
||||||
status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
|
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
||||||
|
status.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth)
|
||||||
|
? 'Opening your browser for secure provider sign-in…'
|
||||||
|
: editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
|
||||||
try {
|
try {
|
||||||
const details = {
|
const details = {
|
||||||
email: selectMailUi('#mail-account-email').value,
|
email: selectMailUi('#mail-account-email').value,
|
||||||
password,
|
password,
|
||||||
|
authMethod,
|
||||||
|
...(authMethod === 'oauth2' ? { oauthProvider } : {}),
|
||||||
|
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
|
||||||
displayName: name,
|
displayName: name,
|
||||||
imapHost: selectMailUi('#mail-account-imap').value,
|
imapHost: selectMailUi('#mail-account-imap').value,
|
||||||
smtpHost: selectMailUi('#mail-account-smtp').value,
|
smtpHost: selectMailUi('#mail-account-smtp').value,
|
||||||
@@ -302,13 +377,13 @@ function openMailAccount(existingAccount = null) {
|
|||||||
mailFeatureState.connectedAccount = account;
|
mailFeatureState.connectedAccount = account;
|
||||||
updateAccountCard(account);
|
updateAccountCard(account);
|
||||||
close();
|
close();
|
||||||
toastMailUi('Mailbox connected securely');
|
toastMailUi(authMethod === 'oauth2' ? 'OAuth2 mailbox connected securely' : 'Mailbox connected securely');
|
||||||
await syncMailbox(true);
|
await syncMailbox(true);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
|
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = editing ? 'Save & reconnect' : 'Test & connect';
|
button.textContent = authMethod === 'oauth2' ? 'Authorize & connect' : editing ? 'Save & reconnect' : 'Test & connect';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
selectMailUi('#mail-account-email').focus();
|
selectMailUi('#mail-account-email').focus();
|
||||||
|
|||||||
Reference in New Issue
Block a user