-
Notifications
You must be signed in to change notification settings - Fork 7
/
macos-communication.js
591 lines (551 loc) · 18.9 KB
/
macos-communication.js
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
/**
* **Incoming data**
*
* On macOS, all data for the dashboard is delivered via methods that have been
* attached to the global `window` object. Please see the aboutLink below under the heading 'macOS -> JavaScript Interface' for examples.
*
* **Outgoing messages**
*
* The dashboard communicates with the macOS application by calling message handlers that
* are added to `window.webkit.messageHandlers.*`. Please see the items below under the heading `"Webkit Message Handlers"`
*
* @module macOS integration
* @category integrations
*/
import invariant from 'tiny-invariant';
import {
cookiePromptManagementStatusSchema,
localeSettingsSchema,
maliciousSiteStatusSchema,
protectionsStatusSchema,
requestDataSchema,
toggleReportScreenSchema,
} from '../../../schema/__generated__/schema.parsers.mjs';
import { isIOS } from '../ui/environment-check';
import { setupGlobalOpenerListener } from '../ui/views/utils/utils';
import {
CloseMessage,
FetchToggleReportOptions,
getContentHeight,
OpenSettingsMessages,
RejectToggleBreakageReport,
SeeWhatIsSent,
SendToggleBreakageReport,
SetListsMessage,
setupColorScheme,
setupMutationObserver,
SubmitBrokenSiteReportMessage,
UpdatePermissionMessage,
ShowNativeFeedback,
} from './common.js';
import { createTabData } from './utils/request-details.mjs';
let channel = null;
/**
* @category Internal API
* @param backgroundModel
*/
const backgroundMessage = (backgroundModel) => {
channel = backgroundModel;
};
const getBackgroundTabDataPromises = [];
let trackerBlockingData;
let permissionsData;
let certificateData;
let upgradedHttps;
/** @type {import("./utils/protections.mjs").Protections | undefined} */
let protections;
let isPendingUpdates;
let parentEntity;
const cookiePromptManagementStatus = {};
/** @type {import('../../../schema/__generated__/schema.types').MaliciousSiteStatus} */
let maliciousSiteStatus;
/** @type {string | undefined} */
let locale;
const combineSources = () => ({
tab: Object.assign(
{},
trackerBlockingData || {},
{ maliciousSiteStatus: maliciousSiteStatus ?? false },
{
isPendingUpdates,
parentEntity,
cookiePromptManagementStatus,
platformLimitations: true,
locale,
},
permissionsData ? { permissions: permissionsData } : {},
certificateData ? { certificate: certificateData } : {}
),
});
const resolveInitialRender = function () {
const isUpgradedHttpsSet = typeof upgradedHttps === 'boolean';
const isIsProtectedSet = typeof protections !== 'undefined';
const isTrackerBlockingDataSet = typeof trackerBlockingData === 'object';
const isLocaleSet = typeof locale === 'string';
const isMaliciousSiteSet = isIOS() || (maliciousSiteStatus && maliciousSiteStatus.kind !== undefined);
if (!isLocaleSet || !isUpgradedHttpsSet || !isIsProtectedSet || !isTrackerBlockingDataSet || !isMaliciousSiteSet) {
return;
}
getBackgroundTabDataPromises.forEach((resolve) => resolve(combineSources()));
channel?.send('updateTabData');
};
// Integration APIs
// -----------------------------------------------------------------------------
/**
* Call this method when there is updated request information.
*
* Note: this expects each call to provide the full data set each time, **not** any kind of delta
*
* @group macOS -> JavaScript Interface
* @example
*
* ```javascript
* window.onChangeTrackerBlockingData("https://example.com", rawRequestData)
* ```
*
* @param {string} tabUrl
* @param {import('../../../schema/__generated__/schema.types').RequestData} rawRequestData
*
* Please see [cnn.json](media://request-data-cnn.json) or [google.json](media://request-data-google.json) for examples of this type
*/
export function onChangeRequestData(tabUrl, rawRequestData) {
const requestData = requestDataSchema.safeParse(rawRequestData);
if (!protections) throw new Error('protections status not set');
if (!requestData.success) {
console.error('could not parse incoming request data from `onChangeRequestData`');
console.log(requestData.error);
return;
}
trackerBlockingData = createTabData(tabUrl, upgradedHttps, protections, requestData.data);
resolveInitialRender();
}
/**
* {@inheritDoc common.onChangeProtectionStatus}
* @type {import("./common.js").onChangeProtectionStatus}
* @group macOS -> JavaScript Interface
*
* @example
*
* On the swift side, evaluate JavaScript calling the correct method on `window`, something like this...
*
* ```swift
* // swift
* evaluate(js: "window.onChangeTrackerBlockingData(\(safeTabUrl), \(trackerBlockingDataJson))", in: webView)
* ```
*
* @param {import('../../../schema/__generated__/schema.types').ProtectionsStatus} protectionsStatus
*/
export function onChangeProtectionStatus(protectionsStatus) {
const parsed = protectionsStatusSchema.safeParse(protectionsStatus);
if (!parsed.success) {
console.error('could not parse incoming protection status from onChangeProtectionStatus');
console.error(parsed.error);
return;
}
protections = parsed.data;
resolveInitialRender();
}
/**
* {@inheritDoc common.onChangeLocale}
* @type {import("./common.js").onChangeLocale}
* @group macOS -> JavaScript Interface
* @example
*
* ```swift
* // swift
* evaluate(js: "window.onChangeLocale(\(localSettingsJsonString))", in: webView)
* ```
*/
export function onChangeLocale(payload) {
const parsed = localeSettingsSchema.safeParse(payload);
if (!parsed.success) {
console.error('could not parse incoming data from onChangeLocale');
console.error(parsed.error);
return;
}
locale = parsed.data.locale;
channel?.send('updateTabData');
}
/**
* {@inheritDoc common.onChangeMaliciousSiteStatus}
* @type {import("./common.js").onChangeMaliciousSiteStatus}
* @group macOS -> JavaScript Interface
* @example
*
* ```swift
* // swift
* evaluate(js: "window.onChangeMaliciousSiteStatus(\(maliciousSiteStatusJsonString))", in: webView)
* ```
*/
export function onChangeMaliciousSiteStatus(payload) {
const parsed = maliciousSiteStatusSchema.safeParse(payload);
if (!parsed.success) {
console.error('could not parse incoming data from onChangeMaliciousSiteStatus');
console.error(parsed.error);
return;
}
maliciousSiteStatus = parsed.data;
resolveInitialRender();
}
/**
* {@inheritDoc common.onChangeConsentManaged}
* @type {import("./common.js").onChangeConsentManaged}
* @group macOS -> JavaScript Interface
* @example On macOS and iOS, it might look something like this:
*
* ```swift
* // swift
* evaluate(js: "window.onChangeConsentManaged(\(cookiePromptManagementStatus))", in: webView)
* ```
*/
export function onChangeConsentManaged(payload) {
const parsed = cookiePromptManagementStatusSchema.safeParse(payload);
if (!parsed.success) {
console.error('could not parse incoming data from onChangeConsentManaged');
console.error(parsed.error);
return;
}
Object.assign(cookiePromptManagementStatus, parsed.data);
channel?.send('updateTabData');
}
// -----------------------------------------------------------------------------
/**
* This message will be sent when the toggle is pressed on, or off via:
* - The primary screen
* - The breakage form
*
* @param {import('../../../schema/__generated__/schema.types').SetProtectionParams} params
* @category Webkit Message Handlers
* @example
*
* This message handler is the equivalent of calling the following JavaScript.
*
* ```js
* window.webkit.messageHandlers.privacyDashboardSetProtection.postMessage({
* isProtected: true,
* eventOrigin: { screen: "primaryScreen" }
* })
* ```
*/
export function privacyDashboardSetProtection(params) {
invariant(
window.webkit?.messageHandlers?.privacyDashboardSetProtection,
'webkit.messageHandlers.privacyDashboardSetProtection required'
);
window.webkit.messageHandlers.privacyDashboardSetProtection.postMessage(params);
}
/**
* {@inheritDoc common.setPermission}
* @type {import("./common.js").setPermission}
* @category Webkit Message Handlers
* @example
*
* This message handler is the equivalent of calling the following JavaScript.
*
* ```js
* window.webkit.messageHandlers.privacyDashboardSetPermission.postMessage({
* permission: "camera",
* value: "grant"
* })
* ```
*/
export function privacyDashboardSetPermission(params) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardSetPermission.postMessage(params);
}
/**
* @category Webkit Message Handler
* @example
*
* When the Dashboard loads, it will call this message handler...
*
* ```js
* window.webkit.messageHandlers.privacyDashboardGetToggleReportOptions.postMessage({})
* ```
*
* ... then, to reply with the correct data, call evaluate on the following window method:
*
* The JSON object should match {@link "Generated Schema Definitions".ToggleReportScreen}
*
* ```js
* window.onGetToggleReportOptionsResponse({ "data": [...] })
* ```
*
* [Sample JSON 📝](../../../schema/__fixtures__/toggle-report-screen.json)
*
* @returns {Promise<import('../../../schema/__generated__/schema.types').ToggleReportScreen>}
*/
export function privacyDashboardGetToggleReportOptions() {
return new Promise((resolve) => {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
invariant(window.webkit.messageHandlers.privacyDashboardGetToggleReportOptions, 'privacyDashboardGetToggleReportOptions required');
window.webkit.messageHandlers.privacyDashboardGetToggleReportOptions.postMessage({});
window.onGetToggleReportOptionsResponse = (data) => {
resolve(data);
Reflect.deleteProperty(window, 'onGetToggleReportOptionsResponse');
};
});
}
/**
* {@inheritDoc common.sendToggleReport}
* @type {import("./common.js").sendToggleReport}
* @category Webkit Message Handlers
* @example
*
* This message handler is the equivalent of calling the following JavaScript.
*
* ```js
* window.webkit.messageHandlers.privacyDashboardSendToggleReport.postMessage({})
* ```
*/
export function privacyDashboardSendToggleReport() {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
invariant(window.webkit.messageHandlers.privacyDashboardSendToggleReport, 'privacyDashboardSendToggleReport required');
window.webkit.messageHandlers.privacyDashboardSendToggleReport.postMessage({});
}
/**
* {@inheritDoc common.rejectToggleReport}
* @type {import("./common.js").rejectToggleReport}
* @category Webkit Message Handlers
* @example
*
* This message handler is the equivalent of calling the following JavaScript.
*
* ```js
* window.webkit.messageHandlers.privacyDashboardRejectToggleReport.postMessage({})
* ```
*/
export function privacyDashboardRejectToggleReport() {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
invariant(window.webkit.messageHandlers.privacyDashboardRejectToggleReport, 'privacyDashboardRejectToggleReport required');
window.webkit.messageHandlers.privacyDashboardRejectToggleReport.postMessage({});
}
/**
* This is sent when the user has chosen to show the information that will be used in the toggle report
*
* @category Webkit Message Handlers
* @example
*
* This message handler is the equivalent of calling the following JavaScript.
*
* ```js
* window.webkit.messageHandlers.privacyDashboardSeeWhatIsSent.postMessage({})
* ```
*/
export function privacyDashboardSeeWhatIsSent() {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
invariant(window.webkit.messageHandlers.privacyDashboardSeeWhatIsSent, 'privacyDashboardSeeWhatIsSent required');
return window.webkit.messageHandlers.privacyDashboardSeeWhatIsSent.postMessage({});
}
/**
* Close the Dashboard.
* @category Webkit Message Handlers
* @param {import('../../../schema/__generated__/schema.types').CloseMessageParams} args
* @example
*
* ```js
* window.webkit.messageHandlers.privacyDashboardClose.postMessage(args)
* ```
* [Sample JSON 📝](../../../schema/__fixtures__/webkit-close.json)
*
*/
export function privacyDashboardClose(args) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardClose.postMessage(args);
}
/**
* @category Internal API
* @type {import("./common.js").fetcher}
*/
async function fetch(message) {
if (message instanceof CloseMessage) {
privacyDashboardClose({ eventOrigin: message.eventOrigin });
return;
}
if (message instanceof SubmitBrokenSiteReportMessage) {
privacyDashboardSubmitBrokenSiteReport({
category: message.category,
description: message.description,
});
return;
}
if (message instanceof SetListsMessage) {
for (const listItem of message.lists) {
const { list, value } = listItem;
if (list !== 'allowlisted') {
if (!window.__playwright) console.warn('only `allowlisted` is currently supported on macos');
continue;
}
// `allowlisted: true` means the user disabled protections.
// so `isProtected` is the opposite of `allowlisted`.
const isProtected = value === false;
privacyDashboardSetProtection({ eventOrigin: message.eventOrigin, isProtected });
}
return;
}
if (message instanceof OpenSettingsMessages) {
privacyDashboardOpenSettings({
target: message.target,
});
return;
}
if (message instanceof UpdatePermissionMessage) {
privacyDashboardSetPermission({
permission: message.id,
value: message.value,
});
}
if (message instanceof FetchToggleReportOptions) {
const data = await privacyDashboardGetToggleReportOptions();
const parsed = toggleReportScreenSchema.parse(data);
return parsed;
}
if (message instanceof SendToggleBreakageReport) {
return privacyDashboardSendToggleReport();
}
if (message instanceof RejectToggleBreakageReport) {
return privacyDashboardRejectToggleReport();
}
if (message instanceof SeeWhatIsSent) {
return privacyDashboardSeeWhatIsSent();
}
if (message instanceof ShowNativeFeedback) {
privacyDashboardShowNativeFeedback({});
return false; // Return true to prevent HTML form from showing
}
}
/**
* @category Internal API
* @returns {Promise<unknown>}
*/
const getBackgroundTabData = () => {
return new Promise((resolve) => {
if (trackerBlockingData) {
resolve(combineSources());
return;
}
getBackgroundTabDataPromises.push(resolve);
});
};
/**
* {@inheritDoc common.openInNewTab}
* @type {import("./common.js").openInNewTab}
* @category Webkit Message Handlers
*/
export function privacyDashboardOpenUrlInNewTab(args) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardOpenUrlInNewTab.postMessage({
url: args.url,
});
}
/**
* {@inheritDoc common.openSettings}
* @type {import("./common.js").openSettings}
* @category Webkit Message Handlers
*/
export function privacyDashboardOpenSettings(args) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardOpenSettings.postMessage({
target: args.target,
});
}
/**
* {@inheritDoc common.submitBrokenSiteReport}
* @type {import("./common.js").submitBrokenSiteReport}
* @category Webkit Message Handlers
*/
export function privacyDashboardSubmitBrokenSiteReport(report) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardSubmitBrokenSiteReport.postMessage({
category: report.category,
description: report.description,
});
}
/**
* {@inheritDoc common.setSize}
* @type {import("./common.js").setSize}
* @category Webkit Message Handlers
*/
export function privacyDashboardSetSize(payload) {
if (!isIOS()) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardSetSize.postMessage(payload);
}
}
/**
* Triggers a native form for general feedback on macOS
*
* @category Webkit Message Handlers
* @param {{}} args - An empty object to keep the `webkit` message handlers happy
* @example
* ```js
* window.webkit.messageHandlers.privacyDashboardShowNativeFeedback.postMessage(args)
* ```
*/
export function privacyDashboardShowNativeFeedback(args) {
invariant(window.webkit?.messageHandlers, 'webkit.messageHandlers required');
window.webkit.messageHandlers.privacyDashboardShowNativeFeedback.postMessage(args);
}
/**
* These side-effects are used on both ios/macos
*/
export function setupShared() {
window.onChangeRequestData = onChangeRequestData;
window.onChangeAllowedPermissions = function (data) {
permissionsData = data;
channel?.send('updateTabData');
};
window.onChangeUpgradedHttps = function (data) {
upgradedHttps = data;
if (trackerBlockingData) trackerBlockingData.upgradedHttps = upgradedHttps;
resolveInitialRender();
};
window.onChangeMaliciousSiteStatus = onChangeMaliciousSiteStatus;
window.onChangeProtectionStatus = onChangeProtectionStatus;
window.onChangeLocale = onChangeLocale;
window.onChangeCertificateData = function (data) {
certificateData = data.secCertificateViewModels;
channel?.send('updateTabData');
};
window.onIsPendingUpdates = function (data) {
isPendingUpdates = data;
channel?.send('updateTabData');
};
window.onChangeParentEntity = function (data) {
parentEntity = data;
channel?.send('updateTabData');
};
window.onChangeConsentManaged = onChangeConsentManaged;
setupGlobalOpenerListener((href) => {
privacyDashboardOpenUrlInNewTab({
url: href,
});
});
}
/**
* macOS specific setup
*/
export function setup() {
setupColorScheme();
setupShared();
setupMutationObserver((height) => {
privacyDashboardSetSize({ height });
});
}
/**
* Called when the DOM has been rendered for the first time. This is
* helpful on platforms that need to update their window size immediately
*
* @type {NonNullable<import('./communication.js').Communication['firstRenderComplete']>}
* @category Internal API
*/
function firstRenderComplete() {
const height = getContentHeight();
if (typeof height === 'number') {
privacyDashboardSetSize({ height });
}
}
/**
* @module
*/
export { fetch, backgroundMessage, getBackgroundTabData, firstRenderComplete };