Bug 1859954 - Use XP_DARWIN rather than XP_MACOS in PHC r=glandium
[gecko.git] / services / fxaccounts / FxAccountsCommands.sys.mjs
blobcf07f45835ad28f700f162591bdea984ac84056e
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/. */
5 import {
6   COMMAND_SENDTAB,
7   COMMAND_SENDTAB_TAIL,
8   SCOPE_OLD_SYNC,
9   log,
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";
16 const lazy = {};
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",
22 });
24 XPCOMUtils.defineLazyPreferenceGetter(
25   lazy,
26   "INVALID_SHAREABLE_SCHEMES",
27   "services.sync.engine.tabs.filteredSchemes",
28   "",
29   null,
30   val => {
31     return new Set(val.split("|"));
32   }
35 export class FxAccountsCommands {
36   constructor(fxAccountsInternal) {
37     this._fxai = fxAccountsInternal;
38     this.sendTab = new SendTab(this, fxAccountsInternal);
39     this._invokeRateLimitExpiry = 0;
40   }
42   async availableCommands() {
43     const encryptedSendTabKeys = await this.sendTab.getEncryptedSendTabKeys();
44     if (!encryptedSendTabKeys) {
45       // This will happen if the account is not verified yet.
46       return {};
47     }
48     return {
49       [COMMAND_SENDTAB]: encryptedSendTabKeys,
50     };
51   }
53   async invoke(command, device, payload) {
54     const { sessionToken } = await this._fxai.getUserAccountData([
55       "sessionToken",
56     ]);
57     const client = this._fxai.fxAccountsClient;
58     const now = Date.now();
59     if (now < this._invokeRateLimitExpiry) {
60       const remaining = (this._invokeRateLimitExpiry - now) / 1000;
61       throw new Error(
62         `Invoke for ${command} is rate-limited for ${remaining} seconds.`
63       );
64     }
65     try {
66       let info = await client.invokeCommand(
67         sessionToken,
68         command,
69         device.id,
70         payload
71       );
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);
75       } else {
76         log.info("Successfully sent", info);
77       }
78     } catch (err) {
79       if (err.code && err.code === 429 && err.retryAfter) {
80         this._invokeRateLimitExpiry = Date.now() + err.retryAfter * 1000;
81       }
82       throw err;
83     }
84     log.info(`Payload sent to device ${device.id}.`);
85   }
87   /**
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.
91    *
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.
95    */
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"]);
103       if (!device) {
104         throw new Error("No device registration.");
105       }
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) {
111         return;
112       }
113       const { index, messages } = await this._fetchDeviceCommands(
114         lastCommandIndex
115       );
116       if (messages.length) {
117         await state.updateUserAccountData({
118           device: { ...device, lastCommandIndex: index },
119         });
120         log.info(`Handling ${messages.length} messages`);
121         await this._handleCommands(messages, notifiedIndex);
122       }
123     });
124     return true;
125   }
127   async _fetchDeviceCommands(index, limit = null) {
128     const userData = await this._fxai.getUserAccountData();
129     if (!userData) {
130       throw new Error("No user.");
131     }
132     const { sessionToken } = userData;
133     if (!sessionToken) {
134       throw new Error("No session token.");
135     }
136     const client = this._fxai.fxAccountsClient;
137     const opts = { index };
138     if (limit != null) {
139       opts.limit = limit;
140     }
141     return client.getCommands(sessionToken, opts);
142   }
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) {
151       return "poll";
152     } else if (notifiedIndex > messageIndex) {
153       return "push-missed";
154     }
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
157     // present.
158     return "push";
159   }
161   async _handleCommands(messages, notifiedIndex) {
162     try {
163       await this._fxai.device.refreshDeviceList();
164     } catch (e) {
165       log.warn("Error refreshing device list", e);
166     }
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);
172       const sender =
173         senderId && this._fxai.device.recentDeviceList
174           ? this._fxai.device.recentDeviceList.find(d => d.id == senderId)
175           : null;
176       if (!sender) {
177         log.warn(
178           "Incoming command is from an unknown device (maybe disconnected?)"
179         );
180       }
181       switch (command) {
182         case COMMAND_SENDTAB:
183           try {
184             const { title, uri } = await this.sendTab.handle(
185               senderId,
186               payload,
187               reason
188             );
189             log.info(
190               `Tab received with FxA commands: ${title} from ${
191                 sender ? sender.name : "Unknown device"
192               }.`
193             );
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.");
200             }
201             tabsReceived.push({ title, uri, sender });
202           } catch (e) {
203             log.error(`Error while handling incoming Send Tab payload.`, e);
204           }
205           break;
206         default:
207           log.info(`Unknown command: ${command}.`);
208       }
209     }
210     if (tabsReceived.length) {
211       this._notifyFxATabsReceived(tabsReceived);
212     }
213   }
215   _notifyFxATabsReceived(tabsReceived) {
216     Observers.notify("fxaccounts:commands:open-uri", tabsReceived);
217   }
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.
233  */
234 export class SendTab {
235   constructor(commands, fxAccountsInternal) {
236     this._commands = commands;
237     this._fxai = fxAccountsInternal;
238   }
239   /**
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}]}
246    */
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 }] };
252     const report = {
253       succeeded: [],
254       failed: [],
255     };
256     for (let device of to) {
257       try {
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(
268           "command-sent",
269           COMMAND_SENDTAB_TAIL,
270           this._fxai.telemetry.sanitizeDeviceId(device.id),
271           { flowID, streamID }
272         );
273         report.succeeded.push(device);
274       } catch (error) {
275         log.error("Error while invoking a send tab command.", error);
276         report.failed.push({ device, error });
277       }
278     }
279     return report;
280   }
282   // Returns true if the target device is compatible with FxA Commands Send tab.
283   isDeviceCompatible(device) {
284     return (
285       device.availableCommands && device.availableCommands[COMMAND_SENDTAB]
286     );
287   }
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")
296       ? data.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(
303       "command-received",
304       COMMAND_SENDTAB_TAIL,
305       this._fxai.telemetry.sanitizeDeviceId(senderID),
306       { flowID, streamID, reason }
307     );
309     return {
310       title,
311       uri,
312     };
313   }
315   async _encrypt(bytes, device) {
316     let bundle = device.availableCommands[COMMAND_SENDTAB];
317     if (!bundle) {
318       throw new Error(`Device ${device.id} does not have send tab keys.`);
319     }
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]
325     );
326     if (theirKid != ourKid) {
327       throw new Error("Target Send Tab key ID is different from ours");
328     }
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(
338       bytes,
339       publicKey,
340       authSecret
341     );
342     return urlsafeBase64Encode(encrypted);
343   }
345   async _getPersistedSendTabKeys() {
346     const { device } = await this._fxai.getUserAccountData(["device"]);
347     return device && device.sendTabKeys;
348   }
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(
357       privateKey,
358       publicKey,
359       authSecret,
360       // The only Push encoding we support.
361       { encoding: "aes128gcm" },
362       ciphertext
363     );
364   }
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 = {
372       publicKey,
373       privateKey,
374       authSecret,
375     };
376     await this._fxai.withCurrentAccountState(async state => {
377       const { device } = await state.getUserAccountData(["device"]);
378       await state.updateUserAccountData({
379         device: {
380           ...device,
381           sendTabKeys,
382         },
383       });
384     });
385     return sendTabKeys;
386   }
388   async _getPersistedEncryptedSendTabKey() {
389     const { encryptedSendTabKeys } = await this._fxai.getUserAccountData([
390       "encryptedSendTabKeys",
391     ]);
392     return encryptedSendTabKeys;
393   }
395   async _generateAndPersistEncryptedSendTabKey() {
396     let sendTabKeys = await this._getPersistedSendTabKeys();
397     if (!sendTabKeys) {
398       log.info("Could not find sendtab keys, generating them");
399       sendTabKeys = await this._generateAndPersistSendTabKeys();
400     }
401     // Strip the private key from the bundle to encrypt.
402     const keyToEncrypt = {
403       publicKey: sendTabKeys.publicKey,
404       authSecret: sendTabKeys.authSecret,
405     };
406     if (!(await this._fxai.keys.canGetKeyForScope(SCOPE_OLD_SYNC))) {
407       log.info("Can't fetch keys, so unable to determine sendtab keys");
408       return null;
409     }
410     let oldsyncKey;
411     try {
412       oldsyncKey = await this._fxai.keys.getKeyForScope(SCOPE_OLD_SYNC);
413     } catch (ex) {
414       log.warn("Failed to fetch keys, so unable to determine sendtab keys", ex);
415       return null;
416     }
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),
424       IV: wrapper.IV,
425       hmac: wrapper.hmac,
426       ciphertext: wrapper.ciphertext,
427     });
428     await this._fxai.withCurrentAccountState(async state => {
429       await state.updateUserAccountData({
430         encryptedSendTabKeys,
431       });
432     });
433     return encryptedSendTabKeys;
434   }
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
451       // it though)
452       encryptedSendTabKeys =
453         await this._generateAndPersistEncryptedSendTabKey();
454     }
455     return encryptedSendTabKeys;
456   }
459 function urlsafeBase64Encode(buffer) {
460   return ChromeUtils.base64URLEncode(new Uint8Array(buffer), { pad: false });
463 function urlsafeBase64Decode(str) {
464   return ChromeUtils.base64URLDecode(str, { padding: "reject" });