-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathmain.tsx
More file actions
1529 lines (1308 loc) · 44.8 KB
/
Copy pathmain.tsx
File metadata and controls
1529 lines (1308 loc) · 44.8 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
app,
dialog,
net,
ipcMain,
BrowserWindow,
IncomingMessage,
Menu,
nativeImage,
Notification,
type MenuItemConstructorOptions,
nativeTheme,
protocol,
} from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import url from 'node:url';
import windowStateKeeper from 'electron-window-state';
import JSONbig from 'json-bigint';
import { uniq } from 'lodash';
import sanitizeFilename from 'sanitize-filename';
// handle setupevents as quickly as possible
import '../config/env';
import packageJson from '../../package.json';
import type { PermissionsNotificationPayload } from '../@types/PermissionsService';
import { WcError, WcErrorCode, encodeWcErrorForIpc } from '../@types/WcError';
import AppIcon from '../assets/img/chia64x64.png';
import { i18n } from '../config/locales';
import { isIpfsUrl } from '../util/ipfs';
import CacheManager, { CACHE_PROTOCOL } from './CacheManager';
import { checkNFTOwnership } from './api/checkNFTOwnership';
import { getKeyDetails } from './api/getKeyDetails';
import { getNetworkInfo } from './api/getNetworkInfo';
import { isMainnet } from './api/isMainnet';
import { sendCommand } from './api/sendCommand';
import { DappCommands } from './commands/DappCommands';
import { filterRequestedDappCommands } from './commands/filterRequestedDappCommands';
import { getDappCommandMetadata } from './commands/getDappCommandMetadata';
import { humanizeCommand } from './commands/humanizeCommand';
import { humanizeDappCommand } from './commands/humanizeDappCommand';
import { isAllowedCommand } from './commands/isAllowedCommand';
import { parseCommandDisplay } from './commands/parseCommandDisplay';
import { parseCommandId } from './commands/parseCommandId';
import { parseDappParams } from './commands/parseDappParams';
import AddressBookAPI from './constants/AddressBookAPI';
import AppAPI from './constants/AppAPI';
import ChiaLogsAPI from './constants/ChiaLogsAPI';
import LinkAPI from './constants/LinkAPI';
import PermissionsAPI from './constants/PermissionsAPI';
import PreferencesAPI from './constants/PreferencesAPI';
import About from './dialogs/About/About';
import Confirm, { type ConfirmProps } from './dialogs/Confirm/Confirm';
import KeyDetail from './dialogs/KeyDetail/KeyDetail';
import { migratePrefs, readPrefs, sanitizeRendererPrefs, savePrefs } from './prefs';
import { readAddressBook, saveAddressBook } from './utils/addressBook';
import chiaEnvironment, { chiaInit } from './utils/chiaEnvironment';
import { dispatchPairRequest } from './utils/dispatchPairRequest';
import downloadFile from './utils/downloadFile';
import fetchJSON from './utils/fetchJSON';
import ipcMainHandle from './utils/ipcMainHandle';
import maybeIpfsToGatewayUrl from './utils/ipfsGateway';
import isValidURL from './utils/isValidURL';
import { loadConfig, checkConfigFileExists } from './utils/loadConfig';
import { getDefaultLogPath, LogPathValidationError, resolveTrustedLogPath } from './utils/logPath';
import manageDaemonLifetime from './utils/manageDaemonLifetime';
import openExternal from './utils/openExternal';
import { openPairDialog } from './utils/openPairDialog';
import openReactDialog from './utils/openReactDialog';
import { toPairPublicRecord, type PairMetadata, type PairRecord } from './utils/pairSchemas';
import {
findPair,
getPairs,
removePair,
resetBypass,
resetBypassAll,
addPair,
updatePair,
addBypassCommand,
} from './utils/pairStore';
import * as privatePreferences from './utils/privatePreferences';
import resolveStoredMaxCacheSize from './utils/resolveStoredMaxCacheSize';
import toCamelCase from './utils/toCamelCase';
import { setUserDataDir } from './utils/userData';
import webSocketBridgeBindEvents from './utils/webSocketBridge';
const isPlaywrightTesting = process.env.PLAYWRIGHT_TESTS === 'true';
const NET = 'mainnet';
type ConfirmDialogResult = {
isAllowed: boolean;
rememberBypass: boolean;
};
app.disableHardwareAcceleration();
app.commandLine.appendSwitch('disable-http-cache');
// The cache: scheme serves NFT media to <img>/<video>/<audio> tags. Media
// elements expect protocols to buffer their responses unless the scheme is
// registered with stream: true, so without this video and audio playback
// stalls. Must be called before the app ready event.
protocol.registerSchemesAsPrivileged([
{
scheme: CACHE_PROTOCOL,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
stream: true,
},
},
]);
const appIcon = nativeImage.createFromPath(path.join(__dirname, AppIcon));
const prefs = readPrefs();
const defaultCacheFolder = path.join(app.getPath('cache'), app.getName());
const cacheDirectory: string = prefs.cacheFolder || defaultCacheFolder;
const storedMaxCacheSize: number | undefined = resolveStoredMaxCacheSize(prefs);
const cacheManager = new CacheManager({
cacheDirectory,
maxCacheSize: storedMaxCacheSize,
});
// Hoisted so IPC handlers registered below can close over them; assigned in
// `createWindow` once Electron is ready.
let mainWindow: BrowserWindow | null = null;
let networkPrefix: string | undefined;
let currentDownloadRequest: any;
let abortDownloadingFiles: boolean = false;
function sendRendererNotification(notification: PermissionsNotificationPayload) {
if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
throw new Error('No renderer window available for notification');
}
mainWindow.webContents.send(PermissionsAPI.SUBSCRIBE_FOR_NOTIFICATIONS, notification);
}
// IPC listeners
ipcMainHandle(PreferencesAPI.READ, () => readPrefs());
ipcMainHandle(PreferencesAPI.SAVE, (prefsObj) => savePrefs(sanitizeRendererPrefs(prefsObj)));
ipcMainHandle(PreferencesAPI.MIGRATE, (prefsObj) => migratePrefs(sanitizeRendererPrefs(prefsObj)));
ipcMainHandle(AddressBookAPI.SAVE, (addressBook) => saveAddressBook(addressBook));
ipcMainHandle(AddressBookAPI.READ, () => readAddressBook());
ipcMainHandle(LinkAPI.OPEN_EXTERNAL, (openUrl: string) => openExternal(openUrl));
ipcMainHandle(AppAPI.OPEN_KEY_DETAIL, async (fingerprint: number) => {
await openKeyDetail(fingerprint);
});
ipcMainHandle(AppAPI.GET_CONFIG, async () => {
const config = await loadConfig();
if (!config) {
return config;
}
return {
url: config.url,
};
});
ipcMainHandle(AppAPI.SHOW_NOTIFICATION, async (options: { title: string; body: string }) => {
const { title, body } = options;
new Notification({
title,
body,
}).show();
});
ipcMainHandle(PermissionsAPI.FIND_PAIR, (topic: string) => {
const pair = findPair(topic);
return pair ? toPairPublicRecord(pair) : undefined;
});
ipcMainHandle(PermissionsAPI.GET_PAIRS, () => getPairs().map(toPairPublicRecord));
ipcMainHandle(
PermissionsAPI.REGISTER_PAIR,
async (payload: { topic: string; mainnet: boolean; metadata: PairMetadata; commands: string[] }) => {
const { topic, mainnet, metadata, commands = [] } = payload;
if (!mainWindow) {
throw new Error('mainWindow is empty');
}
if (!topic) {
throw new Error('topic is required');
}
if (typeof mainnet !== 'boolean') {
throw new Error('mainnet flag is required');
}
if (!commands || commands.length === 0) {
throw new Error('commands are required');
}
if (!metadata) {
throw new Error('metadata are required');
}
const isMainnetValue = await isMainnet();
// if renderer and daemon are not on the same network, throw an error
if (isMainnetValue !== mainnet) {
throw new Error('Mainnet flag does not match network prefix');
}
// filter out unsupported dapp commands (commands that are not in the commands list) from the list of requested commands
const { allowed } = filterRequestedDappCommands(commands);
if (!allowed.length) {
throw new Error('No allowed commands');
}
const decision = await openPairDialog(mainWindow, metadata, commands);
if (!decision) {
return null;
}
const { bypass, fingerprint } = decision;
if (!fingerprint) {
throw new Error('fingerprint is required');
}
const pair = addPair({
topic,
mainnet,
metadata,
commands: allowed,
fingerprint,
bypass,
});
return toPairPublicRecord(pair);
},
);
ipcMainHandle(PermissionsAPI.EDIT_PAIR, async (topic: string) => {
if (!mainWindow) {
throw new Error('mainWindow is empty');
}
const pair = findPair(topic);
if (!pair) {
return null;
}
const result = await openPairDialog(mainWindow, pair.metadata, pair.commands, pair);
if (!result) {
return toPairPublicRecord(pair);
}
const { bypass } = result;
const updatedPair: Partial<PairRecord> = {
bypass,
};
return toPairPublicRecord(updatePair(topic, updatedPair));
});
ipcMainHandle(PermissionsAPI.REVOKE_PAIR, (topic: string) => {
removePair(topic);
});
ipcMainHandle(PermissionsAPI.RESET_PAIR_BYPASS, (topic: string) => {
resetBypass(topic);
});
ipcMainHandle(PermissionsAPI.RESET_ALL_PAIR_BYPASSES, () => {
resetBypassAll();
});
ipcMainHandle(PermissionsAPI.GET_COMMAND_METADATA, (command: string) => getDappCommandMetadata(command));
ipcMainHandle(
PermissionsAPI.DISPATCH_AS_PAIR,
async (payload: {
topic: string;
command: string;
params: string; // serialized params because of bigints
}) => {
const { topic, command, params } = payload;
try {
if (!mainWindow) {
throw new WcError('mainWindow is empty', WcErrorCode.INTERNAL_ERROR);
}
const dappCommandSchema = DappCommands.get(command);
if (!dappCommandSchema) {
throw new WcError(`Unknown wc command: ${command}`, WcErrorCode.METHOD_NOT_FOUND);
}
const { commandId } = dappCommandSchema;
const parsedParams = parseDappParams(command, params);
// verify all permissions and execute command after user confirmation
const result = await dispatchPairRequest(
topic,
command,
parsedParams,
// process the command
async (context) => {
const { destination, command: chiaCommand } = parseCommandId(commandId);
const response = dappCommandSchema.handler
? await dappCommandSchema.handler(parsedParams, {
...context,
sendNotification: sendRendererNotification,
canBypassCommand: (requestedCommand) =>
DappCommands.get(requestedCommand)?.allowConfirmationBypass === true,
})
: await sendCommand(chiaCommand, destination, parsedParams);
const transformedResponse = dappCommandSchema.transform ? dappCommandSchema.transform(response) : response;
// dapp is sending back camelCase response
const camelCaseResponse = toCamelCase(transformedResponse as Record<string, unknown>, {
deep: !dappCommandSchema.preserveNestedDataKeys,
});
return dappCommandSchema.handler ? camelCaseResponse : { data: camelCaseResponse };
},
// show the confirm dialog to the user
async () => {
// humanize all data from command
const { title, message, confirmLabel, destructive, rows } = await humanizeDappCommand(
command,
parsedParams,
networkPrefix,
);
const pair = findPair(topic);
if (!pair) {
throw new WcError(`Pair not found`, WcErrorCode.USER_REJECTED);
}
if (!mainWindow) {
throw new WcError('mainWindow is empty', WcErrorCode.INTERNAL_ERROR);
}
const display = await parseCommandDisplay(commandId, parsedParams);
const confirmResult = await openReactDialog<ConfirmDialogResult, ConfirmProps>(
mainWindow,
Confirm,
{
networkPrefix,
command: commandId,
data: parsedParams,
title,
message,
confirmLabel,
destructive,
rows,
pair,
display,
showBypassToggle: dappCommandSchema.allowConfirmationBypass === true,
},
{
title,
width: 640,
height: 600,
},
);
if (confirmResult && confirmResult.isAllowed === true) {
if (confirmResult.rememberBypass && dappCommandSchema.allowConfirmationBypass === true) {
addBypassCommand(topic, command);
}
return true;
}
throw new WcError('Operation cancelled by user', WcErrorCode.USER_REJECTED);
},
);
return JSONbig.stringify(result);
} catch (e) {
// Electron IPC strips custom Error properties (`code`). Re-throw with
// the code encoded into the message; renderer decodes via decodeWcErrorFromIpc.
throw new Error(encodeWcErrorForIpc(e));
}
},
);
// When there is no config file, it is assumed to be the first run.
// At that time, the config file is created here by `chia init`.
if (!checkConfigFileExists()) {
chiaInit();
}
// Set the userData directory to its location within CHIA_ROOT/gui
setUserDataDir();
const openedWindows = new Set<BrowserWindow>();
// squirrel event handled and app will exit in 1000ms, so don't do anything else
const ensureSingleInstance = () => {
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
return false;
}
app.on('second-instance', () => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.focus();
}
});
return true;
};
const ensureCorrectEnvironment = () => {
// check that the app is either packaged or running in the python venv
if (!chiaEnvironment.guessPackaged() && !('VIRTUAL_ENV' in process.env)) {
app.quit();
return false;
}
return true;
};
const createMenu = () => Menu.buildFromTemplate(getMenuTemplate());
// if any of these checks return false, don't do any other initialization since the app is quitting
if (ensureSingleInstance() && ensureCorrectEnvironment()) {
const exitPyProc = () => {};
app.on('will-quit', exitPyProc);
/** ***********************************************************
* window management
************************************************************ */
let decidedToClose = false;
let isClosing = false;
let promptOnQuit = true;
let mainWindowLaunchTasks: ((window: BrowserWindow) => void)[] = [];
const createWindow = async () => {
if (manageDaemonLifetime(NET)) {
chiaEnvironment.startChiaDaemon();
}
ipcMainHandle(AppAPI.GET_TEMP_DIR, () => app.getPath('temp'));
ipcMainHandle(AppAPI.GET_VERSION, () => app.getVersion());
ipcMainHandle(AppAPI.SET_PROMPT_ON_QUIT, (modeBool: boolean) => {
promptOnQuit = !!modeBool;
});
ipcMainHandle(AppAPI.QUIT_GUI, () => {
promptOnQuit = false;
app.quit();
});
ipcMainHandle(AppAPI.FETCH_TEXT_RESPONSE, async (urlLocal: string, data: string) => {
if (!isValidURL(urlLocal)) {
throw new Error('Invalid URL');
}
const request = net.request({
method: 'POST',
url: urlLocal,
headers: { 'Content-Type': 'application/json' },
});
let statusCode: number | undefined;
let statusMessage: string | undefined;
const responseBody = await new Promise((resolve, reject) => {
request.on('response', (response: IncomingMessage) => {
statusCode = response.statusCode;
statusMessage = response.statusMessage;
response.on('data', (chunk) => {
const body = chunk.toString('utf8');
resolve(body);
});
response.on('error', (e: Error | string) => {
reject(new Error(typeof e === 'string' ? e : e.message));
});
});
request.on('error', (error: any) => {
reject(error);
});
request.write(data);
request.end();
});
return { statusCode, statusMessage, responseBody };
});
ipcMainHandle(AppAPI.FETCH_POOL_INFO, async (poolUrl: string) => {
const poolInfoUrl = `${poolUrl}/pool_info`;
return fetchJSON(poolInfoUrl);
});
ipcMainHandle(AppAPI.SHOW_OPEN_DIRECTORY_DIALOG, async (options: { defaultPath?: string } = {}) => {
const { defaultPath } = options;
const result = await dialog.showOpenDialog({
properties: ['openDirectory', 'showHiddenFiles'],
defaultPath,
});
if (result.canceled || !result.filePaths[0]) {
return undefined;
}
return result.filePaths[0];
});
ipcMainHandle(AppAPI.SHOW_OPEN_FILE_DIALOG_AND_READ, async (options: { extensions?: string[] } = {}) => {
const { extensions } = options;
const result = await dialog.showOpenDialog({
properties: ['openFile'],
filters: extensions ? [{ name: 'Files', extensions }] : undefined,
});
if (result.canceled || !result.filePaths[0]) {
return undefined;
}
const filePath = result.filePaths[0];
const fileContent = await fs.promises.readFile(filePath);
return {
content: fileContent,
filename: path.basename(filePath),
};
});
ipcMainHandle(AppAPI.SHOW_SAVE_DIALOG_AND_SAVE, async (options: { content: string; defaultPath?: string }) => {
const { content, defaultPath } = options;
const result = await dialog.showSaveDialog({
defaultPath,
});
if (!result.canceled && result.filePath) {
await fs.promises.writeFile(result.filePath, content);
}
return { success: true };
});
ipcMainHandle(AppAPI.DOWNLOAD, async (urlLocal: string) => {
if (!isValidURL(urlLocal)) {
return;
}
if (!mainWindow) {
console.error('mainWindow was not initialized');
return;
}
// Chromium's downloader cannot fetch the ipfs: scheme; when the user
// has enabled the gateway, download ipfs URIs through it like every
// other network path. With the option off there is nothing the
// downloader could fetch, so the request is dropped instead of handing
// Chromium a URL it silently fails on.
const downloadUrl = maybeIpfsToGatewayUrl(urlLocal);
if (isIpfsUrl(downloadUrl)) {
return;
}
mainWindow.webContents.downloadURL(downloadUrl);
});
ipcMainHandle(AppAPI.START_MULTIPLE_DOWNLOAD, async (tasks: { url: string; filename: string }[]) => {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
defaultPath: app.getPath('downloads'),
});
if (result.canceled || !result.filePaths[0]) {
return undefined;
}
const folder = result.filePaths[0];
/* eslint no-await-in-loop: off -- we want to handle each file separately! */
let totalDownloadedSize = 0;
let successFileCount = 0;
let errorFileCount = 0;
const handleDownloadProgress = (progress: any, downloadUrl: string, index: number, total: number) => {
mainWindow?.webContents.send(AppAPI.ON_MULTIPLE_DOWNLOAD_PROGRESS, {
progress,
url: downloadUrl,
index,
total,
});
};
for (let i = 0; i < tasks.length; i++) {
const { url: downloadUrl, filename } = tasks[i];
try {
if (!isValidURL(downloadUrl)) {
throw new Error('Invalid URL');
}
const sanitizedFilename = sanitizeFilename(filename);
if (sanitizedFilename !== filename) {
throw new Error(
`Filename ${filename} contains invalid characters. Filename sanitized to ${sanitizedFilename}`,
);
}
const filePath = path.join(folder, sanitizedFilename);
await downloadFile(downloadUrl, filePath, {
onProgress: (progress) => handleDownloadProgress(progress, downloadUrl, i, tasks.length),
});
const fileStats = await fs.promises.stat(filePath);
totalDownloadedSize += fileStats.size;
successFileCount++;
} catch (e: any) {
if (e.message === 'download aborted' && abortDownloadingFiles) {
break;
}
mainWindow?.webContents.send(AppAPI.ON_ERROR_DOWNLOADING_URL, downloadUrl);
errorFileCount++;
}
}
abortDownloadingFiles = false;
mainWindow?.webContents.send(AppAPI.ON_MULTIPLE_DOWNLOAD_DONE, {
totalDownloadedSize,
successFileCount,
errorFileCount,
});
return folder;
});
ipcMainHandle(AppAPI.ABORT_DOWNLOADING_FILES, async () => {
abortDownloadingFiles = true;
if (currentDownloadRequest) {
currentDownloadRequest.abort();
}
});
ipcMainHandle(AppAPI.CHECK_NFT_OWNERSHIP, async (nftId: string) => checkNFTOwnership(nftId));
ipcMainHandle(AppAPI.GET_BYPASS_COMMANDS, async () => privatePreferences.get('bypassCommands', [] as string[]));
ipcMainHandle(AppAPI.SET_BYPASS_COMMANDS, async (commands: string[]) => {
const allowedDestinations = ['chia_wallet', 'chia_full_node', 'chia_farmer', 'chia_harvester', 'daemon'];
// validate all commands
const validCommands = commands.map((nsCommand) => {
const parts = nsCommand.split('.');
if (parts.length !== 2) {
throw new Error(`Invalid command: ${nsCommand}`);
}
const [destination, command] = parts;
if (!allowedDestinations.includes(destination)) {
throw new Error(`Invalid destination: ${destination}`);
}
if (command === 'get_private_key') {
throw new Error('Private key is not allowed to be sent to the renderer process');
}
if (!command.length) {
throw new Error(`Invalid command: ${nsCommand}`);
}
return `${destination.trim()}.${command.trim()}`.toLowerCase();
});
const formattedCommands = validCommands.map((command) => `• ${command}`).join('\n');
const savePreference = await dialog.showMessageBox({
type: 'question',
buttons: [i18n._(/* i18n */ { id: 'No' }), i18n._(/* i18n */ { id: 'Yes' })],
title: i18n._(/* i18n */ { id: 'Save Command Preferences' }),
message: i18n._(
/* i18n */ {
id: 'Would you like to save preferences for the following commands?',
},
),
detail: i18n._('These commands will be executed without confirmation in the future:\n\n {commands}', {
commands: formattedCommands,
}),
});
if (savePreference.response === 1) {
privatePreferences.set('bypassCommands', uniq(validCommands));
}
});
ipcMainHandle(AppAPI.PROCESS_LAUNCH_TASKS, async () => {
const tasks = [...mainWindowLaunchTasks];
mainWindowLaunchTasks = [];
tasks.forEach((task) => task(mainWindow!));
});
ipcMainHandle(AppAPI.FOCUS_WINDOW, () => {
if (mainWindow) {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
// On macOS, app.focus() brings the entire application to the foreground
if (process.platform === 'darwin') {
app.focus({ steal: true });
}
mainWindow.focus();
// On Windows, focus() alone may not bring window to foreground due to OS restrictions.
// Using setAlwaysOnTop temporarily ensures the window comes to front.
if (process.platform === 'win32') {
mainWindow.setAlwaysOnTop(true);
mainWindow.setAlwaysOnTop(false);
}
}
});
decidedToClose = false;
const mainWindowState = windowStateKeeper({
defaultWidth: 1200,
defaultHeight: 1200,
});
await cacheManager.init();
const isDarkMode = prefs.darkMode ?? nativeTheme.shouldUseDarkColors;
const initialBgColor = isDarkMode ? '#0f252a' : '#ffffff';
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minWidth: 500,
minHeight: 500,
backgroundColor: initialBgColor,
show: isPlaywrightTesting,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
nodeIntegrationInWorker: false,
nodeIntegrationInSubFrames: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
experimentalFeatures: false,
plugins: false,
spellcheck: false,
webviewTag: false,
},
});
// allow the cache manager to handle the cache protocol
cacheManager.prepareProtocol(mainWindow.webContents.session.protocol);
function setNetworkPrefix(newNetworkPrefix: string) {
networkPrefix = newNetworkPrefix;
const isTestnet = networkPrefix === 'txch';
const title = isTestnet ? 'Chia Blockchain (Testnet)' : 'Chia Blockchain';
if (mainWindow && mainWindow.title !== title) {
mainWindow.setTitle(title);
}
}
webSocketBridgeBindEvents(mainWindow.webContents, {
onReceive: async (_id: string, data: any) => {
try {
if (networkPrefix) {
return;
}
const parsedData = JSONbig.parse(data.toString());
if (
parsedData.command === 'ping' &&
parsedData.origin === 'chia_wallet' &&
parsedData.destination === 'wallet_ui' &&
parsedData.data?.success === true
) {
const networkInfo = await getNetworkInfo();
if (networkInfo.networkPrefix) {
setNetworkPrefix(networkInfo.networkPrefix);
}
}
} catch (error) {
console.error(error);
}
},
onSend: async (_id: string, data: string) => {
if (!mainWindow) {
throw new Error('`mainWindow` is empty');
}
const parsedData = JSONbig.parse(data);
const command = parsedData.command.trim().toLowerCase();
const destination = parsedData.destination.trim().toLowerCase();
const commandId = `${destination}.${command}`;
// if renderer is trying to get the private key
if (['chia_wallet.get_private_key'].includes(commandId)) {
throw new Error('Private key is not allowed to be sent to the renderer process');
}
// if commands is allowed to run without confirmation
if (isAllowedCommand(commandId)) {
return;
}
// if user put the command in the bypass commands
const bypassCommands = privatePreferences.get<string[]>('bypassCommands', []);
if (bypassCommands.includes(commandId)) {
return;
}
const commandData = (parsedData.data ?? {}) as Record<string, unknown>;
// humanize all data from command
const { title, message, confirmLabel, destructive, rows } = await humanizeCommand(
commandId,
commandData,
networkPrefix,
);
const display = await parseCommandDisplay(commandId, commandData);
const confirmResult = await openReactDialog<ConfirmDialogResult, ConfirmProps>(
mainWindow,
Confirm,
{
networkPrefix,
command: commandId,
data: commandData,
title,
message,
confirmLabel,
destructive,
rows,
display,
},
{
title,
width: 640,
height: 600,
},
);
if (confirmResult && confirmResult.isAllowed === true) {
return;
}
throw new Error('Operation cancelled by user');
},
});
cacheManager.bindEvents(mainWindow);
mainWindowState.manage(mainWindow);
if (process.platform === 'linux') {
mainWindow.setIcon(appIcon);
}
// Reveal the window. `ready-to-show` is the preferred fast path, but on some
// compositors (notably Wayland/mutter) that event can fail to fire, which
// would otherwise leave the window hidden forever even though the page has
// loaded. Guard the show in a once-only helper and back it with
// `did-finish-load` and a timeout fallback so the window is always revealed.
let hasShownMainWindow = false;
const showMainWindow = () => {
// `mainWindow` is never reset to null on close, so a destroyed window is
// still a truthy reference; guard with `isDestroyed()` to avoid throwing
// if a trigger fires after the window is gone. Latch the flag only after a
// successful `show()` so a failed attempt doesn't block the other triggers.
if (hasShownMainWindow || !mainWindow || mainWindow.isDestroyed()) {
return;
}
mainWindow.show();
hasShownMainWindow = true;
};
mainWindow.once('ready-to-show', showMainWindow);
mainWindow.webContents.once('did-finish-load', showMainWindow);
setTimeout(showMainWindow, 5000);
// don't show remote daeomn detials in the title bar
if (!manageDaemonLifetime(NET)) {
mainWindow.webContents.on('did-finish-load', async () => {
const { url: urlLocal } = await loadConfig();
if (mainWindow) {
mainWindow.setTitle(`${app.getName()} [${urlLocal}]`);
}
});
}
// Uncomment this to open devtools by default
// if (!guessPackaged()) {
// mainWindow.webContents.openDevTools();
// }
mainWindow.on('close', async (e) => {
// if the daemon isn't local we aren't going to try to start/stop it
if (decidedToClose || !manageDaemonLifetime(NET)) {
return;
}
if (!mainWindow) {
throw new Error('`mainWindow` is empty');
}
e.preventDefault();
if (!isClosing) {
isClosing = true;
let keepBackgroundRunning: boolean | undefined;
const p = readPrefs();
if (typeof p.keepBackgroundRunning === 'boolean') {
keepBackgroundRunning = p.keepBackgroundRunning;
}
if (promptOnQuit) {
const choice = await dialog.showMessageBox({
type: 'question',
buttons: [i18n._(/* i18n */ { id: 'No' }), i18n._(/* i18n */ { id: 'Yes' })],
title: i18n._(/* i18n */ { id: 'Confirm' }),
message: i18n._(
/* i18n */ {
id: 'Are you sure you want to quit?',
},
),
checkboxChecked: keepBackgroundRunning ?? false,
checkboxLabel: i18n._(/* i18n */ { id: 'Keep service running in the background' }),
});
if (keepBackgroundRunning !== choice.checkboxChecked) {
savePrefs({ ...p, keepBackgroundRunning: choice.checkboxChecked });
}
if (choice.response === 0) {
isClosing = false;
return;
}
keepBackgroundRunning = choice.checkboxChecked;
}
isClosing = false;
decidedToClose = true;
// save the window state and unmange so we don't restore the mini exiting state
mainWindowState.saveState(mainWindow);
mainWindowState.unmanage();
if (keepBackgroundRunning) {
mainWindow.close();
openedWindows.forEach((win) => win.close());
return;
}
mainWindow.webContents.send(AppAPI.ON_EXIT_DAEMON);
mainWindow.setBounds({ height: 500, width: 500 });
mainWindow.center();
ipcMain.handle(AppAPI.DAEMON_EXITED, async () => {
mainWindow?.close();
openedWindows.forEach((win) => win.close());
});
}
});
const startUrl =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: url.format({