-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathfirefox.ts
More file actions
682 lines (618 loc) · 20.9 KB
/
firefox.ts
File metadata and controls
682 lines (618 loc) · 20.9 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
export enum FirefoxCommand {
AccountDeleted = 'fxaccounts:delete',
ProfileChanged = 'profile:change',
PasswordChanged = 'fxaccounts:change_password',
FxAStatus = 'fxaccounts:fxa_status',
Login = 'fxaccounts:login',
Logout = 'fxaccounts:logout',
Loaded = 'fxaccounts:loaded',
Error = 'fxError',
OAuthLogin = 'fxaccounts:oauth_login',
CanLinkAccount = 'fxaccounts:can_link_account',
// opens sync preferences if user is signed in to sync
// use as: firefox.send(FirefoxCommand.SyncPreferences, {ok: true});
// caveat: if browser does not support the command
// or the user is not signed in to sync
// there is no response and the command fails silently
// As of May 2025, this command is available on desktop
// support will be added on Android (https://bugzilla.mozilla.org/show_bug.cgi?id=1968130)
// and iOS (https://github.com/mozilla-mobile/firefox-ios/issues/26837)
SyncPreferences = 'fxaccounts:sync_preferences',
// Check if Firefox has an active OAuth flow
OAuthFlowIsActive = 'fxaccounts:oauth_flow_is_active',
// Start new OAuth flow and get fresh params
OAuthFlowBegin = 'fxaccounts:oauth_flow_begin',
// Pairing commands — sent between web page and Firefox browser
PairHeartbeat = 'fxaccounts:pair_heartbeat',
PairSupplicantMetadata = 'fxaccounts:pair_supplicant_metadata',
PairAuthorize = 'fxaccounts:pair_authorize',
PairDecline = 'fxaccounts:pair_decline',
PairComplete = 'fxaccounts:pair_complete',
PairPreferences = 'fxaccounts:pair_preferences',
}
export interface FirefoxMessageDetail {
id: string;
message?: FirefoxMessage;
}
export interface FirefoxMessage {
command: FirefoxCommand;
data: Record<string, any> & {
error?: {
message: string;
stack: string;
};
};
params?: Record<string, any>; // Some commands use params instead of data
messageId: string;
error?: string;
}
export interface FirefoxMessageError {
error?: string;
stack?: string;
}
interface ProfileUid {
uid: hexstring;
}
interface ProfileMetricsEnabled {
metricsEnabled: boolean;
}
type Profile = ProfileUid | ProfileMetricsEnabled;
type FirefoxEvent = CustomEvent<FirefoxMessageDetail | string>;
// This is defined in the Firefox source code:
// https://searchfox.org/mozilla-central/source/services/fxaccounts/tests/xpcshell/test_web_channel.js#348
type FxAStatusRequest = {
service: string; // ex. 'sync'
isPairing: boolean;
context: string; // ex. 'fx_desktop_v3'
};
export type FxAStatusResponse = {
capabilities: {
engines: string[];
multiService: boolean;
pairing: boolean;
choose_what_to_sync?: boolean;
keys_optional?: boolean;
can_link_account_uid?: boolean;
};
clientId?: string;
signedInUser?: SignedInUser;
};
export type SignedInUser = {
email: string;
// This can be undefined when the browser account
// is in an "Account disconnected" state
sessionToken: string | undefined;
uid: string;
verified: boolean;
};
export type FxALoginRequest = {
email: string;
sessionToken: hexstring;
uid: hexstring;
verified: boolean;
keyFetchToken?: hexstring;
unwrapBKey?: string;
verifiedCanLinkAccount?: boolean;
services?: WebChannelServices;
};
export type SyncEngines = {
offeredEngines?: string[];
declinedEngines?: string[];
};
export type WebChannelServices =
| {
sync: SyncEngines;
}
// For sync optional flows (currently Relay and SmartWindow)
| {
relay: {};
}
| {
smartwindow: {};
}
| {
vpn: {};
};
// ref: [FxAccounts.sys.mjs](https://searchfox.org/mozilla-central/rev/82828dba9e290914eddd294a0871533875b3a0b5/services/fxaccounts/FxAccounts.sys.mjs#910)
export type FxALoginSignedInUserRequest = FxALoginRequest & {
authAt: number;
};
export type FxAOAuthLogin = {
action: string;
code: string;
redirect: string;
state: string;
// OAuth desktop looks at the sync engine list in fxaLogin.
// OAuth mobile currently looks at fxaOAuthLogin, but should
// eventually move to look at fxaLogin as well to prevent FXA-10596.
declinedSyncEngines?: string[];
offeredSyncEngines?: string[];
// Space-separated list of granted scopes, sent so the browser knows
// which scopes were authorized in this flow.
scopes?: string;
};
// ref: https://searchfox.org/mozilla-central/rev/82828dba9e290914eddd294a0871533875b3a0b5/services/fxaccounts/FxAccountsWebChannel.sys.mjs#230
export type FxACanLinkAccount = {
email: string;
// To allow secondary email sign-ins, we send the UID up to the browser when
// the UID is available and the 'can_link_account_uid' capability is true.
uid?: string;
};
type FxACanLinkAccountResponse = {
ok: boolean;
};
export type FxAOAuthFlowIsActiveResponse = {
isActive: boolean;
};
// Pairing types
export type PairHeartbeatResponse = {
err?: { errno: number; message: string };
suppAuthorized?: boolean;
};
export type PairSupplicantMetadataResponse = {
ua: string;
city: string;
country: string;
region: string;
ipAddress: string;
};
export type FxAOAuthFlowBeginResponse = {
action: string;
response_type: string;
access_type: string;
scope: string;
client_id: string;
state: string;
code_challenge?: string;
code_challenge_method?: string;
};
// timeout tuned for device latency
// max timeout of 100-200 ms would be optimal for an ultra-snappy UX, but could cause false negatives on mobile
// compromising with 500ms for safer mobile support without being noticeably long if it times out
const DEFAULT_SEND_TIMEOUT_LENGTH_MS = 500;
let messageIdSuffix = 0;
/**
* Create a messageId for a given command/data combination.
*
* messageId is sent to the relier who is expected to respond
* with the same messageId. Used to keep track of outstanding requests
* and is required in at least Firefox iOS to send back a response.
* */
function createMessageId() {
// If two messages are created within the same millisecond, Date.now()
// returns the same value. Append a suffix that ensures uniqueness.
return `${Date.now()}${++messageIdSuffix}`;
}
export class Firefox extends EventTarget {
private broadcastChannel?: BroadcastChannel;
readonly id: string;
constructor() {
super();
this.id = 'account_updates';
if (typeof BroadcastChannel !== 'undefined') {
this.broadcastChannel = new BroadcastChannel('firefox_accounts');
this.broadcastChannel.addEventListener('message', (event) =>
this.handleBroadcastEvent(event)
);
}
window.addEventListener('WebChannelMessageToContent', (event) =>
this.handleFirefoxEvent(event as FirefoxEvent)
);
}
private handleBroadcastEvent(event: MessageEvent) {
console.debug('broadcast', event);
const envelope = JSON.parse(event.data);
this.dispatchEvent(
new CustomEvent(envelope.name, { detail: envelope.data })
);
}
private handleFirefoxEvent(event: FirefoxEvent) {
console.debug('webchannel', event);
try {
const detail =
typeof event.detail === 'string'
? (JSON.parse(event.detail) as FirefoxMessageDetail)
: event.detail;
if (detail.id !== this.id) {
return;
}
const message = detail.message;
if (message) {
if (message.error || message.data?.error) {
const error = {
message: message.error || message.data.error?.message,
stack: message.data?.error?.stack,
};
this.dispatchEvent(
new CustomEvent(FirefoxCommand.Error, { detail: error })
);
} else {
const responseData = message.data || message.params;
this.dispatchEvent(
new CustomEvent(message.command, { detail: responseData })
);
}
}
} catch (e) {
// TODO: log and ignore
}
}
private formatEventDetail(
command: FirefoxCommand,
data: any,
messageId: string = createMessageId()
) {
const detail = {
id: this.id,
message: {
command,
data,
messageId,
},
};
// Firefox Desktop and Fennec >= 50 expect the detail to be
// sent as a string and fxios as an object.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1275616 and
// https://bugzilla.mozilla.org/show_bug.cgi?id=1238128
if (navigator.userAgent.toLowerCase().includes('fxios')) {
return detail;
}
return JSON.stringify(detail);
}
/**
* Save the name of the event into sessionStorage, used for testing.
*
* @param {String} command
* @private
*/
private saveEventForTests(command: FirefoxCommand, data: any) {
const agent = navigator.userAgent;
const isWebDriver = navigator.webdriver;
if (!isWebDriver && agent.indexOf('FxATester') === -1) {
// not running in automated tests, no reason to store this info.
return;
}
let storedEvents;
try {
storedEvents =
JSON.parse(sessionStorage.getItem('webChannelEvents') || '') || [];
} catch (e) {
storedEvents = [];
}
storedEvents.push({ command, data });
try {
sessionStorage.setItem('webChannelEvents', JSON.stringify(storedEvents));
} catch (e) {}
}
// send a message to the browser chrome
send(command: FirefoxCommand, data: any, messageId?: string) {
const detail = this.formatEventDetail(command, data, messageId);
window.dispatchEvent(
new CustomEvent('WebChannelMessageToChrome', {
detail,
})
);
this.saveEventForTests(command, data);
}
// broadcast a message to other tabs
broadcast(name: FirefoxCommand, data: any) {
this.broadcastChannel?.postMessage(JSON.stringify({ name, data }));
}
accountDeleted(uid: hexstring) {
this.send(FirefoxCommand.AccountDeleted, { uid });
this.broadcast(FirefoxCommand.AccountDeleted, { uid });
}
passwordChanged(
email: string,
uid: hexstring,
sessionToken: hexstring,
verified: boolean,
keyFetchToken?: hexstring,
unwrapBKey?: hexstring
) {
this.send(FirefoxCommand.PasswordChanged, {
email,
uid,
sessionToken,
verified,
keyFetchToken,
unwrapBKey,
});
this.broadcast(FirefoxCommand.PasswordChanged, {
uid,
});
}
profileChanged(profile: Profile) {
this.send(FirefoxCommand.ProfileChanged, profile);
this.broadcast(FirefoxCommand.ProfileChanged, profile);
}
async fxaStatus(options: FxAStatusRequest): Promise<FxAStatusResponse> {
// We must wait for the browser to send a web channel message
// in response to the fxaLogin command. Without this we navigate the user before
// the login completes, resulting in an "Invalid token" error on the next page.
return new Promise((resolve) => {
const eventHandler = (firefoxEvent: any) => {
this.removeEventListener(FirefoxCommand.FxAStatus, eventHandler);
resolve(firefoxEvent.detail as FxAStatusResponse);
};
this.addEventListener(FirefoxCommand.FxAStatus, eventHandler);
// requestAnimationFrame ensures the event listener is added first
// otherwise, there is a race condition
requestAnimationFrame(() => {
this.send(FirefoxCommand.FxAStatus, options);
});
});
}
fxaLogin(options: FxALoginRequest): void {
this.send(FirefoxCommand.Login, options);
}
fxaLoginSignedInUser(options: FxALoginSignedInUserRequest) {
this.send(FirefoxCommand.Login, options);
}
fxaLogout(options: { uid: string }) {
this.send(FirefoxCommand.Logout, options);
}
fxaLoaded(options: any) {
this.send(FirefoxCommand.Loaded, options);
}
fxaOAuthLogin(options: FxAOAuthLogin) {
this.send(FirefoxCommand.OAuthLogin, options);
}
fxaOpenSyncPreferences() {
this.send(FirefoxCommand.SyncPreferences, { ok: true });
}
async fxaCanLinkAccount(
options: FxACanLinkAccount
): Promise<FxACanLinkAccountResponse> {
return new Promise((resolve) => {
const eventHandler = (firefoxEvent: any) => {
this.removeEventListener(FirefoxCommand.CanLinkAccount, eventHandler);
resolve(firefoxEvent.detail || { ok: false });
};
this.addEventListener(FirefoxCommand.CanLinkAccount, eventHandler);
requestAnimationFrame(() => {
this.send(FirefoxCommand.CanLinkAccount, options);
});
});
}
/** Check if Firefox has an active OAuth flow in memory. */
async fxaOAuthFlowIsActive(): Promise<FxAOAuthFlowIsActiveResponse> {
let timeoutId: number;
return Promise.race<FxAOAuthFlowIsActiveResponse>([
new Promise<FxAOAuthFlowIsActiveResponse>((resolve) => {
const eventHandler = (firefoxEvent: any) => {
clearTimeout(timeoutId);
this.removeEventListener(
FirefoxCommand.OAuthFlowIsActive,
eventHandler
);
const response = firefoxEvent.detail as FxAOAuthFlowIsActiveResponse;
resolve(response);
};
this.addEventListener(FirefoxCommand.OAuthFlowIsActive, eventHandler);
requestAnimationFrame(() => {
this.send(FirefoxCommand.OAuthFlowIsActive, {});
});
}),
new Promise<FxAOAuthFlowIsActiveResponse>((resolve) => {
timeoutId = window.setTimeout(() => {
// If timeout, assume no active flow (older Firefox or not supported)
resolve({ isActive: false });
}, DEFAULT_SEND_TIMEOUT_LENGTH_MS);
}),
]);
}
/** Start new OAuth flow in Firefox and get fresh params for recovery. */
async fxaOAuthFlowBegin(
scopes: string[]
): Promise<FxAOAuthFlowBeginResponse | null> {
let timeoutId: number;
return Promise.race<FxAOAuthFlowBeginResponse | null>([
new Promise<FxAOAuthFlowBeginResponse | null>((resolve) => {
const eventHandler = (firefoxEvent: any) => {
clearTimeout(timeoutId);
this.removeEventListener(FirefoxCommand.OAuthFlowBegin, eventHandler);
const response = firefoxEvent.detail as FxAOAuthFlowBeginResponse;
resolve(response);
};
this.addEventListener(FirefoxCommand.OAuthFlowBegin, eventHandler);
requestAnimationFrame(() => {
this.send(FirefoxCommand.OAuthFlowBegin, { scopes });
});
}),
new Promise<FxAOAuthFlowBeginResponse | null>((resolve) => {
timeoutId = window.setTimeout(() => {
resolve(null);
}, DEFAULT_SEND_TIMEOUT_LENGTH_MS);
}),
]);
}
// Pairing methods
/** Poll for heartbeat — authority calls this every ~1000ms. */
async pairHeartbeat(channelId: string): Promise<PairHeartbeatResponse> {
let timeoutId: number;
let eventHandler: EventListener | null = null;
return Promise.race<PairHeartbeatResponse>([
new Promise<PairHeartbeatResponse>((resolve) => {
eventHandler = (firefoxEvent: Event) => {
clearTimeout(timeoutId);
this.removeEventListener(FirefoxCommand.PairHeartbeat, eventHandler!);
resolve(
(firefoxEvent as CustomEvent).detail as PairHeartbeatResponse
);
};
this.addEventListener(FirefoxCommand.PairHeartbeat, eventHandler);
requestAnimationFrame(() => {
this.send(FirefoxCommand.PairHeartbeat, { channel_id: channelId });
});
}),
new Promise<PairHeartbeatResponse>((resolve) => {
timeoutId = window.setTimeout(() => {
if (eventHandler) {
this.removeEventListener(
FirefoxCommand.PairHeartbeat,
eventHandler
);
}
resolve({});
}, DEFAULT_SEND_TIMEOUT_LENGTH_MS);
}),
]);
}
/** Request supplicant device metadata from browser. */
async pairSupplicantMetadata(
channelId: string
): Promise<PairSupplicantMetadataResponse> {
return new Promise((resolve, reject) => {
const timeoutId = window.setTimeout(() => {
this.removeEventListener(
FirefoxCommand.PairSupplicantMetadata,
eventHandler
);
reject(new Error('pairSupplicantMetadata timed out'));
}, 10000);
const eventHandler = (firefoxEvent: Event) => {
clearTimeout(timeoutId);
this.removeEventListener(
FirefoxCommand.PairSupplicantMetadata,
eventHandler
);
resolve(
(firefoxEvent as CustomEvent).detail as PairSupplicantMetadataResponse
);
};
this.addEventListener(
FirefoxCommand.PairSupplicantMetadata,
eventHandler
);
requestAnimationFrame(() => {
this.send(FirefoxCommand.PairSupplicantMetadata, {
channel_id: channelId,
});
});
});
}
/**
* Send a pairing command using the request/response pattern (not
* fire-and-forget) so the browser's WebChannel handler completes
* before we proceed — matches Backbone's authority.js which uses
* request() instead of send(). Resolves after the browser responds
* or after a timeout (whichever comes first).
*/
private sendPairingCommand(
command: FirefoxCommand,
channelId: string
): Promise<void> {
return new Promise<void>((resolve) => {
const timeoutId = window.setTimeout(() => {
this.removeEventListener(command, handler);
resolve(); // resolve anyway — browser may not respond
}, DEFAULT_SEND_TIMEOUT_LENGTH_MS);
const handler = () => {
clearTimeout(timeoutId);
this.removeEventListener(command, handler);
resolve();
};
this.addEventListener(command, handler);
requestAnimationFrame(() => {
this.send(command, { channel_id: channelId });
});
});
}
/** Notify browser that authority approved the pairing request. */
async pairAuthorize(channelId: string): Promise<void> {
return this.sendPairingCommand(FirefoxCommand.PairAuthorize, channelId);
}
/** Notify browser that authority declined the pairing request. */
async pairDecline(channelId: string): Promise<void> {
return this.sendPairingCommand(FirefoxCommand.PairDecline, channelId);
}
/** Notify browser that pairing is complete. */
async pairComplete(channelId: string): Promise<void> {
return this.sendPairingCommand(FirefoxCommand.PairComplete, channelId);
}
/*
* Sends an fxa_status and returns the signed in user if available.
*/
async requestSignedInUser(
context: string,
isPairing: boolean,
service: string
): Promise<undefined | SignedInUser> {
let timeoutId: number;
return Promise.race<undefined | SignedInUser>([
new Promise<undefined | SignedInUser>((resolve) => {
const handleFxAStatusEvent = (event: any) => {
clearTimeout(timeoutId);
this.removeEventListener(
FirefoxCommand.FxAStatus,
handleFxAStatusEvent
);
const status = event.detail as FxAStatusResponse;
resolve(status.signedInUser);
};
this.addEventListener(FirefoxCommand.FxAStatus, handleFxAStatusEvent);
// requestAnimationFrame ensures the event listener is added first
// otherwise, there is a race condition
requestAnimationFrame(() => {
this.send(FirefoxCommand.FxAStatus, {
context,
isPairing,
service,
});
});
}),
// Ideally, we would detect WebChannel support instead of relying on a timeout.
// However, it's difficult to reliably detect all compatible environments —
// including Firefox Desktop, Android (Fenix), and iOS (FxA iOS) — especially
// when considering misconfigurations. For example, when using `localhost`
// with a browser configured to talk to production or stage servers,
// the WebChannel may be present but not able to communicate correctly.
// Because of this, we fall back to a short timeout to detect unresponsiveness.
new Promise((resolve) => {
timeoutId = window.setTimeout(() => {
console.warn(
'[Firefox WebChannel] fxa_status timed out or unavailable in this browser'
);
resolve(undefined);
}, DEFAULT_SEND_TIMEOUT_LENGTH_MS);
}),
]);
}
}
// Some non-firefox legacy browsers can't extend EventTarget.
// For those we can safely return a mock instance that
// implements the interface but does nothing because
// this functionality is only meant for firefox.
let canUseEventTarget = true;
try {
new EventTarget();
} catch (e) {
canUseEventTarget = false;
}
function noop() {}
function mock() {
return Object.fromEntries(
Object.getOwnPropertyNames(Firefox.prototype)
.map((name) => [name, noop])
.concat([
['addEventListener', noop],
['removeEventListener', noop],
['dispatchEvent', noop],
])
) as unknown as Firefox;
}
export const firefox = (() => {
try {
if (canUseEventTarget && typeof window.localStorage !== 'undefined') {
return new Firefox();
}
return mock();
} catch (_) {
return mock();
}
})();
export default firefox;