1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10 } from "resource://gre/modules/FxAccountsCommon.sys.mjs";
12 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
14 import { Observers } from "resource://services-common/observers.sys.mjs";
18 ChromeUtils.defineESModuleGetters(lazy, {
19 BulkKeyBundle: "resource://services-sync/keys.sys.mjs",
20 CryptoWrapper: "resource://services-sync/record.sys.mjs",
21 PushCrypto: "resource://gre/modules/PushCrypto.sys.mjs",
24 XPCOMUtils.defineLazyPreferenceGetter(
26 "INVALID_SHAREABLE_SCHEMES",
27 "services.sync.engine.tabs.filteredSchemes",
31 return new Set(val.split("|"));
35 export class FxAccountsCommands {
36 constructor(fxAccountsInternal) {
37 this._fxai = fxAccountsInternal;
38 this.sendTab = new SendTab(this, fxAccountsInternal);
39 this._invokeRateLimitExpiry = 0;
42 async availableCommands() {
43 const encryptedSendTabKeys = await this.sendTab.getEncryptedSendTabKeys();
44 if (!encryptedSendTabKeys) {
45 // This will happen if the account is not verified yet.
49 [COMMAND_SENDTAB]: encryptedSendTabKeys,
53 async invoke(command, device, payload) {
54 const { sessionToken } = await this._fxai.getUserAccountData([
57 const client = this._fxai.fxAccountsClient;
58 const now = Date.now();
59 if (now < this._invokeRateLimitExpiry) {
60 const remaining = (this._invokeRateLimitExpiry - now) / 1000;
62 `Invoke for ${command} is rate-limited for ${remaining} seconds.`
66 let info = await client.invokeCommand(
72 if (!info.enqueued || !info.notified) {
73 // We want an error log here to help diagnose users who report failure.
74 log.error("Sending was only partially successful", info);
76 log.info("Successfully sent", info);
79 if (err.code && err.code === 429 && err.retryAfter) {
80 this._invokeRateLimitExpiry = Date.now() + err.retryAfter * 1000;
84 log.info(`Payload sent to device ${device.id}.`);
88 * Poll and handle device commands for the current device.
89 * This method can be called either in response to a Push message,
90 * or by itself as a "commands recovery" mechanism.
92 * @param {Number} notifiedIndex "Command received" push messages include
93 * the index of the command that triggered the message. We use it as a
94 * hint when we have no "last command index" stored.
96 async pollDeviceCommands(notifiedIndex = 0) {
97 // Whether the call to `pollDeviceCommands` was initiated by a Push message from the FxA
98 // servers in response to a message being received or simply scheduled in order
99 // to fetch missed messages.
100 log.info(`Polling device commands.`);
101 await this._fxai.withCurrentAccountState(async state => {
102 const { device } = await state.getUserAccountData(["device"]);
104 throw new Error("No device registration.");
106 // We increment lastCommandIndex by 1 because the server response includes the current index.
107 // If we don't have a `lastCommandIndex` stored, we fall back on the index from the push message we just got.
108 const lastCommandIndex = device.lastCommandIndex + 1 || notifiedIndex;
109 // We have already received this message before.
110 if (notifiedIndex > 0 && notifiedIndex < lastCommandIndex) {
113 const { index, messages } = await this._fetchDeviceCommands(
116 if (messages.length) {
117 await state.updateUserAccountData({
118 device: { ...device, lastCommandIndex: index },
120 log.info(`Handling ${messages.length} messages`);
121 await this._handleCommands(messages, notifiedIndex);
127 async _fetchDeviceCommands(index, limit = null) {
128 const userData = await this._fxai.getUserAccountData();
130 throw new Error("No user.");
132 const { sessionToken } = userData;
134 throw new Error("No session token.");
136 const client = this._fxai.fxAccountsClient;
137 const opts = { index };
141 return client.getCommands(sessionToken, opts);
144 _getReason(notifiedIndex, messageIndex) {
145 // The returned reason value represents an explanation for why the command associated with the
146 // message of the given `messageIndex` is being handled. If `notifiedIndex` is zero the command
147 // is a part of a fallback polling process initiated by "Sync Now" ["poll"]. If `notifiedIndex` is
148 // greater than `messageIndex` this is a push command that was previously missed ["push-missed"],
149 // otherwise we assume this is a push command with no missed messages ["push"].
150 if (notifiedIndex == 0) {
152 } else if (notifiedIndex > messageIndex) {
153 return "push-missed";
155 // Note: The returned reason might be "push" in the case where a user sends multiple tabs
156 // in quick succession. We are not attempting to distinguish this from other push cases at
161 async _handleCommands(messages, notifiedIndex) {
163 await this._fxai.device.refreshDeviceList();
165 log.warn("Error refreshing device list", e);
167 // We debounce multiple incoming tabs so we show a single notification.
168 const tabsReceived = [];
169 for (const { index, data } of messages) {
170 const { command, payload, sender: senderId } = data;
171 const reason = this._getReason(notifiedIndex, index);
173 senderId && this._fxai.device.recentDeviceList
174 ? this._fxai.device.recentDeviceList.find(d => d.id == senderId)
178 "Incoming command is from an unknown device (maybe disconnected?)"
182 case COMMAND_SENDTAB:
184 const { title, uri } = await this.sendTab.handle(
190 `Tab received with FxA commands: ${title} from ${
191 sender ? sender.name : "Unknown device"
194 // This should eventually be rare to hit as all platforms will be using the same
195 // scheme filter list, but we have this here in the case other platforms
196 // haven't caught up and/or trying to send invalid uris using older versions
197 const scheme = Services.io.newURI(uri).scheme;
198 if (lazy.INVALID_SHAREABLE_SCHEMES.has(scheme)) {
199 throw new Error("Invalid scheme found for received URI.");
201 tabsReceived.push({ title, uri, sender });
203 log.error(`Error while handling incoming Send Tab payload.`, e);
207 log.info(`Unknown command: ${command}.`);
210 if (tabsReceived.length) {
211 this._notifyFxATabsReceived(tabsReceived);
215 _notifyFxATabsReceived(tabsReceived) {
216 Observers.notify("fxaccounts:commands:open-uri", tabsReceived);
221 * Send Tab is built on top of FxA commands.
223 * Devices exchange keys wrapped in the oldsync key between themselves (getEncryptedSendTabKeys)
224 * during the device registration flow. The FxA server can theoretically never
225 * retrieve the send tab keys since it doesn't know the oldsync key.
227 * Note about the keys:
228 * The server has the `pushPublicKey`. The FxA server encrypt the send-tab payload again using the
229 * push keys - after the client has encrypted the payload using the send-tab keys.
230 * The push keys are different from the send-tab keys. The FxA server uses
231 * the push keys to deliver the tabs using same mechanism we use for web-push.
232 * However, clients use the send-tab keys for end-to-end encryption.
234 export class SendTab {
235 constructor(commands, fxAccountsInternal) {
236 this._commands = commands;
237 this._fxai = fxAccountsInternal;
240 * @param {Device[]} to - Device objects (typically returned by fxAccounts.getDevicesList()).
241 * @param {Object} tab
242 * @param {string} tab.url
243 * @param {string} tab.title
244 * @returns A report object, in the shape of
245 * {succeded: [Device], error: [{device: Device, error: Exception}]}
247 async send(to, tab) {
248 log.info(`Sending a tab to ${to.length} devices.`);
249 const flowID = this._fxai.telemetry.generateFlowID();
250 const encoder = new TextEncoder();
251 const data = { entries: [{ title: tab.title, url: tab.url }] };
256 for (let device of to) {
258 const streamID = this._fxai.telemetry.generateFlowID();
259 const targetData = Object.assign({ flowID, streamID }, data);
260 const bytes = encoder.encode(JSON.stringify(targetData));
261 const encrypted = await this._encrypt(bytes, device);
262 // FxA expects an object as the payload, but we only have a single encrypted string; wrap it.
263 // If you add any plaintext items to this payload, please carefully consider the privacy implications
264 // of revealing that data to the FxA server.
265 const payload = { encrypted };
266 await this._commands.invoke(COMMAND_SENDTAB, device, payload);
267 this._fxai.telemetry.recordEvent(
269 COMMAND_SENDTAB_TAIL,
270 this._fxai.telemetry.sanitizeDeviceId(device.id),
273 report.succeeded.push(device);
275 log.error("Error while invoking a send tab command.", error);
276 report.failed.push({ device, error });
282 // Returns true if the target device is compatible with FxA Commands Send tab.
283 isDeviceCompatible(device) {
285 device.availableCommands && device.availableCommands[COMMAND_SENDTAB]
289 // Handle incoming send tab payload, called by FxAccountsCommands.
290 async handle(senderID, { encrypted }, reason) {
291 const bytes = await this._decrypt(encrypted);
292 const decoder = new TextDecoder("utf8");
293 const data = JSON.parse(decoder.decode(bytes));
294 const { flowID, streamID, entries } = data;
295 const current = data.hasOwnProperty("current")
297 : entries.length - 1;
298 const { title, url: uri } = entries[current];
299 // `flowID` and `streamID` are in the top-level of the JSON, `entries` is
300 // an array of "tabs" with `current` being what index is the one we care
301 // about, or the last one if not specified.
302 this._fxai.telemetry.recordEvent(
304 COMMAND_SENDTAB_TAIL,
305 this._fxai.telemetry.sanitizeDeviceId(senderID),
306 { flowID, streamID, reason }
315 async _encrypt(bytes, device) {
316 let bundle = device.availableCommands[COMMAND_SENDTAB];
318 throw new Error(`Device ${device.id} does not have send tab keys.`);
320 const oldsyncKey = await this._fxai.keys.getKeyForScope(SCOPE_OLD_SYNC);
321 // Older clients expect this to be hex, due to pre-JWK sync key ids :-(
322 const ourKid = this._fxai.keys.kidAsHex(oldsyncKey);
323 const { kid: theirKid } = JSON.parse(
324 device.availableCommands[COMMAND_SENDTAB]
326 if (theirKid != ourKid) {
327 throw new Error("Target Send Tab key ID is different from ours");
329 const json = JSON.parse(bundle);
330 const wrapper = new lazy.CryptoWrapper();
331 wrapper.deserialize({ payload: json });
332 const syncKeyBundle = lazy.BulkKeyBundle.fromJWK(oldsyncKey);
333 let { publicKey, authSecret } = await wrapper.decrypt(syncKeyBundle);
334 authSecret = urlsafeBase64Decode(authSecret);
335 publicKey = urlsafeBase64Decode(publicKey);
337 const { ciphertext: encrypted } = await lazy.PushCrypto.encrypt(
342 return urlsafeBase64Encode(encrypted);
345 async _getPersistedSendTabKeys() {
346 const { device } = await this._fxai.getUserAccountData(["device"]);
347 return device && device.sendTabKeys;
350 async _decrypt(ciphertext) {
351 let { privateKey, publicKey, authSecret } =
352 await this._getPersistedSendTabKeys();
353 publicKey = urlsafeBase64Decode(publicKey);
354 authSecret = urlsafeBase64Decode(authSecret);
355 ciphertext = new Uint8Array(urlsafeBase64Decode(ciphertext));
356 return lazy.PushCrypto.decrypt(
360 // The only Push encoding we support.
361 { encoding: "aes128gcm" },
366 async _generateAndPersistSendTabKeys() {
367 let [publicKey, privateKey] = await lazy.PushCrypto.generateKeys();
368 publicKey = urlsafeBase64Encode(publicKey);
369 let authSecret = lazy.PushCrypto.generateAuthenticationSecret();
370 authSecret = urlsafeBase64Encode(authSecret);
371 const sendTabKeys = {
376 await this._fxai.withCurrentAccountState(async state => {
377 const { device } = await state.getUserAccountData(["device"]);
378 await state.updateUserAccountData({
388 async _getPersistedEncryptedSendTabKey() {
389 const { encryptedSendTabKeys } = await this._fxai.getUserAccountData([
390 "encryptedSendTabKeys",
392 return encryptedSendTabKeys;
395 async _generateAndPersistEncryptedSendTabKey() {
396 let sendTabKeys = await this._getPersistedSendTabKeys();
398 log.info("Could not find sendtab keys, generating them");
399 sendTabKeys = await this._generateAndPersistSendTabKeys();
401 // Strip the private key from the bundle to encrypt.
402 const keyToEncrypt = {
403 publicKey: sendTabKeys.publicKey,
404 authSecret: sendTabKeys.authSecret,
406 if (!(await this._fxai.keys.canGetKeyForScope(SCOPE_OLD_SYNC))) {
407 log.info("Can't fetch keys, so unable to determine sendtab keys");
412 oldsyncKey = await this._fxai.keys.getKeyForScope(SCOPE_OLD_SYNC);
414 log.warn("Failed to fetch keys, so unable to determine sendtab keys", ex);
417 const wrapper = new lazy.CryptoWrapper();
418 wrapper.cleartext = keyToEncrypt;
419 const keyBundle = lazy.BulkKeyBundle.fromJWK(oldsyncKey);
420 await wrapper.encrypt(keyBundle);
421 const encryptedSendTabKeys = JSON.stringify({
422 // This is expected in hex, due to pre-JWK sync key ids :-(
423 kid: this._fxai.keys.kidAsHex(oldsyncKey),
426 ciphertext: wrapper.ciphertext,
428 await this._fxai.withCurrentAccountState(async state => {
429 await state.updateUserAccountData({
430 encryptedSendTabKeys,
433 return encryptedSendTabKeys;
436 async getEncryptedSendTabKeys() {
437 let encryptedSendTabKeys = await this._getPersistedEncryptedSendTabKey();
438 const sendTabKeys = await this._getPersistedSendTabKeys();
439 if (!encryptedSendTabKeys || !sendTabKeys) {
440 log.info("Generating and persisting encrypted sendtab keys");
441 // `_generateAndPersistEncryptedKeys` requires the sync key
442 // which cannot be accessed if the login manager is locked
443 // (i.e when the primary password is locked) or if the sync keys
444 // aren't accessible (account isn't verified)
445 // so this function could fail to retrieve the keys
446 // however, device registration will trigger when the account
447 // is verified, so it's OK
448 // Note that it's okay to persist those keys, because they are
449 // already persisted in plaintext and the encrypted bundle
450 // does not include the sync-key (the sync key is used to encrypt
452 encryptedSendTabKeys =
453 await this._generateAndPersistEncryptedSendTabKey();
455 return encryptedSendTabKeys;
459 function urlsafeBase64Encode(buffer) {
460 return ChromeUtils.base64URLEncode(new Uint8Array(buffer), { pad: false });
463 function urlsafeBase64Decode(str) {
464 return ChromeUtils.base64URLDecode(str, { padding: "reject" });