-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
main.ts
206 lines (180 loc) · 6.04 KB
/
main.ts
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
/**
* Copyright 2023 Gravitational, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { spawn } from 'child_process';
import path from 'path';
import { app, globalShortcut, shell } from 'electron';
import MainProcess from 'teleterm/mainProcess';
import { getRuntimeSettings } from 'teleterm/mainProcess/runtimeSettings';
import { enableWebHandlersProtection } from 'teleterm/mainProcess/protocolHandler';
import { LoggerColor, createFileLoggerService } from 'teleterm/services/logger';
import Logger from 'teleterm/logger';
import * as types from 'teleterm/types';
import { createConfigService } from 'teleterm/services/config';
import { createFileStorage } from 'teleterm/services/fileStorage';
import { WindowsManager } from 'teleterm/mainProcess/windowsManager';
if (app.requestSingleInstanceLock()) {
initializeApp();
} else {
console.log('Attempted to open a second instance of the app, exiting.');
// All windows will be closed immediately without asking the user,
// and the before-quit and will-quit events will not be emitted.
app.exit(1);
}
function initializeApp(): void {
let devRelaunchScheduled = false;
const settings = getRuntimeSettings();
const logger = initMainLogger(settings);
const appStateFileStorage = createFileStorage({
filePath: path.join(settings.userDataDir, 'app_state.json'),
debounceWrites: true,
});
const configFileStorage = createFileStorage({
filePath: path.join(settings.userDataDir, 'app_config.json'),
debounceWrites: false,
});
const configJsonSchemaFileStorage = createFileStorage({
filePath: path.join(settings.userDataDir, 'schema_app_config.json'),
debounceWrites: false,
});
const configService = createConfigService({
configFile: configFileStorage,
jsonSchemaFile: configJsonSchemaFileStorage,
platform: settings.platform,
});
const windowsManager = new WindowsManager(appStateFileStorage, settings);
process.on('uncaughtException', error => {
logger.error('', error);
app.quit();
});
// init main process
const mainProcess = MainProcess.create({
settings,
logger,
configService,
fileStorage: appStateFileStorage,
windowsManager,
});
app.on(
'certificate-error',
(event, webContents, url, error, certificate, callback) => {
// allow certs errors for localhost:8080
if (
settings.dev &&
new URL(url).host === 'localhost:8080' &&
error === 'net::ERR_CERT_AUTHORITY_INVALID'
) {
event.preventDefault();
callback(true);
} else {
callback(false);
console.error(error);
}
}
);
app.on('will-quit', async event => {
event.preventDefault();
appStateFileStorage.writeSync();
globalShortcut.unregisterAll();
try {
await mainProcess.dispose();
} catch (e) {
logger.error('Failed to gracefully dispose of main process', e);
} finally {
app.exit();
}
});
app.on('quit', () => {
if (devRelaunchScheduled) {
const [bin, ...args] = process.argv;
const child = spawn(bin, args, {
env: process.env,
detached: true,
stdio: 'inherit',
});
child.unref();
}
});
app.on('second-instance', () => {
windowsManager.focusWindow();
});
app.whenReady().then(() => {
if (mainProcess.settings.dev) {
// allow restarts on F6
globalShortcut.register('F6', () => {
devRelaunchScheduled = true;
app.quit();
});
}
enableWebHandlersProtection();
windowsManager.createWindow();
});
// Limit navigation capabilities to reduce the attack surface.
// See TEL-Q122-19 from "Teleport Core Testing Q1 2022" security audit.
//
// See also points 12, 13 and 14 from the Electron's security tutorial.
// https://github.com/electron/electron/blob/v17.2.0/docs/tutorial/security.md#12-verify-webview-options-before-creation
app.on('web-contents-created', (_, contents) => {
contents.on('will-navigate', (event, navigationUrl) => {
logger.warn(`Navigation to ${navigationUrl} blocked by 'will-navigate'`);
event.preventDefault();
});
// The usage of webview is blocked by default, but let's include the handler just in case.
// https://github.com/electron/electron/blob/v17.2.0/docs/api/webview-tag.md#enabling
contents.on('will-attach-webview', (event, _, params) => {
logger.warn(
`Opening a webview to ${params.src} blocked by 'will-attach-webview'`
);
event.preventDefault();
});
contents.setWindowOpenHandler(details => {
const url = new URL(details.url);
function isUrlSafe(): boolean {
if (url.protocol !== 'https:') {
return false;
}
if (url.host === 'goteleport.com') {
return true;
}
if (
url.host === 'github.com' &&
url.pathname.startsWith('/gravitational/')
) {
return true;
}
}
// Open links to documentation and GitHub issues in the external browser.
// They need to have `target` set to `_blank`.
if (isUrlSafe()) {
shell.openExternal(url.toString());
} else {
logger.warn(
`Opening a new window to ${url} blocked by 'setWindowOpenHandler'`
);
}
return { action: 'deny' };
});
});
}
function initMainLogger(settings: types.RuntimeSettings) {
const service = createFileLoggerService({
dev: settings.dev,
dir: settings.userDataDir,
name: 'main',
loggerNameColor: LoggerColor.Magenta,
});
Logger.init(service);
return new Logger('Main');
}