File: IPPEnrollAndEntitleManager.sys.mjs

package info (click to toggle)
firefox 149.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,767,760 kB
  • sloc: cpp: 7,416,064; javascript: 6,752,859; ansic: 3,774,850; python: 1,250,473; xml: 641,578; asm: 439,191; java: 186,617; sh: 56,634; makefile: 18,856; objc: 13,092; perl: 12,763; pascal: 5,960; yacc: 4,583; cs: 3,846; lex: 1,720; ruby: 1,002; php: 436; lisp: 258; awk: 105; sql: 66; sed: 53; csh: 10; exp: 6
file content (372 lines) | stat: -rw-r--r-- 10,798 bytes parent folder | download
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
/* 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/. */

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  IPPProxyManager:
    "moz-src:///browser/components/ipprotection/IPPProxyManager.sys.mjs",
  IPPStartupCache:
    "moz-src:///browser/components/ipprotection/IPPStartupCache.sys.mjs",
  IPProtectionService:
    "moz-src:///browser/components/ipprotection/IPProtectionService.sys.mjs",
  IPPSignInWatcher:
    "moz-src:///browser/components/ipprotection/IPPSignInWatcher.sys.mjs",
});

const LOG_PREF = "browser.ipProtection.log";

ChromeUtils.defineLazyGetter(lazy, "logConsole", function () {
  return console.createInstance({
    prefix: "IPPEnrollAndEntitleManager",
    maxLogLevel: Services.prefs.getBoolPref(LOG_PREF, false) ? "Debug" : "Warn",
  });
});

/**
 * This class manages the enrolling and entitlement.
 */
class IPPEnrollAndEntitleManagerSingleton extends EventTarget {
  #entitlement = null;

  // Promises to queue enrolling and entitling operations.
  #enrollingPromise = null;
  #entitlementPromise = null;

  constructor() {
    super();

    this.handleEvent = this.#handleEvent.bind(this);
  }

  get entitlement() {
    return this.#entitlement;
  }

  init() {
    // We will use data from the cache until we are fully functional. Then we
    // will recompute the state in `initOnStartupCompleted`.
    this.#entitlement = lazy.IPPStartupCache.entitlement;

    lazy.IPPSignInWatcher.addEventListener(
      "IPPSignInWatcher:StateChanged",
      this.handleEvent
    );
  }

  initOnStartupCompleted() {
    if (!lazy.IPPSignInWatcher.isSignedIn) {
      return;
    }
    // This bit must be async because we want to trigger the updateState at
    // the end of the rest of the initialization.
    this.updateEntitlement();
  }

  uninit() {
    lazy.IPPSignInWatcher.removeEventListener(
      "IPPSignInWatcher:StateChanged",
      this.handleEvent
    );

    this.#entitlement = null;
  }

  #handleEvent(_event) {
    if (!lazy.IPPSignInWatcher.isSignedIn) {
      this.#setEntitlement(null);
      return;
    }
    this.updateEntitlement();
  }

  /**
   * Updates the entitlement status.
   * This will run only one fetch at a time, and queue behind any ongoing enrollment.
   *
   * @param {boolean} forceRefetch - If true, will refetch the entitlement even when one is present.
   * @returns {Promise<object>} status
   * @returns {boolean} status.isEntitled - True if the user is entitled.
   * @returns {string} [status.error] - Error message if entitlement fetch failed.
   */
  async updateEntitlement(forceRefetch = false) {
    if (this.#entitlementPromise) {
      return this.#entitlementPromise;
    }

    // Queue behind any ongoing enrollment.
    if (this.#enrollingPromise) {
      await this.#enrollingPromise;
    }

    let deferred = Promise.withResolvers();
    this.#entitlementPromise = deferred.promise;

    const entitled = await this.#entitle(forceRefetch);
    deferred.resolve(entitled);

    if (entitled?.isEntitled) {
      lazy.IPPProxyManager.refreshUsage();
    }

    this.#entitlementPromise = null;
    return entitled;
  }

  /**
   * Enrolls and entitles the current Firefox account when possible.
   * This is a long-running request that will set isEnrolling while in progress
   * and will only run once until it completes.
   *
   * @param {AbortSignal} [abortSignal=null] - a signal to indicate the process should be aborted
   * @returns {Promise<object>} result
   * @returns {boolean} result.isEnrolledAndEntitled - True if the user is enrolled and entitled.
   * @returns {string} [result.error] - Error message if enrollment or entitlement failed.
   */
  async maybeEnrollAndEntitle(abortSignal = null) {
    if (this.#enrollingPromise) {
      return this.#enrollingPromise;
    }

    let deferred = Promise.withResolvers();
    this.#enrollingPromise = deferred.promise;

    const enrolledAndEntitled = await this.#enrollAndEntitle(abortSignal);
    deferred.resolve(enrolledAndEntitled);
    this.#enrollingPromise = null;

    return enrolledAndEntitled;
  }

  /**
   * Enroll and entitle the current Firefox account.
   *
   * This will attempt to enroll the user if they are not enrolled, and then fetch
   *
   * @param {AbortSignal} abortSignal - a signal to abort the enrollment
   * @returns {Promise<object>} status
   * @returns {boolean} status.isEnrolledAndEntitled - True if the user is enrolled and entitled.
   * @returns {string} [status.error] - Error message if enrollment or entitlement failed.
   */
  async #enrollAndEntitle(abortSignal = null) {
    if (this.#entitlement) {
      return { isEnrolledAndEntitled: true };
    }

    const { enrollment, error: enrollmentError } =
      await IPPEnrollAndEntitleManagerSingleton.#enroll(abortSignal);

    if (enrollmentError || !enrollment) {
      // Unset the entitlement if enrollment failed.
      this.#setEntitlement(null);
      return { isEnrolledAndEntitled: false, error: enrollmentError };
    }

    const { entitlement, error: entitlementError } =
      await IPPEnrollAndEntitleManagerSingleton.#getEntitlement();

    if (entitlementError || !entitlement) {
      // Unset the entitlement if not available.
      this.#setEntitlement(null);
      return { isEnrolledAndEntitled: false, error: entitlementError };
    }

    this.#setEntitlement(entitlement);
    return { isEnrolledAndEntitled: true };
  }

  /**
   * Fetch and update the entitlement.
   *
   * @param {boolean} forceRefetch - If true, will refetch the entitlement even when one is present.
   * @returns {Promise<object>} status
   * @returns {boolean} status.isEntitled - True if the user is entitled.
   * @returns {string} [status.error] - Error message if entitlement fetch failed.
   */
  async #entitle(forceRefetch = false) {
    if (this.#entitlement && !forceRefetch) {
      return { isEntitled: true };
    }

    // Linked does not mean enrolled: it could be that the link comes from a
    // previous MozillaVPN subscription.
    let isLinked =
      await IPPEnrollAndEntitleManagerSingleton.#isLinkedToGuardian(
        !forceRefetch
      );

    if (!isLinked) {
      this.#setEntitlement(null);
      return { isEntitled: false };
    }

    // Enrolling will handle updating the entitlement.
    if (this.#enrollingPromise) {
      return { isEntitled: false };
    }

    let { entitlement, error } =
      await IPPEnrollAndEntitleManagerSingleton.#getEntitlement();

    if (error || !entitlement) {
      this.#setEntitlement(null);
      return { isEntitled: false, error };
    }

    this.#setEntitlement(entitlement);
    return { isEntitled: true };
  }

  // These methods are static because we don't want to change the internal state
  // of the singleton.

  /**
   * Enrolls the current Firefox account with Guardian.
   *
   * Static to avoid changing internal state of the singleton.
   *
   * @param {AbortSignal} [abortSignal=null] - a signal to indicate the enrollment should be aborted
   * @returns {Promise<object>} status
   * @returns {boolean} status.enrollment - True if enrollment succeeded.
   * @returns {string} [status.error] - Error message if enrollment failed.
   */
  static async #enroll(abortSignal = null) {
    try {
      const enrollment = await lazy.IPProtectionService.guardian.enroll(
        "alpha",
        abortSignal
      );
      if (!enrollment?.ok) {
        return { enrollment: null, error: enrollment?.error };
      }
    } catch (error) {
      return { enrollment: null, error: error?.message };
    }
    return { enrollment: true };
  }

  /**
   * Checks if the current Firefox account is linked to Guardian.
   *
   * Static to avoid changing internal state of the singleton.
   *
   * @param {boolean} useCache - If true, will use cached value if available.
   * @returns {Promise<boolean>} - True if linked, false otherwise.
   */
  static async #isLinkedToGuardian(useCache = true) {
    try {
      let isLinked = await lazy.IPProtectionService.guardian.isLinkedToGuardian(
        /* only cache: */ useCache
      );

      return isLinked;
    } catch (_) {
      return false;
    }
  }

  /**
   * Fetches the entitlement for the current Firefox account.
   *
   * Static to avoid changing internal state of the singleton.
   *
   * @returns {Promise<object>} status
   * @returns {object} status.entitlement - The entitlement object.
   * @returns {string} [status.error] - Error message if fetching entitlement failed.
   */
  static async #getEntitlement() {
    try {
      const { status, entitlement, error } =
        await lazy.IPProtectionService.guardian.fetchUserInfo();
      lazy.logConsole.debug("Entitlement:", { status, entitlement, error });

      if (error || !entitlement || status != 200) {
        return { entitlement: null, error: error || `Status: ${status}` };
      }

      return { entitlement };
    } catch (error) {
      return { entitlement: null, error: error.message };
    }
  }

  /**
   * Sets the entitlement and updates the cache and IPProtectionService state.
   *
   * @param {object | null} entitlement - The entitlement object or null to unset.
   */
  #setEntitlement(entitlement) {
    this.#entitlement = entitlement;
    lazy.IPPStartupCache.storeEntitlement(this.#entitlement);

    lazy.IPProtectionService.updateState();

    this.dispatchEvent(
      new CustomEvent("IPPEnrollAndEntitleManager:StateChanged", {
        bubbles: true,
        composed: true,
      })
    );
  }

  /**
   * Checks if we have the entitlement
   */
  get isEnrolledAndEntitled() {
    return !!this.#entitlement;
  }

  /**
   * Checks if a user has upgraded.
   *
   * @returns {boolean}
   */
  get hasUpgraded() {
    return this.#entitlement?.subscribed;
  }

  /**
   * Checks if we're running the Alpha variant based on
   * available features
   */
  get isAlpha() {
    return (
      !this.#entitlement?.autostart &&
      !this.#entitlement?.website_inclusion &&
      !this.#entitlement?.location_controls
    );
  }

  /**
   * Checks if we are currently enrolling.
   */
  get isEnrolling() {
    return !!this.#enrollingPromise;
  }

  /**
   * Waits for the current enrollment to complete, if any.
   */
  async waitForEnrollment() {
    return this.#enrollingPromise;
  }

  /**
   * Refetches the entitlement even if it is cached.
   */
  async refetchEntitlement() {
    await this.updateEntitlement(true);
  }

  /**
   * Unsets any stored entitlement.
   */
  resetEntitlement() {
    this.#setEntitlement(null);
  }
}

const IPPEnrollAndEntitleManager = new IPPEnrollAndEntitleManagerSingleton();

export { IPPEnrollAndEntitleManager };