213 lines
8.5 KiB
JavaScript
213 lines
8.5 KiB
JavaScript
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 };
|