forked from Kaliiiiiiiiii-Vinyzu/patchright
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchright.patch
More file actions
9284 lines (9117 loc) · 332 KB
/
patchright.patch
File metadata and controls
9284 lines (9117 loc) · 332 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
# NOTE: This patch file is generated automatically and is not used, it is only for documentation. The driver is actually patched using [patchright_driver_patch](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/blob/main/patchright_driver_patch.js), see [the workflow](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/blob/main/.github/workflows/patchright_workflow.yml)
diff -ruN playwright/node_modules/playwright-core/src/server/browserContext.ts patchright/node_modules/playwright-core/src/server/browserContext.ts
---
+++
@@ -146,7 +146,7 @@
`);
}
if (this._options.serviceWorkers === 'block')
- await this.addInitScript(undefined, `\nif (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };\n`);
+ await this.addInitScript(undefined, `navigator.serviceWorker.register = async () => { };`);
if (this._options.permissions)
await this.grantPermissions(this._options.permissions);
@@ -326,27 +326,19 @@
if (page.getBinding(name))
throw new Error(`Function "${name}" has been already registered in one of the pages`);
}
- await progress.race(this.exposePlaywrightBindingIfNeeded());
const binding = new PageBinding(name, playwrightBinding, needsHandle);
binding.forClient = forClient;
this._pageBindings.set(name, binding);
- try {
- await progress.race(this.doAddInitScript(binding.initScript));
- await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, 'main'));
- return binding;
- } catch (error) {
- this._pageBindings.delete(name);
- throw error;
- }
+ await this.doExposeBinding(binding);
}
async removeExposedBindings(bindings: PageBinding[]) {
- bindings = bindings.filter(binding => this._pageBindings.get(binding.name) === binding);
- for (const binding of bindings)
- this._pageBindings.delete(binding.name);
- await this.doRemoveInitScripts(bindings.map(binding => binding.initScript));
- const cleanup = bindings.map(binding => `{ ${binding.cleanupScript} };\n`).join('');
- await this.safeNonStallingEvaluateInAllFrames(cleanup, 'main');
+
+ for (const key of this._pageBindings.keys()) {
+ if (!key.startsWith('__pw')) this._pageBindings.delete(key);
+ }
+ await this.doRemoveExposedBindings();
+
}
async grantPermissions(permissions: string[], origin?: string) {
@@ -463,9 +455,10 @@
}
async removeInitScripts(initScripts: InitScript[]) {
- const set = new Set(initScripts);
- this.initScripts = this.initScripts.filter(script => !set.has(script));
- await this.doRemoveInitScripts(initScripts);
+
+ this.initScripts.splice(0, this.initScripts.length);
+ await this.doRemoveInitScripts();
+
}
async addRequestInterceptor(progress: Progress, handler: network.RouteHandler): Promise<void> {
diff -ruN playwright/node_modules/playwright-core/src/server/chromium/chromiumSwitches.ts patchright/node_modules/playwright-core/src/server/chromium/chromiumSwitches.ts
---
+++
@@ -47,26 +47,16 @@
'--disable-field-trial-config', // https://source.chromium.org/chromium/chromium/src/+/main:testing/variations/README.md
'--disable-background-networking',
'--disable-background-timer-throttling',
- '--disable-backgrounding-occluded-windows',
- '--disable-back-forward-cache', // Avoids surprises like main request not being intercepted during page.goBack().
- '--disable-breakpad',
- '--disable-client-side-phishing-detection',
- '--disable-component-extensions-with-background-pages',
- '--disable-component-update', // Avoids unneeded network activity after startup.
+ '--disable-backgrounding-occluded-windows', // Avoids surprises like main request not being intercepted during page.goBack().
+ '--disable-breakpad', // Avoids unneeded network activity after startup.
'--no-default-browser-check',
- '--disable-default-apps',
'--disable-dev-shm-usage',
- '--disable-extensions',
'--disable-features=' + disabledFeatures(assistantMode).join(','),
channel === 'chromium-tip-of-tree' ? '--enable-features=CDPScreenshotNewSurface' : '',
- '--allow-pre-commit-input',
'--disable-hang-monitor',
- '--disable-ipc-flooding-protection',
- '--disable-popup-blocking',
'--disable-prompt-on-repost',
'--disable-renderer-backgrounding',
'--force-color-profile=srgb',
- '--metrics-recording-only',
'--no-first-run',
'--password-store=basic',
'--use-mock-keychain',
@@ -75,9 +65,7 @@
'--export-tagged-pdf',
// https://chromium-review.googlesource.com/c/chromium/src/+/4853540
'--disable-search-engine-choice-screen',
- // https://issues.chromium.org/41491762
- '--unsafely-disable-devtools-self-xss-warnings',
// Edge can potentially restart on Windows (msRelaunchNoCompatLayer) which looses its file descriptors (stdout/stderr) and CDP (3/4). Disable until fixed upstream.
'--edge-skip-compat-layer-relaunch',
- assistantMode ? '' : '--enable-automation',
+ '--disable-blink-features=AutomationControlled'
].filter(Boolean);
diff -ruN playwright/node_modules/playwright-core/src/server/chromium/crBrowser.ts patchright/node_modules/playwright-core/src/server/chromium/crBrowser.ts
---
+++
@@ -509,8 +509,9 @@
}
async doRemoveInitScripts(initScripts: InitScript[]) {
- for (const page of this.pages())
- await (page.delegate as CRPage).removeInitScripts(initScripts);
+
+ for (const page of this.pages()) await (page.delegate as CRPage).removeInitScripts();
+
}
async doUpdateRequestInterception(): Promise<void> {
@@ -620,4 +621,16 @@
const rootSession = await this._browser._clientRootSession();
return rootSession.attachToTarget(targetId);
}
+
+ async doExposeBinding(binding: PageBinding) {
+
+ for (const page of this.pages()) await (page.delegate as CRPage).exposeBinding(binding);
+
+ }
+
+ async doRemoveExposedBindings() {
+
+ for (const page of this.pages()) await (page.delegate as CRPage).removeExposedBindings();
+
+ }
}
diff -ruN playwright/node_modules/playwright-core/src/server/chromium/crDevTools.ts patchright/node_modules/playwright-core/src/server/chromium/crDevTools.ts
---
+++
@@ -67,7 +67,6 @@
}).catch(e => null);
});
Promise.all([
- session.send('Runtime.enable'),
session.send('Runtime.addBinding', { name: kBindingName }),
session.send('Page.enable'),
session.send('Page.addScriptToEvaluateOnNewDocument', { source: `
diff -ruN playwright/node_modules/playwright-core/src/server/chromium/crNetworkManager.ts patchright/node_modules/playwright-core/src/server/chromium/crNetworkManager.ts
---
+++
@@ -1,3 +1,5 @@
+// patchright - custom imports
+import crypto from 'crypto';
/**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
@@ -156,7 +158,7 @@
const enabled = this._protocolRequestInterceptionEnabled;
if (initial && !enabled)
return;
- const cachePromise = info.session.send('Network.setCacheDisabled', { cacheDisabled: enabled });
+ const cachePromise = info.session.send('Network.setCacheDisabled', { cacheDisabled: false });
let fetchPromise = Promise.resolve<any>(undefined);
if (!info.workerFrame) {
if (enabled)
@@ -238,6 +240,7 @@
}
_onRequestPaused(sessionInfo: SessionInfo, event: Protocol.Fetch.requestPausedPayload) {
+ if (this._alreadyTrackedNetworkIds.has(event.networkId)) return;
if (!event.networkId) {
// Fetch without networkId means that request was not recognized by inspector, and
// it will never receive Network.requestWillBeSent. Continue the request to not affect it.
@@ -276,6 +279,7 @@
}
_onRequest(requestWillBeSentSessionInfo: SessionInfo, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedSessionInfo: SessionInfo | undefined, requestPausedEvent: Protocol.Fetch.requestPausedPayload | undefined) {
+ if (this._alreadyTrackedNetworkIds.has(requestWillBeSentEvent.initiator.requestId)) return;
if (requestWillBeSentEvent.request.url.startsWith('data:'))
return;
let redirectedFrom: InterceptableRequest | null = null;
@@ -342,7 +346,7 @@
headersOverride = redirectedFrom?._originalRequestRoute?._alreadyContinuedParams?.headers;
requestPausedSessionInfo!.session._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId, headers: headersOverride });
} else {
- route = new RouteImpl(requestPausedSessionInfo!.session, requestPausedEvent.requestId);
+ route = new RouteImpl(requestPausedSessionInfo!.session, requestPausedEvent.requestId, this._page, requestPausedEvent.networkId, this);
}
}
const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document';
@@ -553,6 +557,8 @@
if (request.session !== sessionInfo.session && !sessionInfo.isMain && (request._documentId === request._requestId || sessionInfo.workerFrame))
request.session = sessionInfo.session;
}
+
+ _alreadyTrackedNetworkIds: Set<string> = new Set();
}
class InterceptableRequest {
@@ -612,38 +618,189 @@
_alreadyContinuedParams: Protocol.Fetch.continueRequestParameters | undefined;
_fulfilled: boolean = false;
- constructor(session: CRSession, interceptionId: string) {
+ constructor(session: CRSession, interceptionId: string, page, networkId, sessionManager) {
+ this._sessionManager = void 0;
+ this._networkId = void 0;
+ this._page = void 0;
this._session = session;
this._interceptionId = interceptionId;
+ this._page = page;
+ this._networkId = networkId;
+ this._sessionManager = sessionManager;
+ eventsHelper.addEventListener(this._session, 'Fetch.requestPaused', async e => await this._networkRequestIntercepted(e));
}
async continue(overrides: types.NormalizedContinueOverrides): Promise<void> {
- this._alreadyContinuedParams = {
- requestId: this._interceptionId!,
- url: overrides.url,
- headers: overrides.headers,
- method: overrides.method,
- postData: overrides.postData ? overrides.postData.toString('base64') : undefined
- };
- await catchDisallowedErrors(async () => {
- await this._session.send('Fetch.continueRequest', this._alreadyContinuedParams);
- });
+
+ this._alreadyContinuedParams = {
+ requestId: this._interceptionId,
+ url: overrides.url,
+ headers: overrides.headers,
+ method: overrides.method,
+ postData: overrides.postData ? overrides.postData.toString('base64') : undefined,
+ };
+ if (overrides.url && (overrides.url === 'http://patchright-init-script-inject.internal/' || overrides.url === 'https://patchright-init-script-inject.internal/')) {
+ await catchDisallowedErrors(async () => {
+ this._sessionManager._alreadyTrackedNetworkIds.add(this._networkId);
+ this._session._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId, interceptResponse: true });
+ });
+ } else {
+ await catchDisallowedErrors(async () => {
+ await this._session._sendMayFail('Fetch.continueRequest', this._alreadyContinuedParams);
+ });
+ }
+
}
async fulfill(response: types.NormalizedFulfillResponse) {
- this._fulfilled = true;
- const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64');
- const responseHeaders = splitSetCookieHeader(response.headers);
- await catchDisallowedErrors(async () => {
- await this._session.send('Fetch.fulfillRequest', {
- requestId: this._interceptionId!,
- responseCode: response.status,
- responsePhrase: network.statusText(response.status),
- responseHeaders,
- body,
- });
- });
+ const isTextHtml = response.headers.some((header) => header.name.toLowerCase() === "content-type" && header.value.includes("text/html"));
+ var allInjections = [...this._page.delegate._mainFrameSession._evaluateOnNewDocumentScripts];
+ for (const binding of this._page.delegate._browserContext._pageBindings.values()) {
+ if (!allInjections.includes(binding)) allInjections.push(binding);
+ }
+ if (isTextHtml && allInjections.length) {
+ let useNonce = false;
+ let scriptNonce = null;
+ // Decode body if needed
+ if (response.isBase64) {
+ response.isBase64 = false;
+ response.body = Buffer.from(response.body, "base64").toString("utf-8");
+ }
+ // === CSP Detection and Fixing ===
+ const cspHeaderNames = ["content-security-policy", "content-security-policy-report-only"];
+ // Fix CSP in headers
+ for (let i = 0; i < response.headers.length; i++) {
+ const headerName = response.headers[i].name.toLowerCase();
+ if (cspHeaderNames.includes(headerName)) {
+ const originalCsp = response.headers[i].value || "";
+ // Extract nonce if present
+ if (!useNonce) {
+ const nonceMatch = originalCsp.match(/script-src[^;]*'nonce-([^'"\s;]+)'/i);
+ if (nonceMatch && nonceMatch[1]) {
+ scriptNonce = nonceMatch[1];
+ useNonce = true;
+ }
+ }
+
+ const fixedCsp = this._fixCSP(originalCsp, scriptNonce);
+ response.headers[i].value = fixedCsp;
+ }
+ }
+
+ // Fix CSP in meta tags
+ if (typeof response.body === "string" && response.body.length) {
+ response.body = response.body.replace(
+ /<meta[^>]*http-equiv=(?:"|')?Content-Security-Policy(?:"|')?[^>]*>/gi,
+ (match) => {
+ const contentMatch = match.match(/content=(?:"|')([^"']*)(?:"|')/i);
+ if (contentMatch && contentMatch[1]) {
+ let originalCsp = contentMatch[1];
+
+ // Decode HTML entities
+ originalCsp = originalCsp.replace(/&/g, '&') // Must be first!
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/"/g, '"')
+ .replace(/ /g, ' ')
+ .replace(/&#(d+);/g, (match, dec) => String.fromCharCode(dec))
+ .replace(/&#x([0-9a-fA-F]+);/g, (match, hex) => String.fromCharCode(parseInt(hex, 16)));
+
+ // Extract nonce if not already found
+ if (!useNonce) {
+ const nonceMatch = originalCsp.match(/script-src[^;]*'nonce-([^'"\s;]+)'/i);
+ if (nonceMatch && nonceMatch[1]) {
+ scriptNonce = nonceMatch[1];
+ useNonce = true;
+ }
+ }
+
+ const fixedCsp = this._fixCSP(originalCsp, scriptNonce);
+ // Re-encode for HTML
+ const encodedCsp = fixedCsp.replace(/'/g, ''').replace(/"/g, '"');
+ return match.replace(contentMatch[1], encodedCsp);
+ }
+ return match;
+ }
+ );
+ }
+
+ // Build injection HTML - only use nonce if one was found in existing CSP
+ let injectionHTML = "";
+ allInjections.forEach((script) => {
+ let scriptId = crypto.randomBytes(22).toString("hex");
+ let scriptSource = script.source || script;
+ const nonceAttr = useNonce ? `nonce="${scriptNonce}"` : '';
+ injectionHTML += `<script class="${this._page.delegate.initScriptTag}" ${nonceAttr} id="${scriptId}" type="text/javascript">document.getElementById("${scriptId}")?.remove();${scriptSource}</script>`;
+ });
+
+ // Inject at END of <head>
+ const lower = response.body.toLowerCase();
+ const headStartIndex = lower.indexOf("<head");
+ if (headStartIndex !== -1) {
+ const headEndTagIndex = lower.indexOf("</head>", headStartIndex);
+ if (headEndTagIndex !== -1) {
+ // Find the head opening tag end
+ const headOpenEnd = response.body.indexOf(">", headStartIndex) + 1;
+ const headContent = response.body.slice(headOpenEnd, headEndTagIndex);
+ const headContentLower = headContent.toLowerCase();
+
+ // Look for the first <script> tag in the head content
+ const firstScriptIndex = headContentLower.indexOf("<script");
+
+ if (firstScriptIndex !== -1) {
+ // Inject before the first script tag
+ const insertPosition = headOpenEnd + firstScriptIndex;
+ response.body =
+ response.body.slice(0, insertPosition) +
+ injectionHTML +
+ response.body.slice(insertPosition);
+ } else {
+ // No script tags found, inject at the end of head content (before </head>)
+ response.body =
+ response.body.slice(0, headEndTagIndex) +
+ injectionHTML +
+ response.body.slice(headEndTagIndex);
+ }
+ } else {
+ const headStartTagEnd = response.body.indexOf(">", headStartIndex) + 1;
+ response.body =
+ response.body.slice(0, headStartTagEnd) +
+ injectionHTML +
+ response.body.slice(headStartTagEnd);
+ }
+ } else {
+ const doctypeIndex = lower.indexOf("<!doctype");
+ if (doctypeIndex === 0) {
+ const doctypeEnd = response.body.indexOf(">", doctypeIndex) + 1;
+ response.body = response.body.slice(0, doctypeEnd) + injectionHTML + response.body.slice(doctypeEnd);
+ } else {
+ const htmlIndex = lower.indexOf("<html");
+ if (htmlIndex !== -1) {
+ const htmlTagEnd = response.body.indexOf(">", htmlIndex) + 1;
+ response.body =
+ response.body.slice(0, htmlTagEnd) + `<head>${injectionHTML}</head>` + response.body.slice(htmlTagEnd);
+ } else {
+ response.body = injectionHTML + response.body;
+ }
+ }
+ }
+ }
+ this._fulfilled = true;
+ const body = response.isBase64 ? response.body : Buffer.from(response.body).toString("base64");
+ const responseHeaders = splitSetCookieHeader(response.headers);
+ await catchDisallowedErrors(async () => {
+ await this._session.send("Fetch.fulfillRequest", {
+ requestId: response.interceptionId ? response.interceptionId : this._interceptionId,
+ responseCode: response.status,
+ responsePhrase: network.statusText(response.status),
+ responseHeaders,
+ body
+ });
+ });
+
}
async abort(errorCode: string = 'failed') {
@@ -656,6 +813,142 @@
});
});
}
+
+ _fixCSP(csp, scriptNonce) {
+
+ if (!csp || typeof csp !== 'string') return csp;
+
+ // Split by semicolons and clean up
+ const directives = csp.split(';')
+ .map(d => d.trim())
+ .filter(d => d && d.length > 0);
+
+ const fixedDirectives = [];
+ let hasScriptSrc = false;
+
+ for (let directive of directives) {
+ // Skip empty directives
+ if (!directive.trim()) continue;
+
+ // Split directive name from values
+ const parts = directive.trim().split(/s+/);
+ if (parts.length === 0) continue;
+
+ const directiveName = parts[0].toLowerCase();
+ const directiveValues = parts.slice(1);
+
+ switch (directiveName) {
+ case 'script-src':
+ hasScriptSrc = true;
+ let values = [...directiveValues];
+
+ // Add nonce if we have one and it's not already present
+ if (scriptNonce && !values.some(v => v.includes(`nonce-${scriptNonce}`))) {
+ values.push(`'nonce-${scriptNonce}'`);
+ }
+
+ // Add 'unsafe-eval' if not present
+ if (!values.includes("'unsafe-eval'")) {
+ values.push("'unsafe-eval'");
+ }
+
+ fixedDirectives.push(`script-src ${values.join(' ')}`);
+ break;
+
+ case 'style-src':
+ let styleValues = [...directiveValues];
+ // Add 'unsafe-inline' for styles if not present
+ if (!styleValues.includes("'unsafe-inline'")) {
+ styleValues.push("'unsafe-inline'");
+ }
+ fixedDirectives.push(`style-src ${styleValues.join(' ')}`);
+ break;
+
+ case 'img-src':
+ let imgValues = [...directiveValues];
+ // Allow data: URLs for images if not already allowed
+ if (!imgValues.includes("data:") && !imgValues.includes("*")) {
+ imgValues.push("data:");
+ }
+ fixedDirectives.push(`img-src ${imgValues.join(' ')}`);
+ break;
+
+ case 'font-src':
+ let fontValues = [...directiveValues];
+ // Allow data: URLs for fonts if not already allowed
+ if (!fontValues.includes("data:") && !fontValues.includes("*")) {
+ fontValues.push("data:");
+ }
+ fixedDirectives.push(`font-src ${fontValues.join(' ')}`);
+ break;
+
+ case 'connect-src':
+ let connectValues = [...directiveValues];
+ // Allow WebSocket connections if not already allowed
+ const hasWs = connectValues.some(v => v.includes("ws:") || v.includes("wss:") || v === "*");
+ if (!hasWs) {
+ connectValues.push("ws:", "wss:");
+ }
+ fixedDirectives.push(`connect-src ${connectValues.join(' ')}`);
+ break;
+
+ case 'frame-ancestors':
+ let frameAncestorValues = [...directiveValues];
+ // If completely blocked with 'none', allow 'self' at least
+ if (frameAncestorValues.includes("'none'")) {
+ frameAncestorValues = ["'self'"];
+ }
+ fixedDirectives.push(`frame-ancestors ${frameAncestorValues.join(' ')}`);
+ break;
+
+ default:
+ // Keep other directives as-is
+ fixedDirectives.push(directive);
+ break;
+ }
+ }
+
+ // Add script-src if it doesn't exist (for our injected scripts)
+ if (!hasScriptSrc) {
+ if (scriptNonce) {
+ fixedDirectives.push(`script-src 'self' 'unsafe-eval' 'nonce-${scriptNonce}'`);
+ } else {
+ fixedDirectives.push(`script-src 'self' 'unsafe-eval'`);
+ }
+ }
+
+ return fixedDirectives.join('; ');
+
+ }
+
+ async _networkRequestIntercepted(event) {
+
+ if (event.resourceType !== 'Document') {
+ /*await catchDisallowedErrors(async () => {
+ await this._session.send('Fetch.continueRequest', { requestId: event.requestId });
+ });*/
+ return;
+ }
+ if (this._networkId != event.networkId || !this._sessionManager._alreadyTrackedNetworkIds.has(event.networkId)) return;
+ try {
+ if (event.responseStatusCode >= 301 && event.responseStatusCode <= 308 || (event.redirectedRequestId && !event.responseStatusCode)) {
+ await this._session.send('Fetch.continueRequest', { requestId: event.requestId, interceptResponse: true });
+ } else {
+ const responseBody = await this._session.send('Fetch.getResponseBody', { requestId: event.requestId });
+ await this.fulfill({
+ headers: event.responseHeaders,
+ isBase64: true,
+ body: responseBody.body,
+ status: event.responseStatusCode,
+ interceptionId: event.requestId,
+ resourceType: event.resourceType,
+ })
+ }
+ } catch (error) {
+ await this._session._sendMayFail('Fetch.continueRequest', { requestId: event.requestId });
+ }
+
+ }
}
// In certain cases, protocol will return error if the request was already canceled
diff -ruN playwright/node_modules/playwright-core/src/server/chromium/crPage.ts patchright/node_modules/playwright-core/src/server/chromium/crPage.ts
---
+++
@@ -1,3 +1,5 @@
+// patchright - custom imports
+import crypto from 'crypto';
/**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
@@ -103,7 +105,8 @@
this.updateOffline();
this.updateExtraHTTPHeaders();
this.updateHttpCredentials();
- this.updateRequestInterception();
+ this._networkManager.setRequestInterception(true);
+ this.initScriptTag = crypto.randomBytes(20).toString('hex');
this._mainFrameSession = new FrameSession(this, client, targetId, null);
this._sessions.set(targetId, this._mainFrameSession);
if (opener && !browserContext._options.noDefaultViewport) {
@@ -233,6 +236,7 @@
}
async addInitScript(initScript: InitScript, world: types.World = 'main'): Promise<void> {
+ this._page.initScripts.push(initScript);
await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(initScript, world));
}
@@ -370,6 +374,19 @@
shouldToggleStyleSheetToSyncAnimations(): boolean {
return false;
}
+
+ async exposeBinding(binding) {
+
+ await this._forAllFrameSessions(frame => frame._initBinding(binding));
+ await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(binding.source).catch(e => {})));
+
+ }
+
+ async removeExposedBindings() {
+
+ await this._forAllFrameSessions(frame => frame._removeExposedBindings());
+
+ }
}
class FrameSession {
@@ -483,17 +500,6 @@
this._handleFrameTree(frameTree);
this._addRendererListeners();
}
-
- const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)!];
- for (const frame of localFrames) {
- // Note: frames might be removed before we send these.
- this._client._sendMayFail('Page.createIsolatedWorld', {
- frameId: frame._id,
- grantUniveralAccess: true,
- worldName: this._crPage.utilityWorldName,
- });
- }
-
const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';
if (isInitialEmptyPage) {
// Ignore lifecycle events, worlds and bindings for the initial empty page. It is never the final page
@@ -503,13 +509,22 @@
this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
});
} else {
+
+ const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)!];
+ for (const frame of localFrames) {
+ this._page.frameManager.frame(frame._id)._context("utility");
+ for (const binding of this._crPage._browserContext._pageBindings.values())
+ frame.evaluateExpression(binding.source).catch(e => {});
+ for (const source of this._crPage._browserContext.initScripts)
+ frame.evaluateExpression(source).catch(e => {});
+ }
+
this._firstNonInitialNavigationCommittedFulfill();
this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
}
}),
this._client.send('Log.enable', {}),
lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', { enabled: true }),
- this._client.send('Runtime.enable', {}),
this._client.send('Page.addScriptToEvaluateOnNewDocument', {
source: '',
worldName: this._crPage.utilityWorldName,
@@ -553,14 +568,24 @@
promises.push(this._updateGeolocation(true));
promises.push(this._updateEmulateMedia());
promises.push(this._updateFileChooserInterception(true));
- for (const initScript of this._crPage._page.allInitScripts())
- promises.push(this._evaluateOnNewDocument(initScript, 'main', true /* runImmediately */));
+
+ for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));
+ for (const initScript of this._crPage._browserContext.initScripts) promises.push(this._evaluateOnNewDocument(initScript, 'main'));
+ for (const initScript of this._crPage._page.initScripts) promises.push(this._evaluateOnNewDocument(initScript, 'main'));
+
if (screencastOptions)
promises.push(this._startVideoRecording(screencastOptions));
}
- promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));
+
+ if (!(this._crPage._page._pageBindings.size || this._crPage._browserContext._pageBindings.size))
+ promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));
+
promises.push(this._firstNonInitialNavigationCommittedPromise);
await Promise.all(promises);
+
+ if (this._crPage._page._pageBindings.size || this._crPage._browserContext._pageBindings.size)
+ await this._client.send('Runtime.runIfWaitingForDebugger');
+
}
dispose() {
@@ -584,13 +609,25 @@
return { newDocumentId: response.loaderId };
}
- _onLifecycleEvent(event: Protocol.Page.lifecycleEventPayload) {
+ async _onLifecycleEvent(event: Protocol.Page.lifecycleEventPayload) {
if (this._eventBelongsToStaleFrame(event.frameId))
return;
if (event.name === 'load')
this._page.frameManager.frameLifecycleEvent(event.frameId, 'load');
else if (event.name === 'DOMContentLoaded')
this._page.frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');
+ await this._client._sendMayFail('Runtime.runIfWaitingForDebugger');
+ var document = await this._client._sendMayFail("DOM.getDocument");
+ if (!document) return
+ var query = await this._client._sendMayFail("DOM.querySelectorAll", {
+ nodeId: document.root.nodeId,
+ selector: "[class=" + this._crPage.initScriptTag + "]"
+ });
+ if (!query) return
+ for (const nodeId of query.nodeIds) await this._client._sendMayFail("DOM.removeNode", { nodeId: nodeId });
+ await this._client._sendMayFail('Runtime.runIfWaitingForDebugger');
+ // ensuring execution context
+ try { await this._page.frameManager.frame(this._targetId)._context("utility") } catch { };
}
_handleFrameTree(frameTree: Protocol.Page.FrameTree) {
@@ -637,12 +674,24 @@
this._page.frameManager.frameAttached(frameId, parentFrameId);
}
- _onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) {
+ async _onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) {
if (this._eventBelongsToStaleFrame(framePayload.id))
return;
this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);
if (!initial)
this._firstNonInitialNavigationCommittedFulfill();
+ await this._client._sendMayFail('Runtime.runIfWaitingForDebugger');
+ var document = await this._client._sendMayFail("DOM.getDocument");
+ if (!document) return
+ var query = await this._client._sendMayFail("DOM.querySelectorAll", {
+ nodeId: document.root.nodeId,
+ selector: "[class=" + this._crPage.initScriptTag + "]"
+ });
+ if (!query) return
+ for (const nodeId of query.nodeIds) await this._client._sendMayFail("DOM.removeNode", { nodeId: nodeId });
+ await this._client._sendMayFail('Runtime.runIfWaitingForDebugger');
+ // ensuring execution context
+ try { await this._page.frameManager.frame(this._targetId)._context("utility") } catch { };
}
_onFrameRequestedNavigation(payload: Protocol.Page.frameRequestedNavigationPayload) {
@@ -679,19 +728,31 @@
}
_onExecutionContextCreated(contextPayload: Protocol.Runtime.ExecutionContextDescription) {
+
+ for (const name of this._exposedBindingNames)
+ this._client._sendMayFail('Runtime.addBinding', { name: name, executionContextId: contextPayload.id });
+
const frame = contextPayload.auxData ? this._page.frameManager.frame(contextPayload.auxData.frameId) : null;
+
+ if (contextPayload.auxData.type == "worker") throw new Error("ExecutionContext is worker");
+
if (!frame || this._eventBelongsToStaleFrame(frame._id))
return;
const delegate = new CRExecutionContext(this._client, contextPayload);
- let worldName: types.World|null = null;
- if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
- worldName = 'main';
- else if (contextPayload.name === this._crPage.utilityWorldName)
- worldName = 'utility';
+ let worldName = contextPayload.name;
const context = new dom.FrameExecutionContext(delegate, frame, worldName);
if (worldName)
frame._contextCreated(worldName, context);
this._contextIdToContext.set(contextPayload.id, context);
+
+ for (const source of this._exposedBindingScripts) {
+ this._client._sendMayFail("Runtime.evaluate", {
+ expression: source,
+ contextId: contextPayload.id,
+ awaitPromise: true,
+ })
+ }
+
}
_onExecutionContextDestroyed(executionContextId: number) {
@@ -707,7 +768,7 @@
this._onExecutionContextDestroyed(contextId);
}
- _onAttachedToTarget(event: Protocol.Target.attachedToTargetPayload) {
+ async _onAttachedToTarget(event: Protocol.Target.attachedToTargetPayload) {
const session = this._client.createChildSession(event.sessionId);
if (event.targetInfo.type === 'iframe') {
@@ -739,8 +800,18 @@
session.once('Runtime.executionContextCreated', async event => {
worker.createExecutionContext(new CRExecutionContext(session, event.context));
});
+
+ var globalThis = await session._sendMayFail('Runtime.evaluate', {
+ expression: "globalThis",
+ serializationOptions: { serialization: "idOnly" }
+ });
+ if (globalThis && globalThis.result) {
+ var globalThisObjId = globalThis.result.objectId;
+ var executionContextId = parseInt(globalThisObjId.split('.')[1], 10);
+ worker.createExecutionContext(new CRExecutionContext(session, { id: executionContextId }));
+ }
+
// This might fail if the target is closed before we initialize.
- session._sendMayFail('Runtime.enable');
// TODO: attribute workers to the right frame.
this._crPage._networkManager.addSession(session, this._page.frameManager.frame(this._targetId) ?? undefined).catch(() => {});
session._sendMayFail('Runtime.runIfWaitingForDebugger');
@@ -1074,20 +1145,11 @@
}
async _evaluateOnNewDocument(initScript: InitScript, world: types.World, runImmediately?: boolean): Promise<void> {
- const worldName = world === 'utility' ? this._crPage.utilityWorldName : undefined;
- const { identifier } = await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source: initScript.source, worldName, runImmediately });
- this._initScriptIds.set(initScript, identifier);
+ this._evaluateOnNewDocumentScripts.push(initScript)
}
async _removeEvaluatesOnNewDocument(initScripts: InitScript[]): Promise<void> {
- const ids: string[] = [];
- for (const script of initScripts) {
- const id = this._initScriptIds.get(script);
- if (id)
- ids.push(id);
- this._initScriptIds.delete(script);
- }
- await Promise.all(ids.map(identifier => this._client.send('Page.removeScriptToEvaluateOnNewDocument', { identifier }).catch(() => {}))); // target can be closed
+ this._evaluateOnNewDocumentScripts = [];
}
async exposePlaywrightBinding() {
@@ -1198,6 +1260,49 @@
throw new Error(dom.kUnableToAdoptErrorMessage);
return createHandle(to, result.object).asElement()!;
}
+
+ _exposedBindingNames: string[] = [];
+ _evaluateOnNewDocumentScripts: string[] = [];
+ _parsedExecutionContextIds: number[] = [];
+ _exposedBindingScripts: string[] = [];
+
+ async _initBinding(binding = PageBinding) {
+
+ var result = await this._client._sendMayFail('Page.createIsolatedWorld', {
+ frameId: this._targetId, grantUniveralAccess: true, worldName: "utility"
+ });
+ if (!result) return
+ var isolatedContextId = result.executionContextId
+
+ var globalThis = await this._client._sendMayFail('Runtime.evaluate', {
+ expression: "globalThis",
+ serializationOptions: { serialization: "idOnly" }
+ });
+ if (!globalThis) return
+ var globalThisObjId = globalThis["result"]['objectId']
+ var mainContextId = parseInt(globalThisObjId.split('.')[1], 10);
+
+ await Promise.all([
+ this._client._sendMayFail('Runtime.addBinding', { name: binding.name }),
+ this._client._sendMayFail('Runtime.addBinding', { name: binding.name, executionContextId: mainContextId }),
+ this._client._sendMayFail('Runtime.addBinding', { name: binding.name, executionContextId: isolatedContextId }),
+ // this._client._sendMayFail("Runtime.evaluate", { expression: binding.source, contextId: mainContextId, awaitPromise: true })
+ ]);
+ this._exposedBindingNames.push(binding.name);
+ this._exposedBindingScripts.push(binding.source);
+ await this._crPage.addInitScript(binding.source);
+ //this._client._sendMayFail('Runtime.runIfWaitingForDebugger')
+ }
+
+ async _removeExposedBindings() {
+ const toRetain: string[] = [];
+ const toRemove: string[] = [];
+ for (const name of this._exposedBindingNames)
+ (name.startsWith('__pw_') ? toRetain : toRemove).push(name);
+ this._exposedBindingNames = toRetain;
+ await Promise.all(toRemove.map(name => this._client.send('Runtime.removeBinding', { name })));
+
+ }
}
async function emulateLocale(session: CRSession, locale: string) {
diff -ruN playwright/node_modules/playwright-core/src/server/chromium/crServiceWorker.ts patchright/node_modules/playwright-core/src/server/chromium/crServiceWorker.ts
---
+++
@@ -44,13 +44,23 @@
this.updateOffline();
this._networkManager.addSession(session, undefined, true /* isMain */).catch(() => {});
}
-
- session.send('Runtime.enable', {}).catch(e => { });
session.send('Runtime.runIfWaitingForDebugger').catch(e => { });
session.on('Inspector.targetReloadedAfterCrash', () => {
// Resume service worker after restart.
session._sendMayFail('Runtime.runIfWaitingForDebugger', {});
});
+
+ session._sendMayFail("Runtime.evaluate", {
+ expression: "globalThis",
+ serializationOptions: { serialization: "idOnly" }
+ }).then(globalThis => {
+ if (globalThis && globalThis.result) {
+ var globalThisObjId = globalThis.result.objectId;
+ var executionContextId = parseInt(globalThisObjId.split(".")[1], 10);
+ this.createExecutionContext(new CRExecutionContext(session, { id: executionContextId }));
+ }
+ });
+
}
override didClose() {
diff -ruN playwright/node_modules/playwright-core/src/server/clock.ts patchright/node_modules/playwright-core/src/server/clock.ts
---
+++
@@ -106,6 +106,16 @@
}
private async _evaluateInFrames(script: string) {
+
+ // Dont ask me why this works
+ await Promise.all(this._browserContext.pages().map(async page => {
+ await Promise.all(page.frames().map(async frame => {
+ try {
+ await frame.evaluateExpression("");
+ } catch (e) {}
+ }));
+ }));
+
await this._browserContext.safeNonStallingEvaluateInAllFrames(script, 'main', { throwOnJSErrors: true });
}
}
diff -ruN playwright/node_modules/playwright-core/src/server/dispatchers/frameDispatcher.ts patchright/node_modules/playwright-core/src/server/dispatchers/frameDispatcher.ts
---
+++
@@ -84,11 +84,15 @@
}
async evaluateExpression(params: channels.FrameEvaluateExpressionParams, progress: Progress): Promise<channels.FrameEvaluateExpressionResult> {
- return { value: serializeResult(await progress.race(this._frame.evaluateExpression(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg)))) };
+
+ return { value: serializeResult(await progress.race(this._frame.evaluateExpression(params.expression, { isFunction: params.isFunction, world: params.isolatedContext ? 'utility': 'main' }, parseArgument(params.arg)))) };
+
}
async evaluateExpressionHandle(params: channels.FrameEvaluateExpressionHandleParams, progress: Progress): Promise<channels.FrameEvaluateExpressionHandleResult> {
- return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this, await progress.race(this._frame.evaluateExpressionHandle(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg)))) };
+
+ return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this, await progress.race(this._frame.evaluateExpressionHandle(params.expression, { isFunction: params.isFunction, world: params.isolatedContext ? 'utility': 'main' }, parseArgument(params.arg)))) };
+
}
async waitForSelector(params: channels.FrameWaitForSelectorParams, progress: Progress): Promise<channels.FrameWaitForSelectorResult> {
@@ -104,7 +108,9 @@
}
async evalOnSelectorAll(params: channels.FrameEvalOnSelectorAllParams, progress: Progress): Promise<channels.FrameEvalOnSelectorAllResult> {
- return { value: serializeResult(await progress.race(this._frame.evalOnSelectorAll(params.selector, params.expression, params.isFunction, parseArgument(params.arg)))) };
+
+ return { value: serializeResult(await this._frame.evalOnSelectorAll(params.selector, params.expression, params.isFunction, parseArgument(params.arg), null, params.isolatedContext)) };
+
}
async querySelector(params: channels.FrameQuerySelectorParams, progress: Progress): Promise<channels.FrameQuerySelectorResult> {
diff -ruN playwright/node_modules/playwright-core/src/server/frameSelectors.ts patchright/node_modules/playwright-core/src/server/frameSelectors.ts
---
+++
@@ -1,3 +1,5 @@
+// patchright - custom imports
+import { ElementHandle } from './dom';
/**
* Copyright (c) Microsoft Corporation.
*
@@ -65,8 +67,8 @@
return adoptIfNeeded(elementHandle, await resolved.frame._mainContext());
}
- async queryArrayInMainWorld(selector: string, scope?: ElementHandle): Promise<JSHandle<Element[]>> {
- const resolved = await this.resolveInjectedForSelector(selector, { mainWorld: true }, scope);
+ async queryArrayInMainWorld(selector: string, scope?: ElementHandle, isolatedContext?: boolean): Promise<JSHandle<Element[]>> {
+ const resolved = await this.resolveInjectedForSelector(selector, { mainWorld: !isolatedContext }, scope);
// Be careful, |this.frame| can be different from |resolved.frame|.
if (!resolved)
throw new Error(`Failed to find frame for selector "${selector}"`);
@@ -152,9 +154,31 @@
throw injected.createStacklessError(`Selector "${selectorString}" resolved to ${injected.previewNode(element)}, <iframe> was expected`);
return element;
}, { info, scope: i === 0 ? scope : undefined, selectorString: stringifySelector(info.parsed) });
- const element = handle.asElement() as ElementHandle<Element> | null;
- if (!element)
- return null;
+ let element = handle.asElement() as ElementHandle<Element> | null;
+
+ if (!element) {
+ try {
+ var client = frame._page.delegate._sessionForFrame(frame)._client;
+ } catch (e) {
+ var client = frame._page.delegate._mainFrameSession._client;
+ }
+ var mainContext = await frame._context("main");
+ const documentNode = await client.send("Runtime.evaluate", {
+ expression: "document",
+ serializationOptions: {
+ serialization: "idOnly"
+ },
+ contextId: mainContext.delegate._contextId
+ });
+ const documentScope = new ElementHandle(mainContext, documentNode.result.objectId);
+ var check = await this._customFindFramesByParsed(injectedScript, client, mainContext, documentScope, info.parsed);
+ if (check.length > 0) {
+ element = check[0];
+ } else {
+ return null;
+ }
+ }
+
const maybeFrame = await frame._page.delegate.getContentFrame(element);
element.dispose();