-
Notifications
You must be signed in to change notification settings - Fork 704
Expand file tree
/
Copy pathmain.ts
More file actions
335 lines (268 loc) · 11.5 KB
/
Copy pathmain.ts
File metadata and controls
335 lines (268 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { BrowserWindow, Menu, type Session, Tray, app, nativeImage, nativeTheme, session, shell } from 'electron';
import { join } from 'path';
import { ForkType } from '@proton/shared/lib/authentication/fork/constants';
import { APPS, APPS_CONFIGURATION } from '@proton/shared/lib/constants';
import { getAppVersionHeaders } from '@proton/shared/lib/fetch/headers';
import { getAppUrlFromApiUrl, getSecondLevelDomain } from '@proton/shared/lib/helpers/url';
import noop from '@proton/utils/noop';
import config from './app/config';
import { WINDOWS_APP_ID } from './constants';
import { migrateSameSiteCookies, upgradeSameSiteCookies } from './lib/cookies';
import { fixSSOUrl } from './lib/sso';
import { getTheme } from './lib/theming';
import { setTagCookie } from './lib/updater/helpers';
import { getUpdateStore } from './lib/updater/store';
import { startUpdater } from './lib/updater/updater';
import { userAgent } from './lib/user-agent';
import { onHideWindow } from './lib/window';
import { getWindowConfig, registerWindowManagementHandlers } from './lib/window-management';
import { setApplicationMenu } from './menu-view/application-menu';
import { startup } from './startup';
import { certificateVerifyProc } from './tls';
import type { PassElectronContext } from './types';
import logger from './utils/logger';
import { isMac, isProdEnv, isWindows } from './utils/platform';
const ctx: PassElectronContext = { session: null, window: null, quitting: false };
const DOMAIN = getSecondLevelDomain(new URL(config.API_URL).hostname);
const createSession = () => {
const partitionKey = ENV !== 'production' ? 'app-dev' : 'app';
const secureSession = session.fromPartition(`persist:${partitionKey}`, { cache: false });
const filter = { urls: [`${getAppUrlFromApiUrl(config.API_URL, APPS.PROTONPASS)}*`] };
secureSession.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false));
// Use certificate pinning
secureSession.setCertificateVerifyProc(certificateVerifyProc);
secureSession.webRequest.onHeadersReceived({ urls: [`https://*.${DOMAIN}/*`] }, (details, callback) => {
// FIXME: Temporary bypass for SSO callback using the wrong protocol
fixSSOUrl(details);
if (isProdEnv()) {
if (!details.responseHeaders) details.responseHeaders = {};
const { responseHeaders, frame } = details;
const appRequest = frame?.url?.startsWith('file://') ?? false;
/** If the request is made from a `file://` url: migrate ALL `SameSite` directives
* to `None` and allow cross-origin requests for the API. If not then only upgrade
* EMPTY `SameSite` cookie directives to `None` to preserve `Session-ID` cookies */
if (appRequest) {
migrateSameSiteCookies(responseHeaders);
responseHeaders['access-control-allow-headers'] = Object.keys(responseHeaders);
responseHeaders['access-control-allow-origin'] = ['file://'];
responseHeaders['access-control-allow-credentials'] = ['true'];
} else upgradeSameSiteCookies(responseHeaders);
}
callback({ cancel: false, responseHeaders: details.responseHeaders });
});
const clientId = ((): string => {
const config = APPS_CONFIGURATION[APPS.PROTONPASS];
switch (process.platform) {
case 'win32':
return config.windowsClientID || config.clientID;
case 'darwin':
return config.macosClientID || config.clientID;
case 'linux':
return config.linuxClientID || config.clientID;
default:
return config.clientID;
}
})();
secureSession.webRequest.onBeforeSendHeaders(({ requestHeaders }, callback) =>
callback({
requestHeaders: {
...requestHeaders,
...getAppVersionHeaders(clientId, config.APP_VERSION),
},
})
);
// Intercept SSO login redirect to the Pass web app
secureSession.webRequest.onBeforeRequest(filter, async (details, callback) => {
if (!ctx.window) return;
const url = new URL(details.url);
if (url.pathname !== '/login') return callback({ cancel: false });
callback({ cancel: true });
const nextUrl = `${MAIN_WINDOW_WEBPACK_ENTRY}#/login${url.hash}`;
await ctx.window.loadURL(nextUrl);
});
secureSession.setUserAgent(userAgent());
void setTagCookie(secureSession, getUpdateStore().beta);
return secureSession;
};
const createWindow = async (session: Session): Promise<BrowserWindow> => {
if (ctx.window) return ctx.window;
const { x, y, minHeight, minWidth, height, width, maximized, zoomLevel } = getWindowConfig();
ctx.window = new BrowserWindow({
x,
y,
minHeight,
minWidth,
width,
height,
show: false,
opacity: 1,
autoHideMenuBar: true,
icon: join(app.isPackaged ? process.resourcesPath : app.getAppPath(), 'assets', 'logo.png'),
webPreferences: {
session: session,
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
disableBlinkFeatures: 'Auxclick',
devTools: Boolean(process.env.PASS_DEBUG) || !isProdEnv(),
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
...(isMac() ? { titleBarStyle: 'hidden', frame: false } : { titleBarStyle: 'default' }),
trafficLightPosition: {
x: 20,
y: 18,
},
acceptFirstMouse: true,
});
if (zoomLevel) {
ctx.window.webContents.setZoomLevel(zoomLevel);
}
setApplicationMenu(ctx.window);
registerWindowManagementHandlers(ctx.window);
ctx.window.on('show', () => {
if (isMac()) void app.dock?.show();
});
ctx.window.on('close', (e) => {
if (!ctx.quitting) {
e.preventDefault();
ctx.window?.hide();
onHideWindow(() => ctx.window);
if (isMac()) app.dock?.hide();
}
});
ctx.window.on('closed', () => (ctx.window = null));
await ctx.window.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
ctx.window.show();
if (maximized) {
ctx.window.maximize();
}
return ctx.window;
};
const createTrayIcon = (session: Session) => {
const trayIconName = (() => {
switch (process.platform) {
case 'darwin':
return 'trayTemplate.png';
case 'win32':
return 'logo.ico';
default:
return 'tray.png';
}
})();
const trayIconPath = join(app.isPackaged ? process.resourcesPath : app.getAppPath(), 'assets', trayIconName);
const trayIcon = nativeImage.createFromPath(trayIconPath);
const tray = new Tray(trayIcon);
tray.setToolTip('Proton Pass');
const onOpenPassHandler = async () => {
const window = await createWindow(session);
window.show();
};
const contextMenu = Menu.buildFromTemplate([
{ label: 'Open Proton Pass', click: onOpenPassHandler },
{ type: 'separator' },
{ label: 'Quit', role: 'quit', click: app.quit },
]);
tray.setContextMenu(contextMenu);
if (process.platform === 'win32') tray.on('double-click', onOpenPassHandler);
};
const onActivate = (secureSession: Session) => () => {
if (ctx.window) return ctx.window.show();
if (BrowserWindow.getAllWindows().length === 0) return createWindow(secureSession);
};
if (!app.requestSingleInstanceLock()) app.quit();
app.addListener('web-contents-created', (_, contents) => {
contents.addListener('will-attach-webview', (evt) => evt.preventDefault());
const allowedHosts: string[] = [
new URL(config.API_URL).host,
new URL(config.SSO_URL).host,
getAppUrlFromApiUrl(config.API_URL, APPS.PROTONPASS).host,
];
contents.addListener('will-navigate', (evt) => {
// Do nothing if navigating to the bundled web app
if (evt.url.startsWith(MAIN_WINDOW_WEBPACK_ENTRY)) return;
const url = new URL(evt.url);
// Open 'Create account' externally
if (
url.origin === config.SSO_URL &&
url.pathname === '/authorize' &&
url.searchParams.get('t') === ForkType.SIGNUP
) {
evt.preventDefault();
logger.debug(`[will-navigate] allow (external): ${url.toString()}`);
return shell.openExternal(url.href).catch(noop);
}
// Allow account URLs
if (allowedHosts.includes(url.host) && ['/authorize', '/login'].includes(url.pathname)) {
logger.debug(`[will-navigate] allow (main frame): ${url.href}`);
return;
}
// Allow SSO flows (happens in a dedicated window)
if (
evt.initiator?.url?.startsWith(config.SSO_URL) ||
ctx.window?.webContents.getURL().startsWith(config.SSO_URL)
) {
logger.debug(`[will-navigate] allow (external frame): ${url.href}`);
return;
}
// Let OS handle anything else
evt.preventDefault();
logger.debug(`[will-navigate] allow (external): ${url.href}`);
return shell.openExternal(evt.url).catch(noop);
});
contents.setWindowOpenHandler(({ url: href }) => {
const url = new URL(href);
// Open a new window for SSO
if (url.origin === config.SSO_URL && url.pathname.match(/(\/api)?\/auth\/sso/)) {
logger.debug(`[setWindowOpenHandler] opening url in window: ${href}`);
return { action: 'allow' };
}
// Shell out to the OS handler for http(s) and mailto
if (['http:', 'https:', 'mailto:'].includes(url.protocol)) {
logger.debug(`[setWindowOpenHandler] opening url externally: ${href}`);
shell.openExternal(href).catch(noop);
}
// Always deny opening extra windows
return { action: 'deny' };
});
});
// Startup all Pass handlers
const cleanup = await startup(app, ctx);
// Wait for Electron to be initialized
await app.whenReady();
// Always use system DNS settings
app.configureHostResolver({
enableAdditionalDnsQueryTypes: false,
enableBuiltInResolver: true,
secureDnsMode: 'off',
secureDnsServers: [],
});
ctx.session = createSession();
// Match title bar with the saved (or default) theme
nativeTheme.themeSource = getTheme();
const handleActivate = onActivate(ctx.session);
// Create tray icon
createTrayIcon(ctx.session);
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
app.addListener('activate', handleActivate);
// On Windows, launching Pass while it's already running shold focus
// or create the main window of the existing process
app.addListener('second-instance', handleActivate);
// Prevent hiding windows when explicitly quitting
app.addListener('before-quit', () => (ctx.quitting = true));
await createWindow(ctx.session);
startUpdater(ctx.session);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.addListener('window-all-closed', () => !isMac() && app.quit());
app.addListener('will-finish-launching', () => isWindows() && app.setAppUserModelId(WINDOWS_APP_ID));
// Call cleanup functions when quitting
let exiting = false;
app.addListener('will-quit', async (event) => {
if (exiting) return;
event.preventDefault();
exiting = true;
await cleanup();
app.exit(0);
});