forked from electron/electron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chromium-spec.ts
3558 lines (3186 loc) · 139 KB
/
chromium-spec.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
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 { expect } from 'chai';
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents, dialog, MessageBoxOptions } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import * as https from 'node:https';
import * as http from 'node:http';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as url from 'node:url';
import * as ChildProcess from 'node:child_process';
import { EventEmitter, once } from 'node:events';
import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
import { PipeTransport } from './pipe-transport';
import * as ws from 'ws';
import { setTimeout } from 'node:timers/promises';
import { AddressInfo } from 'node:net';
const features = process._linkedBinding('electron_common_features');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
describe('reporting api', () => {
it('sends a report for an intervention', async () => {
const reporting = new EventEmitter();
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
cb(0);
});
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options, (req, res) => {
if (req.url?.endsWith('report')) {
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
req.on('end', () => {
reporting.emit('report', JSON.parse(data));
});
}
const { port } = server.address() as any;
res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`);
res.setHeader('Content-Type', 'text/html');
res.end('<script>window.navigator.vibrate(1)</script>');
});
await listen(server);
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as AddressInfo).port}/a`);
const [reports] = await reportGenerated;
expect(reports).to.be.an('array').with.lengthOf(1);
const { type, url, body } = reports[0];
expect(type).to.equal('intervention');
expect(url).to.equal(url);
expect(body.id).to.equal('NavigatorVibrate');
expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/);
} finally {
bw.destroy();
server.close();
}
});
});
describe('window.postMessage', () => {
afterEach(async () => {
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await once(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
});
describe('focus handling', () => {
let webviewContents: WebContents;
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
});
const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await once(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
const [, focusedElementId] = await once(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
};
it('moves focus to the next focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
};
it('moves focus to the previous focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will load successfully but its body will be emptied out
// by CORB, so we don't expect a syntax error.
s.onload = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
describe('csp', () => {
for (const sandbox of [true, false]) {
describe(`when sandbox: ${sandbox}`, () => {
for (const contextIsolation of [true, false]) {
describe(`when contextIsolation: ${contextIsolation}`, () => {
it('prevents eval from running in an inline script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
</head>
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.match(/Refused to evaluate a string/);
});
it('does not prevent eval from running in an inline script when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.equal('true');
});
it('prevents eval from running in executeJavaScript', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>');
await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected();
});
it('does not prevent eval from running in executeJavaScript when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,');
expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true();
});
});
}
});
}
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
const currentLocale = app.getLocale();
const currentSystemLocale = app.getSystemLocale();
const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages());
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await once(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replaceAll(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
};
it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await once(appProcess, 'exit');
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
});
}
});
});
});
});
describe('chromium features', () => {
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('first party sets', () => {
const fps = [
'https://fps-member1.glitch.me',
'https://fps-member2.glitch.me',
'https://fps-member3.glitch.me'
];
it('loads first party sets', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
it('loads sets from the command line', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
const args = [appPath, `--use-first-party-set=${fps}`];
const fpsProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.keyboard', () => {
afterEach(closeAllWindows);
it('getLayoutMap() should return a KeyboardLayoutMap object', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const size = await w.webContents.executeJavaScript(`
navigator.keyboard.getLayoutMap().then(map => map.size)
`);
expect(size).to.be.a('number');
});
it('should lock the keyboard', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'modal.html'));
// Test that without lock, with ESC:
// - the window leaves fullscreen
// - the dialog is not closed
const enterFS1 = once(w, 'enter-full-screen');
await w.webContents.executeJavaScript('document.body.requestFullscreen()', true);
await enterFS1;
await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').showModal()', true);
const open1 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(open1).to.be.true();
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await setTimeout(1000);
const openAfter1 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(openAfter1).to.be.true();
expect(w.isFullScreen()).to.be.false();
// Test that with lock, with ESC:
// - the window does not leave fullscreen
// - the dialog is closed
const enterFS2 = once(w, 'enter-full-screen');
await w.webContents.executeJavaScript(`
navigator.keyboard.lock(['Escape']);
document.body.requestFullscreen();
`, true);
await enterFS2;
await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').showModal()', true);
const open2 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(open2).to.be.true();
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await setTimeout(1000);
const openAfter2 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(openAfter2).to.be.false();
expect(w.isFullScreen()).to.be.true();
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not allow nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
const data = await w.webContents.executeJavaScript(`
navigator.serviceWorker.register('worker-no-node.js', {
scope: './'
}).then(() => navigator.serviceWorker.ready)
new Promise((resolve) => {
navigator.serviceWorker.onmessage = event => resolve(event.data);
});
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
describe('navigator.geolocation', () => {
ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
});
const message = once(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
callback(false);
} else {
callback(true);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
});
ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'geolocation-spec'
}
});
w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
callback(true);
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
x => resolve({coords: x.coords, timestamp: x.timestamp}),
err => reject(new Error(err.message))))`);
expect(position).to.have.property('coords');
expect(position).to.have.property('timestamp');
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
it('Worker can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
worker.postMessage(message);
eventPromise.then(t => t.data)
`);
expect(data).to.equal('ping');
});
it('Worker has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker_node.js');
new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('Worker has node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/worker.html`);
const [, data] = await once(ipcMain, 'worker-result');
expect(data).to.equal('object function object function');
});
describe('SharedWorker', () => {
it('can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
worker.port.postMessage(message);
eventPromise
`);
expect(data).to.equal('ping');
});
it('has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('does not have node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
});
describe('form submit', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
res.end(`body:${body}`);
});
});
serverUrl = (await listen(server)).url;
});
after(async () => {
server.close();
await closeAllWindows();
});
for (const isSandboxEnabled of [true, false]) {
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const loadPromise = once(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
`);
await loadPromise;
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;