i18n: Upgrade translations from crowdin (5d3e42b3). (drive)
[ProtonMail-WebClient.git] / applications / pass-desktop / src / main.ts
blobd2b25c84ccf984f4370781f6e9b08c48cdb64ef4
1 import { BrowserWindow, Menu, type Session, Tray, app, nativeImage, nativeTheme, session, shell } from 'electron';
2 import logger from 'electron-log/main';
3 import { join } from 'path';
5 import { ForkType } from '@proton/shared/lib/authentication/fork/constants';
6 import { APPS, APPS_CONFIGURATION } from '@proton/shared/lib/constants';
7 import { getAppVersionHeaders } from '@proton/shared/lib/fetch/headers';
8 import { getAppUrlFromApiUrl, getSecondLevelDomain } from '@proton/shared/lib/helpers/url';
9 import noop from '@proton/utils/noop';
11 import * as config from './app/config';
12 import { WINDOWS_APP_ID } from './constants';
13 import { migrateSameSiteCookies, upgradeSameSiteCookies } from './lib/cookies';
14 import { ARCH } from './lib/env';
15 import { setApplicationMenu } from './menu-view/application-menu';
16 import { startup } from './startup';
17 import { certificateVerifyProc } from './tls';
18 import type { PassElectronContext } from './types';
19 import { SourceType, updateElectronApp } from './update';
20 import { isMac, isProdEnv, isWindows } from './utils/platform';
22 const ctx: PassElectronContext = { window: null, quitting: false };
24 const DOMAIN = getSecondLevelDomain(new URL(config.API_URL).hostname);
26 const createSession = () => {
27     const partitionKey = ENV !== 'production' ? 'app-dev' : 'app';
28     const secureSession = session.fromPartition(`persist:${partitionKey}`, { cache: false });
30     const filter = { urls: [`${getAppUrlFromApiUrl(config.API_URL, APPS.PROTONPASS)}*`] };
32     secureSession.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false));
34     if (isProdEnv()) {
35         // Always use system DNS settings
36         app.configureHostResolver({
37             enableAdditionalDnsQueryTypes: false,
38             enableBuiltInResolver: true,
39             secureDnsMode: 'off',
40             secureDnsServers: [],
41         });
43         // Use certificate pinning
44         if (config.SSO_URL.endsWith('proton.me')) secureSession.setCertificateVerifyProc(certificateVerifyProc);
46         secureSession.webRequest.onHeadersReceived({ urls: [`https://*.${DOMAIN}/*`] }, (details, callback) => {
47             const { responseHeaders = {}, frame } = details;
48             const appRequest = frame?.url?.startsWith('file://') ?? false;
50             /** If the request is made from a `file://` url: migrate ALL `SameSite` directives
51              * to `None` and allow cross-origin requests for the API. If not then only upgrade
52              * EMPTY `SameSite` cookie directives to `None` to preserve `Session-ID` cookies */
53             if (appRequest) {
54                 migrateSameSiteCookies(responseHeaders);
55                 responseHeaders['access-control-allow-origin'] = ['file://'];
56                 responseHeaders['access-control-allow-credentials'] = ['true'];
57                 responseHeaders['access-control-allow-headers'] = Object.keys(details.responseHeaders || {});
58             } else upgradeSameSiteCookies(responseHeaders);
60             callback({ cancel: false, responseHeaders });
61         });
62     }
64     const clientId = ((): string => {
65         const config = APPS_CONFIGURATION[APPS.PROTONPASS];
67         switch (process.platform) {
68             case 'win32':
69                 return config.windowsClientID || config.clientID;
70             case 'darwin':
71                 return config.macosClientID || config.clientID;
72             case 'linux':
73                 return config.linuxClientID || config.clientID;
74             default:
75                 return config.clientID;
76         }
77     })();
79     secureSession.webRequest.onBeforeSendHeaders(({ requestHeaders }, callback) =>
80         callback({
81             requestHeaders: {
82                 ...requestHeaders,
83                 ...getAppVersionHeaders(clientId, config.APP_VERSION),
84             },
85         })
86     );
88     // Intercept SSO login redirect to the Pass web app
89     secureSession.webRequest.onBeforeRequest(filter, async (details, callback) => {
90         if (!ctx.window) return;
92         const url = new URL(details.url);
93         if (url.pathname !== '/login') return callback({ cancel: false });
95         callback({ cancel: true });
96         const nextUrl = `${MAIN_WINDOW_WEBPACK_ENTRY}#/login${url.hash}`;
97         await ctx.window.loadURL(nextUrl);
98     });
100     return secureSession;
103 const createWindow = async (session: Session): Promise<BrowserWindow> => {
104     if (ctx.window) return ctx.window;
106     ctx.window = new BrowserWindow({
107         show: false,
108         width: 960,
109         height: 640,
110         opacity: 1,
111         autoHideMenuBar: true,
112         webPreferences: {
113             session: session,
114             sandbox: true,
115             contextIsolation: true,
116             nodeIntegration: false,
117             disableBlinkFeatures: 'Auxclick',
118             devTools: Boolean(process.env.PASS_DEBUG) || !isProdEnv(),
119             preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
120         },
121         ...(isMac ? { titleBarStyle: 'hidden', frame: false } : { titleBarStyle: 'default' }),
122         trafficLightPosition: {
123             x: 20,
124             y: 18,
125         },
126         minWidth: 881,
127         minHeight: 480,
128     });
130     setApplicationMenu(ctx.window);
132     ctx.window.on('close', (e) => {
133         if (!ctx.quitting) {
134             e.preventDefault();
135             ctx.window?.hide();
136         }
137     });
139     ctx.window.on('closed', () => (ctx.window = null));
141     await ctx.window.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
143     ctx.window.show();
145     return ctx.window;
148 const createTrayIcon = (session: Session) => {
149     const trayIconName = (() => {
150         switch (process.platform) {
151             case 'darwin':
152                 return 'trayTemplate.png';
153             case 'win32':
154                 return 'logo.ico';
155             default:
156                 return 'tray.png';
157         }
158     })();
160     const trayIconPath = join(app.isPackaged ? process.resourcesPath : app.getAppPath(), 'assets', trayIconName);
161     const trayIcon = nativeImage.createFromPath(trayIconPath);
162     const tray = new Tray(trayIcon);
163     tray.setToolTip('Proton Pass');
165     const onOpenPassHandler = async () => {
166         const window = await createWindow(session);
167         window.show();
168     };
170     const contextMenu = Menu.buildFromTemplate([
171         { label: 'Open Proton Pass', click: onOpenPassHandler },
172         { type: 'separator' },
173         { label: 'Quit', role: 'quit', click: app.quit },
174     ]);
176     tray.setContextMenu(contextMenu);
178     if (process.platform === 'win32') tray.on('double-click', onOpenPassHandler);
181 const onActivate = (secureSession: Session) => () => {
182     if (ctx.window) return ctx.window.show();
183     if (BrowserWindow.getAllWindows().length === 0) return createWindow(secureSession);
186 if (!app.requestSingleInstanceLock()) app.quit();
188 await startup(ctx);
190 // This method will be called when Electron has finished
191 // initialization and is ready to create browser windows.
192 // Some APIs can only be used after this event occurs.
193 app.addListener('ready', async () => {
194     const secureSession = createSession();
195     const handleActivate = onActivate(secureSession);
197     // Use dark title bar
198     nativeTheme.themeSource = 'dark';
200     // Create tray icon
201     createTrayIcon(secureSession);
203     // On OS X it's common to re-create a window in the app when the
204     // dock icon is clicked and there are no other windows open.
205     app.addListener('activate', handleActivate);
207     // On Windows, launching Pass while it's already running shold focus
208     // or create the main window of the existing process
209     app.addListener('second-instance', handleActivate);
211     // Prevent hiding windows when explicitly quitting
212     app.addListener('before-quit', () => (ctx.quitting = true));
214     await createWindow(secureSession);
216     updateElectronApp({
217         session: secureSession,
218         updateSource: {
219             type: SourceType.StaticStorage,
220             baseUrl: `https://proton.me/download/PassDesktop/${process.platform}/${ARCH}`,
221         },
222     });
225 app.addListener('web-contents-created', (_, contents) => {
226     contents.addListener('will-attach-webview', (evt) => evt.preventDefault());
228     const allowedHosts: string[] = [
229         new URL(config.API_URL).host,
230         new URL(config.SSO_URL).host,
231         getAppUrlFromApiUrl(config.API_URL, APPS.PROTONPASS).host,
232     ];
234     contents.addListener('will-navigate', (evt, href) => {
235         if (href.startsWith(MAIN_WINDOW_WEBPACK_ENTRY)) return;
237         const url = new URL(href);
239         // Prevent opening URLs outside of account
240         if (!allowedHosts.includes(url.host) || !['/authorize', '/login'].includes(url.pathname)) {
241             evt.preventDefault();
242             logger.warn(`[will-navigate] preventDefault: ${url.toString()}`);
243             return;
244         }
246         // Open Create account externally
247         if (url.searchParams.has('t') && url.searchParams.get('t') === ForkType.SIGNUP) {
248             evt.preventDefault();
249             logger.warn(`[will-navigate] openExternal: ${url.toString()}`);
250             return shell.openExternal(href).catch(noop);
251         }
252     });
254     contents.setWindowOpenHandler(({ url: href }) => {
255         const url = new URL(href);
257         // Shell out to the system browser if http(s)
258         if (['http:', 'https:'].includes(url.protocol)) shell.openExternal(href).catch(noop);
260         // Always deny opening external links in-app
261         return { action: 'deny' };
262     });
265 // Quit when all windows are closed, except on macOS. There, it's common
266 // for applications and their menu bar to stay active until the user quits
267 // explicitly with Cmd + Q.
268 app.addListener('window-all-closed', () => !isMac && app.quit());
269 app.addListener('will-finish-launching', () => isWindows && app.setAppUserModelId(WINDOWS_APP_ID));