summaryrefslogtreecommitdiff
path: root/services/fxaccounts/FxAccountsOAuthClient.jsm
blob: c59f1a86913d67bf2a1e38ea12e1502763916159 (plain)
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
/* 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/. */

/**
 * Firefox Accounts OAuth browser login helper.
 * Uses the WebChannel component to receive OAuth messages and complete login flows.
 */

this.EXPORTED_SYMBOLS = ["FxAccountsOAuthClient"];

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");
XPCOMUtils.defineLazyModuleGetter(this, "WebChannel",
                                  "resource://gre/modules/WebChannel.jsm");
Cu.importGlobalProperties(["URL"]);

/**
 * Create a new FxAccountsOAuthClient for browser some service.
 *
 * @param {Object} options Options
 *   @param {Object} options.parameters
 *   Opaque alphanumeric token to be included in verification links
 *     @param {String} options.parameters.client_id
 *     OAuth id returned from client registration
 *     @param {String} options.parameters.state
 *     A value that will be returned to the client as-is upon redirection
 *     @param {String} options.parameters.oauth_uri
 *     The FxA OAuth server uri
 *     @param {String} options.parameters.content_uri
 *     The FxA Content server uri
 *     @param {String} [options.parameters.scope]
 *     Optional. A colon-separated list of scopes that the user has authorized
 *     @param {String} [options.parameters.action]
 *     Optional. If provided, should be either signup, signin or force_auth.
 *     @param {String} [options.parameters.email]
 *     Optional. Required if options.paramters.action is 'force_auth'.
 *     @param {Boolean} [options.parameters.keys]
 *     Optional. If true then relier-specific encryption keys will be
 *     available in the second argument to onComplete.
 *   @param [authorizationEndpoint] {String}
 *   Optional authorization endpoint for the OAuth server
 * @constructor
 */
this.FxAccountsOAuthClient = function(options) {
  this._validateOptions(options);
  this.parameters = options.parameters;
  this._configureChannel();

  let authorizationEndpoint = options.authorizationEndpoint || "/authorization";

  try {
    this._fxaOAuthStartUrl = new URL(this.parameters.oauth_uri + authorizationEndpoint + "?");
  } catch (e) {
    throw new Error("Invalid OAuth Url");
  }

  let params = this._fxaOAuthStartUrl.searchParams;
  params.append("client_id", this.parameters.client_id);
  params.append("state", this.parameters.state);
  params.append("scope", this.parameters.scope || "");
  params.append("action", this.parameters.action || "signin");
  params.append("webChannelId", this._webChannelId);
  if (this.parameters.keys) {
    params.append("keys", "true");
  }
  // Only append if we actually have a value.
  if (this.parameters.email) {
    params.append("email", this.parameters.email);
  }
};

this.FxAccountsOAuthClient.prototype = {
  /**
   * Function that gets called once the OAuth flow is complete.
   * The callback will receive an object with code and state properties.
   * If the keys parameter was specified and true, the callback will receive
   * a second argument with kAr and kBr properties.
   */
  onComplete: null,
  /**
   * Function that gets called if there is an error during the OAuth flow,
   * for example due to a state mismatch.
   * The callback will receive an Error object as its argument.
   */
  onError: null,
  /**
   * Configuration object that stores all OAuth parameters.
   */
  parameters: null,
  /**
   * WebChannel that is used to communicate with content page.
   */
  _channel: null,
  /**
   * Boolean to indicate if this client has completed an OAuth flow.
   */
  _complete: false,
  /**
   * The url that opens the Firefox Accounts OAuth flow.
   */
  _fxaOAuthStartUrl: null,
  /**
   * WebChannel id.
   */
  _webChannelId: null,
  /**
   * WebChannel origin, used to validate origin of messages.
   */
  _webChannelOrigin: null,
  /**
   * Opens a tab at "this._fxaOAuthStartUrl".
   * Registers a WebChannel listener and sets up a callback if needed.
   */
  launchWebFlow: function () {
    if (!this._channelCallback) {
      this._registerChannel();
    }

    if (this._complete) {
      throw new Error("This client already completed the OAuth flow");
    } else {
      let opener = Services.wm.getMostRecentWindow("navigator:browser").gBrowser;
      opener.selectedTab = opener.addTab(this._fxaOAuthStartUrl.href);
    }
  },

  /**
   * Release all resources that are in use.
   */
  tearDown: function() {
    this.onComplete = null;
    this.onError = null;
    this._complete = true;
    this._channel.stopListening();
    this._channel = null;
  },

  /**
   * Configures WebChannel id and origin
   *
   * @private
   */
  _configureChannel: function() {
    this._webChannelId = "oauth_" + this.parameters.client_id;

    // if this.parameters.content_uri is present but not a valid URI, then this will throw an error.
    try {
      this._webChannelOrigin = Services.io.newURI(this.parameters.content_uri, null, null);
    } catch (e) {
      throw e;
    }
  },

  /**
   * Create a new channel with the WebChannelBroker, setup a callback listener
   * @private
   */
  _registerChannel: function() {
    /**
     * Processes messages that are called back from the FxAccountsChannel
     *
     * @param webChannelId {String}
     *        Command webChannelId
     * @param message {Object}
     *        Command message
     * @param sendingContext {Object}
     *        Channel message event sendingContext
     * @private
     */
    let listener = function (webChannelId, message, sendingContext) {
      if (message) {
        let command = message.command;
        let data = message.data;
        let target = sendingContext && sendingContext.browser;

        switch (command) {
          case "oauth_complete":
            // validate the returned state and call onComplete or onError
            let result = null;
            let err = null;

            if (this.parameters.state !== data.state) {
              err = new Error("OAuth flow failed. State doesn't match");
            } else if (this.parameters.keys && !data.keys) {
              err = new Error("OAuth flow failed. Keys were not returned");
            } else {
              result = {
                code: data.code,
                state: data.state
              };
            }

            // if the message asked to close the tab
            if (data.closeWindow && target) {
              // for e10s reasons the best way is to use the TabBrowser to close the tab.
              let tabbrowser = target.getTabBrowser();

              if (tabbrowser) {
                let tab = tabbrowser.getTabForBrowser(target);

                if (tab) {
                  tabbrowser.removeTab(tab);
                  log.debug("OAuth flow closed the tab.");
                } else {
                  log.debug("OAuth flow failed to close the tab. Tab not found in TabBrowser.");
                }
              } else {
                log.debug("OAuth flow failed to close the tab. TabBrowser not found.");
              }
            }

            if (err) {
              log.debug(err.message);
              if (this.onError) {
                this.onError(err);
              }
            } else {
              log.debug("OAuth flow completed.");
              if (this.onComplete) {
                if (this.parameters.keys) {
                  this.onComplete(result, data.keys);
                } else {
                  this.onComplete(result);
                }
              }
            }

            // onComplete will be called for this client only once
            // calling onComplete again will result in a failure of the OAuth flow
            this.tearDown();
            break;
        }
      }
    };

    this._channelCallback = listener.bind(this);
    this._channel = new WebChannel(this._webChannelId, this._webChannelOrigin);
    this._channel.listen(this._channelCallback);
    log.debug("Channel registered: " + this._webChannelId + " with origin " + this._webChannelOrigin.prePath);
  },

  /**
   * Validates the required FxA OAuth parameters
   *
   * @param options {Object}
   *        OAuth client options
   * @private
   */
  _validateOptions: function (options) {
    if (!options || !options.parameters) {
      throw new Error("Missing 'parameters' configuration option");
    }

    ["oauth_uri", "client_id", "content_uri", "state"].forEach(option => {
      if (!options.parameters[option]) {
        throw new Error("Missing 'parameters." + option + "' parameter");
      }
    });

    if (options.parameters.action == "force_auth" && !options.parameters.email) {
      throw new Error("parameters.email is required for action 'force_auth'");
    }
  },
};