@moonbase.sh/licensing 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ ActivationController: () => ActivationController,
34
+ ActivationError: () => ActivationError,
33
35
  ActivationMethod: () => ActivationMethod,
34
36
  DEVICE_ID_SOURCE_TAGS: () => DEVICE_ID_SOURCE_TAGS,
35
37
  ErrorType: () => ErrorType,
@@ -39,6 +41,7 @@ __export(index_exports, {
39
41
  IDENTIFYING_PARAM_NAMES: () => IDENTIFYING_PARAM_NAMES,
40
42
  InMemoryLicenseStore: () => InMemoryLicenseStore,
41
43
  InsufficientDeviceIdentityError: () => InsufficientDeviceIdentityError,
44
+ InventoryClient: () => InventoryClient,
42
45
  LegacyDeviceIdResolver: () => LegacyDeviceIdResolver,
43
46
  LicenseClient: () => LicenseClient,
44
47
  LicenseValidator: () => LicenseValidator,
@@ -49,14 +52,18 @@ __export(index_exports, {
49
52
  MoonbaseLicensing: () => MoonbaseLicensing,
50
53
  ReleaseNotCoveredError: () => ReleaseNotCoveredError,
51
54
  buildFingerprintMaterial: () => buildFingerprintMaterial,
55
+ canDownload: () => canDownload,
52
56
  canonicalizeParams: () => canonicalizeParams,
53
57
  canonicalizeValue: () => canonicalizeValue,
54
58
  coversVersion: () => coversVersion,
55
59
  defaultDeviceIdentityReader: () => defaultDeviceIdentityReader,
60
+ filenameFromDownloadUrl: () => filenameFromDownloadUrl,
56
61
  fingerprintDeviceId: () => fingerprintDeviceId,
57
62
  fingerprintDigest: () => fingerprintDigest,
58
63
  hasSubProduct: () => hasSubProduct,
59
64
  identitySource: () => identitySource,
65
+ isNewerVersion: () => isNewerVersion,
66
+ licensingVersion: () => version,
60
67
  parseAppVersion: () => parseAppVersion,
61
68
  parseDeviceIdStamp: () => parseDeviceIdStamp,
62
69
  parseIoregPlatformUuid: () => parseIoregPlatformUuid,
@@ -66,14 +73,14 @@ __export(index_exports, {
66
73
  stampDeviceId: () => stampDeviceId
67
74
  });
68
75
  module.exports = __toCommonJS(index_exports);
69
- var import_node_buffer2 = require("buffer");
70
- var import_node_process3 = __toESM(require("process"), 1);
71
-
72
- // src/client.ts
73
- var import_cross_fetch = __toESM(require("cross-fetch"), 1);
74
76
 
75
77
  // package.json
76
- var version = "3.3.0";
78
+ var version = "3.5.0";
79
+
80
+ // src/activation/controller.ts
81
+ var import_promises4 = __toESM(require("fs/promises"), 1);
82
+ var import_node_path4 = __toESM(require("path"), 1);
83
+ var import_jsonwebtoken2 = __toESM(require("jsonwebtoken"), 1);
77
84
 
78
85
  // src/errors.ts
79
86
  var ErrorType = /* @__PURE__ */ ((ErrorType2) => {
@@ -124,6 +131,18 @@ var ReleaseNotCoveredError = class extends MoonbaseError {
124
131
  }
125
132
  };
126
133
 
134
+ // src/inventory.ts
135
+ var import_cross_fetch = __toESM(require("cross-fetch"), 1);
136
+ var import_zod2 = require("zod");
137
+
138
+ // src/clientHeader.ts
139
+ function clientHeader(configuration) {
140
+ var _a;
141
+ const own = `@moonbase.sh/licensing/${version}`;
142
+ const layers = (_a = configuration.clientInfo) == null ? void 0 : _a.trim();
143
+ return layers ? `${layers} ${own}` : own;
144
+ }
145
+
127
146
  // src/schemas.ts
128
147
  var import_zod = require("zod");
129
148
 
@@ -285,6 +304,12 @@ var releaseAccessSchema = import_zod.z.object({
285
304
  });
286
305
  var licenseSchema = import_zod.z.object({
287
306
  id: import_zod.z.string(),
307
+ /**
308
+ * This device's activation of the license: it stays the same when the license
309
+ * is validated again, and a new activation gets a new one. Absent in a license
310
+ * stored before this release read it.
311
+ */
312
+ activationId: import_zod.z.string().optional(),
288
313
  trial: import_zod.z.boolean(),
289
314
  activationMethod: import_zod.z.nativeEnum(ActivationMethod),
290
315
  product: productSchema,
@@ -302,6 +327,10 @@ var licenseSchema = import_zod.z.object({
302
327
  validatedAt: import_zod.z.coerce.date(),
303
328
  /** Which versions of the app the license covers. Absent when it covers every version. */
304
329
  releaseAccess: releaseAccessSchema.optional(),
330
+ /** How many devices the license can be activated on. Absent when the token does not say. */
331
+ seatCount: import_zod.z.number().optional(),
332
+ /** How many of them are activated, this one included. Absent when the token does not say. */
333
+ seatsUsed: import_zod.z.number().optional(),
305
334
  properties: import_zod.z.record(import_zod.z.unknown()).nullish(),
306
335
  token: import_zod.z.string()
307
336
  });
@@ -320,29 +349,212 @@ var releaseNotCoveredProblemSchema = import_zod.z.object({
320
349
  }).nullish().catch(void 0)
321
350
  });
322
351
 
323
- // src/client.ts
324
- var defaultFetchOptions = {
325
- method: "GET",
326
- mode: "cors",
327
- headers: {
328
- "Accept": "application/json",
329
- "Content-Type": "application/json",
330
- "x-mb-client": `@moonbase.sh/licensing/${version}`
352
+ // src/inventory.ts
353
+ var NIL_GUID = "00000000-0000-0000-0000-000000000000";
354
+ function canDownload(license, info) {
355
+ if (!info.releaseCovered)
356
+ return false;
357
+ if (info.downloadsAllowed !== void 0)
358
+ return info.downloadsAllowed;
359
+ const owns = !license.trial;
360
+ const hasUser = !!license.issuedTo.id && license.issuedTo.id !== NIL_GUID;
361
+ return !(info.downloadsNeedOwnership && !owns) && !(info.downloadsNeedUser && !hasUser);
362
+ }
363
+ function filenameFromDownloadUrl(url) {
364
+ let decoded;
365
+ try {
366
+ decoded = decodeURIComponent(url.replace(/\+/g, " "));
367
+ } catch (e) {
368
+ decoded = url;
369
+ }
370
+ const at = decoded.indexOf("filename");
371
+ if (at < 0)
372
+ return "";
373
+ let rest = decoded.slice(at + "filename".length);
374
+ if (rest.startsWith("*"))
375
+ rest = rest.slice(1);
376
+ const equals = rest.indexOf("=");
377
+ if (equals < 0)
378
+ return "";
379
+ rest = rest.slice(equals + 1);
380
+ const quote = rest.indexOf("''");
381
+ if (quote >= 0 && quote < 12)
382
+ rest = rest.slice(quote + 2);
383
+ let name = "";
384
+ let quoted = false;
385
+ for (const character of rest) {
386
+ if (character === '"') {
387
+ if (quoted)
388
+ break;
389
+ quoted = true;
390
+ continue;
391
+ }
392
+ if (!quoted && (character === ";" || character === "&" || character === " "))
393
+ break;
394
+ name += character;
395
+ }
396
+ return name;
397
+ }
398
+ var releaseAccessResponseSchema = import_zod2.z.object({
399
+ coversRelease: import_zod2.z.boolean().nullish().catch(void 0),
400
+ updatesUntil: import_zod2.z.string().nullish().catch(void 0),
401
+ upToMajor: import_zod2.z.number().nullish().catch(void 0),
402
+ upToVersion: import_zod2.z.string().nullish().catch(void 0),
403
+ upgradeUrl: import_zod2.z.string().nullish().catch(void 0)
404
+ }).nullish().catch(void 0);
405
+ var releaseResponseSchema = import_zod2.z.object({
406
+ version: import_zod2.z.string().nullish().catch(void 0),
407
+ currentVersion: import_zod2.z.string().nullish().catch(void 0),
408
+ releaseDescription: import_zod2.z.string().nullish().catch(void 0),
409
+ downloads: import_zod2.z.array(import_zod2.z.object({ platform: import_zod2.z.string().nullish().catch(void 0) }).catch({})).nullish().catch(void 0),
410
+ downloadsNeedsUser: import_zod2.z.boolean().nullish().catch(void 0),
411
+ downloadsNeedsOwnership: import_zod2.z.boolean().nullish().catch(void 0),
412
+ downloadsAllowed: import_zod2.z.boolean().nullish().catch(void 0),
413
+ releaseAccess: releaseAccessResponseSchema
414
+ });
415
+ function apiDate(value) {
416
+ if (!value)
417
+ return void 0;
418
+ const date = new Date(/T[^Z+-]*$/i.test(value) ? `${value}Z` : value);
419
+ return Number.isNaN(date.getTime()) ? void 0 : date;
420
+ }
421
+ function readReleaseAccess(access) {
422
+ if (!access)
423
+ return void 0;
424
+ const releaseAccess = {};
425
+ const updatesUntil = apiDate(access.updatesUntil);
426
+ if (updatesUntil)
427
+ releaseAccess.updatesUntil = updatesUntil;
428
+ if (typeof access.upToMajor === "number")
429
+ releaseAccess.upToMajor = access.upToMajor;
430
+ if (access.upToVersion)
431
+ releaseAccess.upToVersion = access.upToVersion;
432
+ return releaseAccess.updatesUntil || releaseAccess.upToMajor !== void 0 ? releaseAccess : void 0;
433
+ }
434
+ var InventoryClient = class {
435
+ constructor(configuration) {
436
+ this.configuration = configuration;
437
+ }
438
+ /**
439
+ * The notes for a release, and whether the customer may download it. An empty
440
+ * `releaseVersion` asks for the current one.
441
+ *
442
+ * These endpoints never refuse the license itself: a token they cannot use just
443
+ * makes the request anonymous, so a private product then answers 404. Every
444
+ * failure is a {@link MoonbaseError} carrying the status.
445
+ */
446
+ async getRelease(releaseVersion, licenseToken) {
447
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
448
+ const query = new URLSearchParams({ includeManifests: "false" });
449
+ if (releaseVersion)
450
+ query.set("version", releaseVersion);
451
+ const body = releaseResponseSchema.parse(await this.get(`${this.productPath}?${query}`, licenseToken));
452
+ const access = body.releaseAccess;
453
+ return {
454
+ version: (_b = (_a = body.version) != null ? _a : body.currentVersion) != null ? _b : "",
455
+ description: (_c = body.releaseDescription) != null ? _c : "",
456
+ hasDownloads: ((_e = (_d = body.downloads) == null ? void 0 : _d.length) != null ? _e : 0) > 0,
457
+ platforms: [...new Set(((_f = body.downloads) != null ? _f : []).flatMap((download) => download.platform ? [download.platform] : []))],
458
+ downloadsNeedUser: (_g = body.downloadsNeedsUser) != null ? _g : false,
459
+ downloadsNeedOwnership: (_h = body.downloadsNeedsOwnership) != null ? _h : false,
460
+ ...typeof body.downloadsAllowed === "boolean" && { downloadsAllowed: body.downloadsAllowed },
461
+ releaseCovered: (_i = access == null ? void 0 : access.coversRelease) != null ? _i : true,
462
+ releaseAccess: readReleaseAccess(access),
463
+ upgradeUrl: (access == null ? void 0 : access.upgradeUrl) || void 0
464
+ };
465
+ }
466
+ /**
467
+ * A signed link to the latest installer for a platform. Fails with status 404
468
+ * when there is none for it, 403 when this license may not download it, and
469
+ * with a {@link ReleaseNotCoveredError}, carrying the upgrade link, when the
470
+ * customer's licenses don't cover the release.
471
+ */
472
+ async getDownloadUrl(platform, licenseToken) {
473
+ const body = await this.get(`${this.productPath}/download/${encodeURIComponent(platform)}/latest?redirect=false`, licenseToken);
474
+ const location = import_zod2.z.object({ location: import_zod2.z.string() }).safeParse(body);
475
+ if (!location.success)
476
+ throw new MoonbaseError("Could not read the download", "The download response had no location", "ApiError" /* ApiError */);
477
+ return { url: location.data.location, filename: filenameFromDownloadUrl(location.data.location) };
478
+ }
479
+ get productPath() {
480
+ return `${this.configuration.endpoint}/api/customer/inventory/products/${encodeURIComponent(this.configuration.productId)}`;
481
+ }
482
+ async get(url, licenseToken) {
483
+ const response = await (0, import_cross_fetch.default)(url, {
484
+ method: "GET",
485
+ headers: {
486
+ "Accept": "application/json",
487
+ "x-mb-client": clientHeader(this.configuration),
488
+ ...licenseToken && { Authorization: `LicenseToken ${licenseToken}` }
489
+ }
490
+ });
491
+ const text = await response.text();
492
+ let body;
493
+ try {
494
+ body = text ? JSON.parse(text) : void 0;
495
+ } catch (e) {
496
+ body = void 0;
497
+ }
498
+ if (response.status >= 400)
499
+ throw inventoryError(response, body);
500
+ if (body === void 0)
501
+ throw withStatus(new MoonbaseError("Could not read the response", "The inventory response was not JSON", "ApiError" /* ApiError */), response.status);
502
+ return body;
331
503
  }
332
504
  };
505
+ function withStatus(error, status) {
506
+ error.status = status;
507
+ return error;
508
+ }
509
+ function inventoryError(response, body) {
510
+ var _a;
511
+ const problem = problemDetailsSchema.safeParse(body);
512
+ const title = problem.success && problem.data.title || "Request not successful";
513
+ const detail = problem.success && problem.data.detail || `The API responded with a ${response.status} ${response.statusText} response`;
514
+ const errorType = problem.success ? problem.data.errorType : void 0;
515
+ if (errorType === "StoreClosed" /* StoreClosed */)
516
+ return withStatus(new MoonbaseError(title, detail, "StoreClosed" /* StoreClosed */), response.status);
517
+ if (errorType === "ReleaseNotCovered" /* ReleaseNotCovered */) {
518
+ const access = import_zod2.z.object({ releaseAccess: releaseAccessResponseSchema, upgradeUrl: import_zod2.z.string().nullish().catch(void 0) }).safeParse(body);
519
+ return withStatus(new ReleaseNotCoveredError(title, detail || "Your license doesn't cover this version", {
520
+ releaseAccess: access.success ? readReleaseAccess(access.data.releaseAccess) : void 0,
521
+ upgradeUrl: access.success && (access.data.upgradeUrl || ((_a = access.data.releaseAccess) == null ? void 0 : _a.upgradeUrl)) || void 0
522
+ }), response.status);
523
+ }
524
+ return withStatus(new MoonbaseError(title, detail, "ApiError" /* ApiError */), response.status);
525
+ }
526
+
527
+ // src/licensing.ts
528
+ var import_node_buffer2 = require("buffer");
529
+ var import_node_process4 = __toESM(require("process"), 1);
530
+
531
+ // src/client.ts
532
+ var import_cross_fetch2 = __toESM(require("cross-fetch"), 1);
533
+ function fetchOptionsFor(configuration) {
534
+ return {
535
+ method: "GET",
536
+ mode: "cors",
537
+ headers: {
538
+ "Accept": "application/json",
539
+ "Content-Type": "application/json",
540
+ "x-mb-client": clientHeader(configuration)
541
+ }
542
+ };
543
+ }
333
544
  var LicenseClient = class {
334
545
  constructor(configuration, deviceIdResolver, licenseValidator) {
335
546
  this.configuration = configuration;
336
547
  this.deviceIdResolver = deviceIdResolver;
337
548
  this.licenseValidator = licenseValidator;
549
+ this.defaultFetchOptions = fetchOptionsFor(configuration);
338
550
  }
339
551
  async requestActivation() {
340
552
  const content = {
341
553
  deviceName: await this.deviceIdResolver.resolveDeviceName(),
342
554
  deviceSignature: await this.deviceIdResolver.resolveDeviceId()
343
555
  };
344
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/activations/${this.configuration.productId}/request${this.buildQueryString()}`, {
345
- ...defaultFetchOptions,
556
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/activations/${this.configuration.productId}/request${this.buildQueryString()}`, {
557
+ ...this.defaultFetchOptions,
346
558
  method: "POST",
347
559
  body: JSON.stringify(content)
348
560
  });
@@ -362,7 +574,7 @@ var LicenseClient = class {
362
574
  }
363
575
  }
364
576
  async getRequestedActivation(request) {
365
- const response = await (0, import_cross_fetch.default)(request.request, defaultFetchOptions);
577
+ const response = await (0, import_cross_fetch2.default)(request.request, this.defaultFetchOptions);
366
578
  if (response.status === 204 || response.status === 404)
367
579
  return null;
368
580
  return await this.handleLicenseResponse(response);
@@ -372,11 +584,11 @@ var LicenseClient = class {
372
584
  deviceName: await this.deviceIdResolver.resolveDeviceName(),
373
585
  deviceSignature: await this.deviceIdResolver.resolveDeviceId()
374
586
  };
375
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/trials/${this.configuration.productId}/request${this.buildQueryString()}`, {
376
- ...defaultFetchOptions,
587
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/trials/${this.configuration.productId}/request${this.buildQueryString()}`, {
588
+ ...this.defaultFetchOptions,
377
589
  method: "POST",
378
590
  headers: {
379
- ...defaultFetchOptions.headers,
591
+ ...this.defaultFetchOptions.headers,
380
592
  "Content-Type": "application/json"
381
593
  },
382
594
  body: JSON.stringify(content)
@@ -384,11 +596,11 @@ var LicenseClient = class {
384
596
  return await this.handleLicenseResponse(response);
385
597
  }
386
598
  async activateSubProduct(license, subProductId) {
387
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/sub-products/${encodeURIComponent(subProductId)}/activate${this.buildQueryString()}`, {
388
- ...defaultFetchOptions,
599
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/sub-products/${encodeURIComponent(subProductId)}/activate${this.buildQueryString()}`, {
600
+ ...this.defaultFetchOptions,
389
601
  method: "POST",
390
602
  headers: {
391
- ...defaultFetchOptions.headers,
603
+ ...this.defaultFetchOptions.headers,
392
604
  "Content-Type": "text/plain"
393
605
  },
394
606
  body: license.token
@@ -396,11 +608,11 @@ var LicenseClient = class {
396
608
  return await this.handleLicenseResponse(response);
397
609
  }
398
610
  async requestSubProductTrial(license, subProductId) {
399
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/sub-products/${encodeURIComponent(subProductId)}/trial${this.buildQueryString()}`, {
400
- ...defaultFetchOptions,
611
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/sub-products/${encodeURIComponent(subProductId)}/trial${this.buildQueryString()}`, {
612
+ ...this.defaultFetchOptions,
401
613
  method: "POST",
402
614
  headers: {
403
- ...defaultFetchOptions.headers,
615
+ ...this.defaultFetchOptions.headers,
404
616
  "Content-Type": "text/plain"
405
617
  },
406
618
  body: license.token
@@ -408,11 +620,11 @@ var LicenseClient = class {
408
620
  return await this.handleLicenseResponse(response);
409
621
  }
410
622
  async listSubProducts(license) {
411
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/sub-products`, {
412
- ...defaultFetchOptions,
623
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/sub-products`, {
624
+ ...this.defaultFetchOptions,
413
625
  method: "POST",
414
626
  headers: {
415
- ...defaultFetchOptions.headers,
627
+ ...this.defaultFetchOptions.headers,
416
628
  "Content-Type": "text/plain"
417
629
  },
418
630
  body: license.token
@@ -433,11 +645,11 @@ var LicenseClient = class {
433
645
  }
434
646
  }
435
647
  async validateLicense(license) {
436
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/validate${this.buildQueryString()}`, {
437
- ...defaultFetchOptions,
648
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/validate${this.buildQueryString()}`, {
649
+ ...this.defaultFetchOptions,
438
650
  method: "POST",
439
651
  headers: {
440
- ...defaultFetchOptions.headers,
652
+ ...this.defaultFetchOptions.headers,
441
653
  "Content-Type": "text/plain"
442
654
  },
443
655
  body: license.token
@@ -452,11 +664,11 @@ var LicenseClient = class {
452
664
  return await this.validateLicense(license);
453
665
  }
454
666
  async revokeLicense(license) {
455
- const response = await (0, import_cross_fetch.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/revoke?format=JWT`, {
456
- ...defaultFetchOptions,
667
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/licenses/${this.configuration.productId}/revoke?format=JWT`, {
668
+ ...this.defaultFetchOptions,
457
669
  method: "POST",
458
670
  headers: {
459
- ...defaultFetchOptions.headers,
671
+ ...this.defaultFetchOptions.headers,
460
672
  "Content-Type": "text/plain"
461
673
  },
462
674
  body: license.token
@@ -500,6 +712,11 @@ var licenseErrorTypes = /* @__PURE__ */ new Set([
500
712
  "ReleaseNotCovered" /* ReleaseNotCovered */
501
713
  ]);
502
714
  async function errorFromResponse(response, licenseValidator) {
715
+ const error = await readErrorFromResponse(response, licenseValidator);
716
+ error.status = response.status;
717
+ return error;
718
+ }
719
+ async function readErrorFromResponse(response, licenseValidator) {
503
720
  const fallback = new MoonbaseError(
504
721
  "Request not successful",
505
722
  `The API responded with a ${response.status} ${response.statusText} response`,
@@ -743,9 +960,9 @@ function commandOutput(command) {
743
960
  return "";
744
961
  }
745
962
  }
746
- function readSysFile(path2) {
963
+ function readSysFile(path5) {
747
964
  try {
748
- return import_node_fs.default.readFileSync(path2, "utf8");
965
+ return import_node_fs.default.readFileSync(path5, "utf8");
749
966
  } catch (e) {
750
967
  return "";
751
968
  }
@@ -1016,6 +1233,7 @@ var LegacyDeviceIdResolver = class {
1016
1233
  var import_node_fs2 = __toESM(require("fs"), 1);
1017
1234
  var import_promises = __toESM(require("fs/promises"), 1);
1018
1235
  var import_node_path = __toESM(require("path"), 1);
1236
+ var import_node_process3 = __toESM(require("process"), 1);
1019
1237
  var InMemoryLicenseStore = class {
1020
1238
  async loadLocalLicense() {
1021
1239
  var _a;
@@ -1043,23 +1261,50 @@ var FileLicenseStore = class {
1043
1261
  throw new MoonbaseError("File error", "Could not load local license", "LicenseInvalid" /* LicenseInvalid */, err);
1044
1262
  }
1045
1263
  }
1264
+ /**
1265
+ * Writes the license to a file beside the license and moves it into place, so
1266
+ * another process reading the license never sees half of it. Creates the
1267
+ * directory when it does not exist yet.
1268
+ */
1046
1269
  async storeLocalLicense(license) {
1047
- await import_promises.default.writeFile(this.path, JSON.stringify(license), { encoding: "utf-8" });
1270
+ await import_promises.default.mkdir(import_node_path.default.dirname(this.path), { recursive: true });
1271
+ const temporary = `${this.path}.${import_node_process3.default.pid}.${Math.random().toString(36).slice(2)}.tmp`;
1272
+ await import_promises.default.writeFile(temporary, JSON.stringify(license), { encoding: "utf-8" });
1273
+ try {
1274
+ await replaceFile(temporary, this.path);
1275
+ } catch (err) {
1276
+ await import_promises.default.rm(temporary, { force: true });
1277
+ throw err;
1278
+ }
1048
1279
  }
1049
1280
  async deleteLocalLicense() {
1050
1281
  if (!import_node_fs2.default.existsSync(this.path))
1051
1282
  return;
1052
- await import_promises.default.rm(this.path);
1283
+ await import_promises.default.rm(this.path, { force: true });
1053
1284
  }
1285
+ /** Where the license is kept. */
1054
1286
  get path() {
1055
1287
  var _a, _b, _c, _d;
1056
1288
  return import_node_path.default.resolve((_b = (_a = this.options) == null ? void 0 : _a.dir) != null ? _b : import_node_path.default.resolve(), (_d = (_c = this.options) == null ? void 0 : _c.licenseFileName) != null ? _d : "license.mb");
1057
1289
  }
1058
1290
  };
1291
+ async function replaceFile(from, to) {
1292
+ for (let attempt = 0; ; attempt++) {
1293
+ try {
1294
+ await import_promises.default.rename(from, to);
1295
+ return;
1296
+ } catch (err) {
1297
+ const code = err.code;
1298
+ if (attempt >= 10 || code !== "EPERM" && code !== "EACCES" && code !== "EBUSY")
1299
+ throw err;
1300
+ await new Promise((resolve) => setTimeout(resolve, 20 * (attempt + 1)));
1301
+ }
1302
+ }
1303
+ }
1059
1304
 
1060
1305
  // src/validator.ts
1061
1306
  var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1);
1062
- var import_zod2 = require("zod");
1307
+ var import_zod3 = require("zod");
1063
1308
 
1064
1309
  // src/releaseAccess.ts
1065
1310
  var maxVersionPart = 9999999;
@@ -1109,34 +1354,37 @@ function coversVersion(license, version2, now = /* @__PURE__ */ new Date()) {
1109
1354
  }
1110
1355
 
1111
1356
  // src/validator.ts
1112
- var integerClaimSchema = import_zod2.z.union([
1113
- import_zod2.z.number().int(),
1114
- import_zod2.z.string().regex(/^-?\d+$/).transform(Number)
1357
+ var integerClaimSchema = import_zod3.z.union([
1358
+ import_zod3.z.number().int(),
1359
+ import_zod3.z.string().regex(/^-?\d+$/).transform(Number)
1115
1360
  ]).nullish().catch(void 0);
1116
- var licenseClaimsSchema = import_zod2.z.object({
1117
- ["l:id" /* LicenseId */]: import_zod2.z.string(),
1118
- ["trial" /* Trial */]: import_zod2.z.string().or(import_zod2.z.boolean()).transform((v) => v === true || v === "true").pipe(import_zod2.z.boolean()),
1119
- ["method" /* ActivationMethod */]: import_zod2.z.nativeEnum(ActivationMethod),
1120
- ["sig" /* ComputerSignature */]: import_zod2.z.string(),
1121
- ["iat" /* IssuedAt */]: import_zod2.z.number().transform((v) => new Date(v * 1e3)).pipe(import_zod2.z.date()),
1122
- ["exp" /* ExpiresAt */]: import_zod2.z.number().nullish().transform((v) => v ? new Date(v * 1e3) : void 0).pipe(import_zod2.z.date().nullish()),
1123
- ["validated" /* ValidatedAt */]: import_zod2.z.number().transform((v) => new Date(v * 1e3)).pipe(import_zod2.z.date()),
1124
- ["p:id" /* ProductId */]: import_zod2.z.string(),
1125
- ["p:name" /* ProductName */]: import_zod2.z.string(),
1126
- ["p:rel" /* ProductReleaseVersion */]: import_zod2.z.string().nullish(),
1127
- ["sp:owned" /* OwnedSubProducts */]: import_zod2.z.string().nullish().transform((v) => v ? v.split(",") : []),
1128
- ["sp" /* SubProducts */]: import_zod2.z.array(import_zod2.z.unknown()).nullish().transform(readSubProducts),
1129
- ["s:id" /* SubscriptionId */]: import_zod2.z.string().nullish(),
1130
- ["u:id" /* UserId */]: import_zod2.z.string(),
1131
- ["u:name" /* UserName */]: import_zod2.z.string(),
1132
- ["u:email" /* UserEmail */]: import_zod2.z.string(),
1133
- ["p:properties" /* ProductProperties */]: import_zod2.z.record(import_zod2.z.unknown()).nullish(),
1134
- ["u:properties" /* UserProperties */]: import_zod2.z.record(import_zod2.z.unknown()).nullish(),
1135
- ["l:properties" /* LicenseProperties */]: import_zod2.z.record(import_zod2.z.unknown()).nullish(),
1136
- ["t:properties" /* TrialProperties */]: import_zod2.z.record(import_zod2.z.unknown()).nullish(),
1361
+ var licenseClaimsSchema = import_zod3.z.object({
1362
+ ["id" /* ActivationId */]: import_zod3.z.string().nullish().catch(void 0),
1363
+ ["l:id" /* LicenseId */]: import_zod3.z.string(),
1364
+ ["trial" /* Trial */]: import_zod3.z.string().or(import_zod3.z.boolean()).transform((v) => v === true || v === "true").pipe(import_zod3.z.boolean()),
1365
+ ["method" /* ActivationMethod */]: import_zod3.z.nativeEnum(ActivationMethod),
1366
+ ["sig" /* ComputerSignature */]: import_zod3.z.string(),
1367
+ ["iat" /* IssuedAt */]: import_zod3.z.number().transform((v) => new Date(v * 1e3)).pipe(import_zod3.z.date()),
1368
+ ["exp" /* ExpiresAt */]: import_zod3.z.number().nullish().transform((v) => v ? new Date(v * 1e3) : void 0).pipe(import_zod3.z.date().nullish()),
1369
+ ["validated" /* ValidatedAt */]: import_zod3.z.number().transform((v) => new Date(v * 1e3)).pipe(import_zod3.z.date()),
1370
+ ["p:id" /* ProductId */]: import_zod3.z.string(),
1371
+ ["p:name" /* ProductName */]: import_zod3.z.string(),
1372
+ ["p:rel" /* ProductReleaseVersion */]: import_zod3.z.string().nullish(),
1373
+ ["sp:owned" /* OwnedSubProducts */]: import_zod3.z.string().nullish().transform((v) => v ? v.split(",") : []),
1374
+ ["sp" /* SubProducts */]: import_zod3.z.array(import_zod3.z.unknown()).nullish().transform(readSubProducts),
1375
+ ["s:id" /* SubscriptionId */]: import_zod3.z.string().nullish(),
1376
+ ["u:id" /* UserId */]: import_zod3.z.string(),
1377
+ ["u:name" /* UserName */]: import_zod3.z.string(),
1378
+ ["u:email" /* UserEmail */]: import_zod3.z.string(),
1379
+ ["p:properties" /* ProductProperties */]: import_zod3.z.record(import_zod3.z.unknown()).nullish(),
1380
+ ["u:properties" /* UserProperties */]: import_zod3.z.record(import_zod3.z.unknown()).nullish(),
1381
+ ["l:properties" /* LicenseProperties */]: import_zod3.z.record(import_zod3.z.unknown()).nullish(),
1382
+ ["t:properties" /* TrialProperties */]: import_zod3.z.record(import_zod3.z.unknown()).nullish(),
1137
1383
  ["l:rel:until" /* ReleaseAccessUpdatesUntil */]: integerClaimSchema,
1138
1384
  ["l:rel:major" /* ReleaseAccessUpToMajor */]: integerClaimSchema,
1139
- ["l:rel:upto" /* ReleaseAccessUpToVersion */]: import_zod2.z.string().nullish().catch(void 0)
1385
+ ["l:rel:upto" /* ReleaseAccessUpToVersion */]: import_zod3.z.string().nullish().catch(void 0),
1386
+ ["p:seats:total" /* SeatsTotal */]: integerClaimSchema,
1387
+ ["p:seats:used" /* SeatsUsed */]: integerClaimSchema
1140
1388
  });
1141
1389
  var LicenseValidator = class {
1142
1390
  constructor(configuration, deviceIdResolver) {
@@ -1146,7 +1394,7 @@ var LicenseValidator = class {
1146
1394
  async validateLicense(token, options) {
1147
1395
  var _a, _b;
1148
1396
  const [license, claims] = await this.parseLicenseToken(token);
1149
- if (license.expiresAt && license.expiresAt < /* @__PURE__ */ new Date()) {
1397
+ if (!(options == null ? void 0 : options.allowExpired) && license.expiresAt && license.expiresAt < /* @__PURE__ */ new Date()) {
1150
1398
  throw new MoonbaseError(
1151
1399
  "License expired",
1152
1400
  "This license has expired",
@@ -1204,9 +1452,13 @@ var LicenseValidator = class {
1204
1452
  }
1205
1453
  try {
1206
1454
  const claims = licenseClaimsSchema.parse(decoded);
1207
- const releaseAccess = readReleaseAccess(claims);
1455
+ const releaseAccess = readReleaseAccess2(claims);
1456
+ const activationId = claims["id" /* ActivationId */];
1457
+ const seatCount = claims["p:seats:total" /* SeatsTotal */];
1458
+ const seatsUsed = claims["p:seats:used" /* SeatsUsed */];
1208
1459
  resolve([{
1209
1460
  id: claims["l:id" /* LicenseId */],
1461
+ ...activationId && { activationId },
1210
1462
  trial: claims["trial" /* Trial */],
1211
1463
  activationMethod: claims["method" /* ActivationMethod */],
1212
1464
  product: {
@@ -1228,6 +1480,8 @@ var LicenseValidator = class {
1228
1480
  issuedAt: claims["iat" /* IssuedAt */],
1229
1481
  validatedAt: claims["validated" /* ValidatedAt */],
1230
1482
  ...releaseAccess && { releaseAccess },
1483
+ ...typeof seatCount === "number" && { seatCount },
1484
+ ...typeof seatsUsed === "number" && { seatsUsed },
1231
1485
  properties: (_e = claims["trial" /* Trial */] ? claims["t:properties" /* TrialProperties */] : claims["l:properties" /* LicenseProperties */]) != null ? _e : void 0,
1232
1486
  token
1233
1487
  }, claims]);
@@ -1244,16 +1498,16 @@ var LicenseValidator = class {
1244
1498
  });
1245
1499
  }
1246
1500
  };
1247
- var subProductClaimSchema = import_zod2.z.object({
1248
- id: import_zod2.z.string(),
1249
- active: import_zod2.z.boolean().catch(false),
1250
- trial: import_zod2.z.boolean().catch(false),
1251
- revoked: import_zod2.z.boolean().catch(false),
1252
- exp: import_zod2.z.number().nullish().catch(void 0),
1253
- seats: import_zod2.z.object({
1254
- total: import_zod2.z.number(),
1255
- used: import_zod2.z.number(),
1256
- remaining: import_zod2.z.number()
1501
+ var subProductClaimSchema = import_zod3.z.object({
1502
+ id: import_zod3.z.string(),
1503
+ active: import_zod3.z.boolean().catch(false),
1504
+ trial: import_zod3.z.boolean().catch(false),
1505
+ revoked: import_zod3.z.boolean().catch(false),
1506
+ exp: import_zod3.z.number().nullish().catch(void 0),
1507
+ seats: import_zod3.z.object({
1508
+ total: import_zod3.z.number(),
1509
+ used: import_zod3.z.number(),
1510
+ remaining: import_zod3.z.number()
1257
1511
  }).nullish().catch(void 0)
1258
1512
  });
1259
1513
  function readSubProducts(entries) {
@@ -1272,7 +1526,7 @@ function readSubProducts(entries) {
1272
1526
  }];
1273
1527
  });
1274
1528
  }
1275
- function readReleaseAccess(claims) {
1529
+ function readReleaseAccess2(claims) {
1276
1530
  var _a, _b;
1277
1531
  const updatesUntil = (_a = claims["l:rel:until" /* ReleaseAccessUpdatesUntil */]) != null ? _a : void 0;
1278
1532
  const upToMajor = (_b = claims["l:rel:major" /* ReleaseAccessUpToMajor */]) != null ? _b : void 0;
@@ -1334,20 +1588,11 @@ function describeSourceDifference(expected, bound) {
1334
1588
  return "The binding was created from hardware identity, while this SDK has fallen back to the host name \u2014 check why hardware identity cannot be read here rather than re-activating, which would rebind the device to the weaker id.";
1335
1589
  }
1336
1590
 
1337
- // src/subProducts.ts
1338
- function hasSubProduct(license, subProductId) {
1339
- var _a;
1340
- const parentPrefix = `${license.product.id}.`;
1341
- const id = subProductId.startsWith(parentPrefix) ? subProductId.slice(parentPrefix.length) : subProductId;
1342
- const now = /* @__PURE__ */ new Date();
1343
- return ((_a = license.subProducts) != null ? _a : []).some((subProduct) => subProduct.id === id && subProduct.active && (!subProduct.expiresAt || subProduct.expiresAt > now));
1344
- }
1345
-
1346
- // src/index.ts
1591
+ // src/licensing.ts
1347
1592
  function detectPlatform() {
1348
- if (typeof import_node_process3.default === "undefined")
1593
+ if (typeof import_node_process4.default === "undefined")
1349
1594
  return void 0;
1350
- switch (import_node_process3.default.platform) {
1595
+ switch (import_node_process4.default.platform) {
1351
1596
  case "darwin":
1352
1597
  return "Mac";
1353
1598
  case "win32":
@@ -1370,6 +1615,7 @@ var MoonbaseLicensing = class {
1370
1615
  this.deviceIdResolver = (_b = configuration.deviceIdResolver) != null ? _b : new MoonbaseDeviceIdResolver();
1371
1616
  this.validator = new LicenseValidator(this.configuration, this.deviceIdResolver);
1372
1617
  this.client = new LicenseClient(this.configuration, this.deviceIdResolver, this.validator);
1618
+ this.inventory = new InventoryClient(this.configuration);
1373
1619
  }
1374
1620
  async generateDeviceToken() {
1375
1621
  const token = {
@@ -1385,8 +1631,1742 @@ var MoonbaseLicensing = class {
1385
1631
  return await this.client.validateRawLicense(license);
1386
1632
  }
1387
1633
  };
1634
+
1635
+ // src/subProducts.ts
1636
+ function hasSubProduct(license, subProductId) {
1637
+ var _a;
1638
+ const parentPrefix = `${license.product.id}.`;
1639
+ const id = subProductId.startsWith(parentPrefix) ? subProductId.slice(parentPrefix.length) : subProductId;
1640
+ const now = /* @__PURE__ */ new Date();
1641
+ return ((_a = license.subProducts) != null ? _a : []).some((subProduct) => subProduct.id === id && subProduct.active && (!subProduct.expiresAt || subProduct.expiresAt > now));
1642
+ }
1643
+
1644
+ // src/version.ts
1645
+ var NUMBER = /^\d+$/;
1646
+ function parseNumber(text) {
1647
+ if (text === void 0)
1648
+ return 0;
1649
+ return NUMBER.test(text) ? Number(text) : null;
1650
+ }
1651
+ function parseSemver(input) {
1652
+ let text = input.trim().replace(/^v/i, "");
1653
+ if (!text)
1654
+ return null;
1655
+ text = text.split("+")[0];
1656
+ const dash = text.indexOf("-");
1657
+ const core = dash < 0 ? text : text.slice(0, dash);
1658
+ const prerelease = dash < 0 ? "" : text.slice(dash + 1);
1659
+ const parts = core.split(".");
1660
+ if (parts.length > 3 || parts[0] === "")
1661
+ return null;
1662
+ const [major, minor, patch] = [parseNumber(parts[0]), parseNumber(parts[1]), parseNumber(parts[2])];
1663
+ if (major === null || minor === null || patch === null)
1664
+ return null;
1665
+ return { major, minor, patch, prerelease: prerelease ? prerelease.split(".") : [] };
1666
+ }
1667
+ function compareSemver(left, right) {
1668
+ for (const key of ["major", "minor", "patch"]) {
1669
+ if (left[key] !== right[key])
1670
+ return left[key] < right[key] ? -1 : 1;
1671
+ }
1672
+ if (!left.prerelease.length || !right.prerelease.length)
1673
+ return right.prerelease.length - left.prerelease.length;
1674
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
1675
+ for (let index = 0; index < length; index++) {
1676
+ const a = left.prerelease[index];
1677
+ const b = right.prerelease[index];
1678
+ if (a === void 0)
1679
+ return -1;
1680
+ if (b === void 0)
1681
+ return 1;
1682
+ if (a === b)
1683
+ continue;
1684
+ const numeric = [NUMBER.test(a), NUMBER.test(b)];
1685
+ if (numeric[0] && numeric[1])
1686
+ return Number(a) < Number(b) ? -1 : 1;
1687
+ if (numeric[0] !== numeric[1])
1688
+ return numeric[0] ? -1 : 1;
1689
+ return a < b ? -1 : 1;
1690
+ }
1691
+ return 0;
1692
+ }
1693
+ function isNewerVersion(current, latest) {
1694
+ const parsedCurrent = parseSemver(current);
1695
+ const parsedLatest = parseSemver(latest);
1696
+ return !!parsedCurrent && !!parsedLatest && compareSemver(parsedLatest, parsedCurrent) > 0;
1697
+ }
1698
+
1699
+ // src/activation/fileLock.ts
1700
+ var import_promises2 = __toESM(require("fs/promises"), 1);
1701
+ var import_node_path2 = __toESM(require("path"), 1);
1702
+ var RETRY_INTERVAL = 50;
1703
+ var LockUnavailableError = class extends Error {
1704
+ constructor(message) {
1705
+ super(message);
1706
+ this.name = "LockUnavailableError";
1707
+ }
1708
+ };
1709
+ async function withFileLock(lockPath, action, options = {}) {
1710
+ var _a, _b, _c, _d;
1711
+ const staleAfter = (_a = options.staleAfter) != null ? _a : 3e4;
1712
+ const deadline = Date.now() + ((_b = options.timeout) != null ? _b : 6e4);
1713
+ for (; ; ) {
1714
+ if ((_c = options.signal) == null ? void 0 : _c.aborted)
1715
+ throw new LockUnavailableError("Stopped waiting for the license lock");
1716
+ try {
1717
+ await import_promises2.default.mkdir(lockPath);
1718
+ break;
1719
+ } catch (err) {
1720
+ const code = err.code;
1721
+ if (code === "ENOENT") {
1722
+ await import_promises2.default.mkdir(import_node_path2.default.dirname(lockPath), { recursive: true });
1723
+ continue;
1724
+ }
1725
+ if (code !== "EEXIST")
1726
+ throw new LockUnavailableError(`Couldn't take the license lock: ${err.message}`);
1727
+ }
1728
+ try {
1729
+ const { mtimeMs } = await import_promises2.default.stat(lockPath);
1730
+ if (Date.now() - mtimeMs > staleAfter) {
1731
+ await import_promises2.default.rm(lockPath, { recursive: true, force: true });
1732
+ continue;
1733
+ }
1734
+ } catch (e) {
1735
+ continue;
1736
+ }
1737
+ if (Date.now() > deadline)
1738
+ throw new LockUnavailableError("Timed out waiting for the license lock");
1739
+ await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL));
1740
+ }
1741
+ const touch = setInterval(() => {
1742
+ const now = /* @__PURE__ */ new Date();
1743
+ import_promises2.default.utimes(lockPath, now, now).catch(() => {
1744
+ });
1745
+ }, staleAfter / 3);
1746
+ (_d = touch.unref) == null ? void 0 : _d.call(touch);
1747
+ try {
1748
+ return await action();
1749
+ } finally {
1750
+ clearInterval(touch);
1751
+ await import_promises2.default.rm(lockPath, { recursive: true, force: true }).catch(() => {
1752
+ });
1753
+ }
1754
+ }
1755
+
1756
+ // src/activation/files.ts
1757
+ var import_promises3 = __toESM(require("fs/promises"), 1);
1758
+ var import_node_path3 = __toESM(require("path"), 1);
1759
+ var import_node_process5 = __toESM(require("process"), 1);
1760
+ function fileSafe(name) {
1761
+ const cleaned = name.replace(/[\u0000-\u001F\u007F\\/:*?"<>|]/g, "-").trim().replace(/^\.+|\.+$/g, "");
1762
+ return cleaned || "license";
1763
+ }
1764
+ async function reserveFile(dir, name) {
1765
+ const dot = name.lastIndexOf(".");
1766
+ const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];
1767
+ for (let n = 1; ; n++) {
1768
+ const candidate = import_node_path3.default.join(dir, n === 1 ? name : `${stem} (${n})${extension}`);
1769
+ try {
1770
+ await (await import_promises3.default.open(candidate, "wx")).close();
1771
+ return candidate;
1772
+ } catch (err) {
1773
+ if (err.code !== "EEXIST")
1774
+ throw err;
1775
+ }
1776
+ }
1777
+ }
1778
+ function stateFile(licenseFile) {
1779
+ return `${licenseFile}.state.json`;
1780
+ }
1781
+ async function readState(licenseFile) {
1782
+ try {
1783
+ const state = JSON.parse(await import_promises3.default.readFile(stateFile(licenseFile), "utf8"));
1784
+ return state && typeof state === "object" && !Array.isArray(state) ? state : {};
1785
+ } catch (e) {
1786
+ return {};
1787
+ }
1788
+ }
1789
+ async function isUpdateSkipped(licenseFile, version2) {
1790
+ const skipped = (await readState(licenseFile)).ignoredUpdates;
1791
+ return Array.isArray(skipped) && skipped.includes(version2);
1792
+ }
1793
+ async function skipUpdate(licenseFile, version2) {
1794
+ const state = await readState(licenseFile);
1795
+ const skipped = Array.isArray(state.ignoredUpdates) ? state.ignoredUpdates : [];
1796
+ if (!skipped.includes(version2))
1797
+ skipped.push(version2);
1798
+ state.ignoredUpdates = skipped;
1799
+ await import_promises3.default.mkdir(import_node_path3.default.dirname(stateFile(licenseFile)), { recursive: true });
1800
+ await import_promises3.default.writeFile(stateFile(licenseFile), JSON.stringify(state, null, 2));
1801
+ }
1802
+ async function downloadFile(url, target, onProgress, fetcher = fetch) {
1803
+ const response = await fetcher(url);
1804
+ if (!response.ok || !response.body)
1805
+ throw new Error(`The server answered ${response.status}`);
1806
+ const total = Number(response.headers.get("content-length")) || 0;
1807
+ const partial = `${target}.${import_node_process5.default.pid}-${Math.random().toString(36).slice(2)}.part`;
1808
+ const file = await import_promises3.default.open(partial, "w");
1809
+ let received = 0;
1810
+ let lastReport = 0;
1811
+ try {
1812
+ const reader = response.body.getReader();
1813
+ for (; ; ) {
1814
+ const { done, value } = await reader.read();
1815
+ if (done)
1816
+ break;
1817
+ await file.write(value);
1818
+ received += value.byteLength;
1819
+ if (Date.now() - lastReport > 120) {
1820
+ lastReport = Date.now();
1821
+ onProgress(total ? Math.min(1, received / total) : null);
1822
+ }
1823
+ }
1824
+ await file.close();
1825
+ await import_promises3.default.rename(partial, target);
1826
+ } catch (err) {
1827
+ await file.close().catch(() => {
1828
+ });
1829
+ await import_promises3.default.rm(partial, { force: true });
1830
+ throw err;
1831
+ }
1832
+ }
1833
+
1834
+ // src/activation/models.ts
1835
+ var ActivationError = class extends Error {
1836
+ constructor(kind, message) {
1837
+ super(message);
1838
+ this.kind = kind;
1839
+ this.name = "ActivationError";
1840
+ }
1841
+ };
1842
+
1843
+ // src/activation/controller.ts
1844
+ var DAY = 864e5;
1845
+ var LICENSE_CHANGED = "Your license changed while this was in progress.";
1846
+ function noop() {
1847
+ }
1848
+ function emptyAddOns() {
1849
+ return { phase: "idle", currency: null, addOns: [], error: null, busyId: null, actionError: null };
1850
+ }
1851
+ function sleep(ms) {
1852
+ return new Promise((resolve) => {
1853
+ var _a;
1854
+ const timer = setTimeout(resolve, ms);
1855
+ (_a = timer.unref) == null ? void 0 : _a.call(timer);
1856
+ });
1857
+ }
1858
+ function isLicenseInvalid(error) {
1859
+ if (!(error instanceof MoonbaseError))
1860
+ return false;
1861
+ return error.type === "LicenseInvalid" /* LicenseInvalid */ || error.type === "LicenseRevoked" /* LicenseRevoked */ || error.type === "LicenseActivationRevoked" /* LicenseActivationRevoked */ || error.type === "LicenseDeviceMismatch" /* LicenseDeviceMismatch */;
1862
+ }
1863
+ function isLicenseRejection(error) {
1864
+ return isLicenseInvalid(error) || error instanceof MoonbaseError && (error.type === "LicenseExpired" /* LicenseExpired */ || error.type === "NoEligibleLicense" /* NoEligibleLicense */);
1865
+ }
1866
+ function isType(error, type) {
1867
+ return error instanceof MoonbaseError && error.type === type;
1868
+ }
1869
+ function isBusyStatus(error) {
1870
+ const status = error instanceof MoonbaseError ? error.status : void 0;
1871
+ return status === 408 || status === 429 || status !== void 0 && status >= 500;
1872
+ }
1873
+ function isUnanswered(error) {
1874
+ return !(error instanceof MoonbaseError) || error.type === "ApiError" /* ApiError */ || error.type === void 0;
1875
+ }
1876
+ function endsActivation(error) {
1877
+ return isLicenseRejection(error) || isType(error, "StoreClosed" /* StoreClosed */) || isType(error, "DeviceIdentityUnavailable" /* DeviceIdentityUnavailable */) || isType(error, "ApiError" /* ApiError */) && (error.status === 400 || error.status === 410);
1878
+ }
1879
+ function errorText(error) {
1880
+ return error instanceof Error ? error.message : String(error);
1881
+ }
1882
+ function failureKind(error) {
1883
+ var _a;
1884
+ return error instanceof MoonbaseError ? (_a = error.type) != null ? _a : null : null;
1885
+ }
1886
+ function failure(activity, error) {
1887
+ let message;
1888
+ if (isType(error, "DeviceIdentityUnavailable" /* DeviceIdentityUnavailable */))
1889
+ message = "This computer can't be identified, so it can't be activated. Contact the developer for help.";
1890
+ else if (isType(error, "StoreClosed" /* StoreClosed */))
1891
+ message = activity === "deactivation" ? "This store has closed, so this computer can't be deactivated." : "This store has closed, so activation isn't available.";
1892
+ else if (activity === "startActivation" && isUnanswered(error))
1893
+ message = isBusyStatus(error) ? "Moonbase couldn't start activation right now. Try again in a minute." : "Couldn't reach Moonbase to start activation. Check your internet connection and try again.";
1894
+ else if (activity === "startActivation" && isLicenseRejection(error))
1895
+ message = "Activation isn't available for this product right now. If this keeps happening, contact the developer.";
1896
+ else if (activity === "activation" && isType(error, "ApiError" /* ApiError */))
1897
+ message = "This activation expired or was cancelled. Activate again to continue.";
1898
+ else if (activity === "activation" && isType(error, "LicenseExpired" /* LicenseExpired */))
1899
+ message = "This license has expired, so it can't be activated.";
1900
+ else if (activity === "activation" && isLicenseRejection(error))
1901
+ message = "Activation was rejected. If this keeps happening, contact the developer.";
1902
+ else if (activity === "deactivation" && isUnanswered(error))
1903
+ message = isBusyStatus(error) ? "Moonbase couldn't deactivate right now. Try again in a minute." : "Couldn't reach Moonbase to deactivate. Try again when you're online.";
1904
+ else if (activity === "offlineActivation")
1905
+ message = isType(error, "ReleaseNotCovered" /* ReleaseNotCovered */) ? "That license doesn't cover this version." : "That license file isn't valid for this device.";
1906
+ else if (activity === "startActivation")
1907
+ message = `Activation couldn't start: ${errorText(error)}`;
1908
+ else if (activity === "activation")
1909
+ message = `Activation failed: ${errorText(error)}`;
1910
+ else
1911
+ message = `Couldn't deactivate: ${errorText(error)}`;
1912
+ return { message, detail: errorText(error), kind: failureKind(error) };
1913
+ }
1914
+ function addOnFailure(error, lead, notFound) {
1915
+ const status = error instanceof MoonbaseError ? error.status : void 0;
1916
+ if (isUnanswered(error) && status === 404)
1917
+ return notFound;
1918
+ if (isUnanswered(error) && isBusyStatus(error))
1919
+ return "Moonbase couldn't do that right now. Try again in a minute.";
1920
+ if (isUnanswered(error) && (status === void 0 || status !== 400))
1921
+ return "Couldn't reach Moonbase. Check your internet connection and try again.";
1922
+ if (isType(error, "StoreClosed" /* StoreClosed */))
1923
+ return "This store has closed, so add-ons aren't available.";
1924
+ if (isType(error, "DeviceIdentityUnavailable" /* DeviceIdentityUnavailable */))
1925
+ return "This computer can't be identified. Contact the developer for help.";
1926
+ if (isLicenseRejection(error) || status === 400)
1927
+ return `${lead}. If this keeps happening, contact the developer.`;
1928
+ return `${lead}: ${errorText(error)}`;
1929
+ }
1930
+ function daysUntil(when) {
1931
+ return Math.max(0, Math.ceil((when.getTime() - Date.now()) / DAY));
1932
+ }
1933
+ function age(time) {
1934
+ return Math.max(0, Date.now() - time.getTime());
1935
+ }
1936
+ function activationIdOf(license) {
1937
+ var _a, _b;
1938
+ return (_b = (_a = license.activationId) != null ? _a : tokenClaim(license.token, "id")) != null ? _b : license.id;
1939
+ }
1940
+ function activationIdOfToken(token) {
1941
+ var _a;
1942
+ return (_a = tokenClaim(token, "id")) != null ? _a : tokenClaim(token, "l:id");
1943
+ }
1944
+ function tokenClaim(token, claim) {
1945
+ const payload = import_jsonwebtoken2.default.decode(token);
1946
+ const value = payload && typeof payload === "object" ? payload[claim] : void 0;
1947
+ return typeof value === "string" ? value : null;
1948
+ }
1949
+ function sameActivation(a, b) {
1950
+ return activationIdOf(a) === activationIdOf(b);
1951
+ }
1952
+ function activeSubProductsOf(license) {
1953
+ var _a;
1954
+ const active = [];
1955
+ for (const entry of (_a = license.subProducts) != null ? _a : []) {
1956
+ if (hasSubProduct(license, entry.id) && !active.includes(entry.id))
1957
+ active.push(entry.id);
1958
+ }
1959
+ return active;
1960
+ }
1961
+ function findSubProduct(license, subProductId) {
1962
+ var _a;
1963
+ const prefix = `${license.product.id}.`;
1964
+ const id = subProductId.startsWith(prefix) ? subProductId.slice(prefix.length) : subProductId;
1965
+ return ((_a = license.subProducts) != null ? _a : []).find((entry) => entry.id === id);
1966
+ }
1967
+ function toView(license) {
1968
+ const { token: _token, ...rest } = license;
1969
+ return { ...rest, daysRemaining: license.expiresAt ? daysUntil(license.expiresAt) : null };
1970
+ }
1971
+ function notCoveredFrom(refusal, fallback) {
1972
+ var _a, _b, _c, _d, _e;
1973
+ const license = (_a = refusal.license) != null ? _a : fallback;
1974
+ return {
1975
+ license,
1976
+ appVersion: (_b = refusal.appVersion) != null ? _b : "",
1977
+ releaseAccess: (_d = (_c = refusal.releaseAccess) != null ? _c : license.releaseAccess) != null ? _d : null,
1978
+ upgradeUrl: (_e = refusal.upgradeUrl) != null ? _e : null
1979
+ };
1980
+ }
1981
+ function sameStamp(a, b) {
1982
+ return !!a && a.exists === b.exists && a.size === b.size && a.modified === b.modified;
1983
+ }
1984
+ var ActivationController = class {
1985
+ constructor(options) {
1986
+ this.listeners = /* @__PURE__ */ new Set();
1987
+ /** The callers of {@link ready} waiting for the stored license to be checked. */
1988
+ this.waitingForReady = /* @__PURE__ */ new Set();
1989
+ this.shutdown = new AbortController();
1990
+ this.generation = 0;
1991
+ this.started = false;
1992
+ this.watchTimer = null;
1993
+ this.watching = false;
1994
+ this.onlineQueue = Promise.resolve();
1995
+ this.emittedSubProducts = [];
1996
+ this.loading = false;
1997
+ this.standing = { kind: "unlicensed", reason: null };
1998
+ this.activation = null;
1999
+ this.pending = null;
2000
+ /** The generation of the deactivation in flight, so only that one clears it. */
2001
+ this.deactivating = null;
2002
+ this.error = null;
2003
+ this.refreshesInFlight = 0;
2004
+ this.lastGraceCheck = null;
2005
+ this.fileStamp = null;
2006
+ /** Where to buy the upgrade the update screen last offered. */
2007
+ this.updateUpgradeUrl = null;
2008
+ this.addOns = emptyAddOns();
2009
+ /** Bumped by every list, and when the license they were listed for goes, so a list that lands late is dropped. */
2010
+ this.addOnsGeneration = 0;
2011
+ this.addOnCalls = 0;
2012
+ this.addOnCall = 0;
2013
+ /** Add-ons that ran out and were checked again for, once each. */
2014
+ this.lapsesChecked = /* @__PURE__ */ new Set();
2015
+ /** Set once an add-on's buy link opened, until the app comes back to the front. */
2016
+ this.purchaseOpenedAt = null;
2017
+ this.leftForPurchase = null;
2018
+ /** The ends the screens count down to, and the days to each as of the last watch tick. */
2019
+ this.countdown = [[], []];
2020
+ var _a, _b, _c, _d, _e, _f;
2021
+ this.options = options;
2022
+ this.licenseFile = options.licenseFile;
2023
+ this.store = new FileLicenseStore({ dir: import_node_path4.default.dirname(options.licenseFile), licenseFileName: import_node_path4.default.basename(options.licenseFile) });
2024
+ this.licensing = new MoonbaseLicensing({ ...options, licenseStore: this.store });
2025
+ this.gracePeriod = (_a = options.gracePeriod) != null ? _a : 7 * DAY;
2026
+ this.checkInterval = (_b = options.checkInterval) != null ? _b : 5 * 6e4;
2027
+ const log = (_c = options.log) != null ? _c : {};
2028
+ this.log = {
2029
+ debug: (_d = log.debug) != null ? _d : noop,
2030
+ info: (_e = log.info) != null ? _e : noop,
2031
+ warn: (_f = log.warn) != null ? _f : (message) => console.warn(message)
2032
+ };
2033
+ }
2034
+ // -- State --------------------------------------------------------------------
2035
+ /**
2036
+ * Is there a valid license right now? Cheap enough to check anywhere a feature
2037
+ * is gated.
2038
+ */
2039
+ isLicensed() {
2040
+ return this.standing.kind === "licensed";
2041
+ }
2042
+ /** The license in force, if any. */
2043
+ license() {
2044
+ return this.standing.kind === "licensed" ? this.standing.license : null;
2045
+ }
2046
+ /**
2047
+ * Whether to unlock an add-on on this device: the license in force lists it as
2048
+ * active and it hasn't expired. Takes the add-on's own part of its product ID
2049
+ * (`drum-kit`) or its whole ID (`my-app.drum-kit`). False while no license is
2050
+ * in force.
2051
+ */
2052
+ hasSubProduct(subProductId) {
2053
+ const license = this.license();
2054
+ return !!license && hasSubProduct(license, subProductId);
2055
+ }
2056
+ /** The add-ons {@link hasSubProduct} is true for right now, by their own part of their product ID. */
2057
+ activeSubProducts() {
2058
+ const license = this.license();
2059
+ return license ? activeSubProductsOf(license) : [];
2060
+ }
2061
+ /** A snapshot of the license state, as a UI sees it. */
2062
+ state() {
2063
+ let status;
2064
+ if (this.loading)
2065
+ status = "loading";
2066
+ else if (this.activation)
2067
+ status = "activating";
2068
+ else if (this.standing.kind === "licensed")
2069
+ status = this.standing.license.trial ? "trial" : "licensed";
2070
+ else
2071
+ status = this.standing.kind;
2072
+ const license = this.license();
2073
+ const current = this.options.appVersion;
2074
+ const latest = license == null ? void 0 : license.product.currentReleaseVersion;
2075
+ const update = license && current && latest && isNewerVersion(current, latest) ? { currentVersion: current, latestVersion: latest } : null;
2076
+ const notCovered = this.standing.kind === "notCovered" ? this.standing.notCovered : null;
2077
+ const notCoveredView = notCovered ? { license: toView(notCovered.license), appVersion: notCovered.appVersion, releaseAccess: notCovered.releaseAccess, upgradeUrl: notCovered.upgradeUrl } : null;
2078
+ return {
2079
+ status,
2080
+ licensed: !!license,
2081
+ license: license ? toView(license) : null,
2082
+ expiredTrial: this.standing.kind === "trialExpired" ? toView(this.standing.trial) : null,
2083
+ notCovered: notCoveredView,
2084
+ lockReason: this.lockReason(),
2085
+ activation: this.activation ? { ...this.activation } : null,
2086
+ busy: this.deactivating !== null,
2087
+ refreshing: this.refreshesInFlight > 0,
2088
+ error: this.error ? { ...this.error } : null,
2089
+ update,
2090
+ activeSubProducts: license ? activeSubProductsOf(license) : [],
2091
+ addOns: { ...this.addOns, addOns: [...this.addOns.addOns] }
2092
+ };
2093
+ }
2094
+ /**
2095
+ * Resolves with the license state once {@link start} has checked the stored
2096
+ * license, or at once if it already has, so a caller need not watch for
2097
+ * `loading` to end. Rejects if the controller is disposed first.
2098
+ */
2099
+ ready() {
2100
+ if (this.shutdown.signal.aborted)
2101
+ return Promise.reject(new ActivationError("internal", "This controller was disposed"));
2102
+ if (this.started && !this.loading)
2103
+ return Promise.resolve(this.state());
2104
+ return new Promise((resolve, reject) => this.waitingForReady.add({ resolve, reject }));
2105
+ }
2106
+ /** Called with the new state after every change. Returns a function that stops it. */
2107
+ subscribe(listener) {
2108
+ this.listeners.add(listener);
2109
+ return () => this.listeners.delete(listener);
2110
+ }
2111
+ lockReason() {
2112
+ switch (this.standing.kind) {
2113
+ case "unlicensed":
2114
+ return this.standing.reason;
2115
+ case "licensed":
2116
+ return null;
2117
+ case "trialExpired":
2118
+ return "expired";
2119
+ case "notCovered":
2120
+ return "notCovered";
2121
+ }
2122
+ }
2123
+ /** The license this device holds: the one in force, or one that doesn't cover this version of the app. */
2124
+ held() {
2125
+ if (this.standing.kind === "licensed")
2126
+ return this.standing.license;
2127
+ if (this.standing.kind === "notCovered")
2128
+ return this.standing.notCovered.license;
2129
+ return null;
2130
+ }
2131
+ emit() {
2132
+ const state = this.state();
2133
+ this.emittedSubProducts = state.activeSubProducts;
2134
+ for (const listener of [...this.listeners]) {
2135
+ try {
2136
+ listener(state);
2137
+ } catch (err) {
2138
+ this.log.warn(`moonbase: a state listener failed: ${errorText(err)}`);
2139
+ }
2140
+ }
2141
+ }
2142
+ bump() {
2143
+ return ++this.generation;
2144
+ }
2145
+ isCurrent(generation) {
2146
+ return this.generation === generation;
2147
+ }
2148
+ resetAddOns() {
2149
+ this.addOnsGeneration++;
2150
+ this.addOns = emptyAddOns();
2151
+ this.addOnCall = 0;
2152
+ this.lapsesChecked.clear();
2153
+ this.purchaseOpenedAt = null;
2154
+ this.leftForPurchase = null;
2155
+ }
2156
+ setStanding(standing) {
2157
+ const current = this.license();
2158
+ const next = standing.kind === "licensed" ? standing.license : null;
2159
+ if (!(current && next && sameActivation(current, next)))
2160
+ this.resetAddOns();
2161
+ this.standing = standing;
2162
+ }
2163
+ setLicense(license) {
2164
+ this.setStanding({ kind: "licensed", license });
2165
+ }
2166
+ /** Drop the license and say why. The file stays, so the next launch checks it again. */
2167
+ lock(reason) {
2168
+ this.setStanding({ kind: "unlicensed", reason });
2169
+ }
2170
+ showTrialExpired(trial) {
2171
+ this.setStanding({ kind: "trialExpired", trial });
2172
+ }
2173
+ /** Lock like an ended trial, but keep the license stored: it still covers the versions it did. */
2174
+ showNotCovered(notCovered) {
2175
+ this.setStanding({ kind: "notCovered", notCovered });
2176
+ this.error = null;
2177
+ }
2178
+ /** Stop polling and drop everything in flight: their results land on nothing. */
2179
+ endActivationFlows() {
2180
+ this.activation = null;
2181
+ this.pending = null;
2182
+ this.deactivating = null;
2183
+ this.resetAddOns();
2184
+ this.bump();
2185
+ }
2186
+ /** Whether `copy` is an older copy of the activation held, licensed or not covered. */
2187
+ isOlderThanHeld(copy) {
2188
+ const held = this.held();
2189
+ return !!held && sameActivation(held, copy) && copy.validatedAt < held.validatedAt;
2190
+ }
2191
+ // -- The license file ---------------------------------------------------------
2192
+ async stampFile() {
2193
+ try {
2194
+ const stat = await import_promises4.default.stat(this.licenseFile);
2195
+ if (stat.isFile())
2196
+ return { exists: true, size: stat.size, modified: stat.mtimeMs };
2197
+ } catch (e) {
2198
+ }
2199
+ return { exists: false, size: 0, modified: 0 };
2200
+ }
2201
+ /** The token stored in the license file, read straight from the file, with no validation. */
2202
+ async storedToken() {
2203
+ try {
2204
+ const stored = JSON.parse(await import_promises4.default.readFile(this.licenseFile, "utf8"));
2205
+ return typeof stored.token === "string" ? stored.token : null;
2206
+ } catch (e) {
2207
+ return null;
2208
+ }
2209
+ }
2210
+ /**
2211
+ * Whether the store still holds this activation. If it no longer does, another
2212
+ * instance deactivated or replaced it after a request went out, and writing that
2213
+ * request's answer would bring a removed license back.
2214
+ */
2215
+ async storesActivation(activationId) {
2216
+ const token = await this.storedToken();
2217
+ return !!token && activationIdOfToken(token) === activationId;
2218
+ }
2219
+ withStoreLock(action) {
2220
+ return withFileLock(`${this.licenseFile}.lock`, action, { signal: this.shutdown.signal });
2221
+ }
2222
+ /** Store a license under the store's lock, when `shouldPersist` still says so. Best-effort. */
2223
+ async storeUnderLock(license, shouldPersist = () => true) {
2224
+ try {
2225
+ await this.withStoreLock(async () => {
2226
+ if (await shouldPersist())
2227
+ await this.store.storeLocalLicense(license);
2228
+ });
2229
+ } catch (err) {
2230
+ this.log.warn(`moonbase: couldn't store the license: ${errorText(err)}`);
2231
+ }
2232
+ }
2233
+ /**
2234
+ * Delete the stored license. With `only`, just while the file still holds the
2235
+ * license it picks out: another instance may have stored a new one since.
2236
+ */
2237
+ async deleteStored(only) {
2238
+ let kept = false;
2239
+ try {
2240
+ await this.withStoreLock(async () => {
2241
+ const token = only ? await this.storedToken() : null;
2242
+ if (only && (!token || !only(token))) {
2243
+ kept = true;
2244
+ return;
2245
+ }
2246
+ await this.store.deleteLocalLicense();
2247
+ });
2248
+ } catch (err) {
2249
+ this.log.warn(`moonbase: couldn't delete the stored license: ${errorText(err)}`);
2250
+ }
2251
+ this.fileStamp = kept ? null : await this.stampFile();
2252
+ }
2253
+ /** In-process turns for a re-check and an add-on call, so their answers land in the order they reached the store. */
2254
+ onlineTurn(action) {
2255
+ const run = this.onlineQueue.then(action, action);
2256
+ this.onlineQueue = run.catch(noop);
2257
+ return run;
2258
+ }
2259
+ ensureCoversAppVersion(license) {
2260
+ const { appVersion, enforceReleaseAccess } = this.options;
2261
+ if (enforceReleaseAccess === false || !appVersion || coversVersion(license, appVersion))
2262
+ return;
2263
+ const parsed = parseAppVersion(appVersion);
2264
+ const version2 = parsed ? `${parsed.major}.${parsed.minor}.${parsed.patch}` : appVersion;
2265
+ throw new ReleaseNotCoveredError("Version not covered", `The license doesn't cover version ${version2}`, { license, appVersion: version2 });
2266
+ }
2267
+ validateLocally(token, options = {}) {
2268
+ var _a;
2269
+ return this.licensing.validator.validateLicense(token, { enforceReleaseAccess: (_a = options.enforceReleaseAccess) != null ? _a : false, allowExpired: options.allowExpired });
2270
+ }
2271
+ /**
2272
+ * Validate a license on the device, then online when it is due, and store the
2273
+ * refreshed copy, as `validate_token_online_with` does in the Rust SDK:
2274
+ *
2275
+ * - Validated more recently than the check interval: Moonbase is not asked.
2276
+ * - A failure that is not a verdict (offline, 5xx, rate limiting, a closed
2277
+ * store) falls back to the license while it is within the grace period.
2278
+ * - Offline licenses never contact Moonbase.
2279
+ * - A license that doesn't cover the app's version fails with a
2280
+ * `ReleaseNotCoveredError`; the copy Moonbase sent along is stored first.
2281
+ *
2282
+ * Instances sharing the license file take turns, and a later one picks up the
2283
+ * license an earlier one just refreshed instead of asking again.
2284
+ */
2285
+ async validateOnline(token, shouldPersist) {
2286
+ const local = await this.validateLocally(token);
2287
+ if (local.activationMethod === "Offline" /* Offline */) {
2288
+ this.ensureCoversAppVersion(local);
2289
+ return local;
2290
+ }
2291
+ try {
2292
+ return await this.validateOnlineUnderLock(token, local, shouldPersist);
2293
+ } catch (err) {
2294
+ if (!(err instanceof LockUnavailableError) || age(local.validatedAt) > this.gracePeriod)
2295
+ throw err;
2296
+ this.log.warn(`moonbase: couldn't check the license online: ${errorText(err)}`);
2297
+ this.ensureCoversAppVersion(local);
2298
+ return local;
2299
+ }
2300
+ }
2301
+ async validateOnlineUnderLock(token, local, shouldPersist) {
2302
+ return await this.withStoreLock(async () => {
2303
+ let freshest = local;
2304
+ let undecided = false;
2305
+ const storedToken = await this.storedToken();
2306
+ if (storedToken && storedToken !== freshest.token) {
2307
+ try {
2308
+ const candidate = await this.validateLocally(storedToken);
2309
+ if (sameActivation(candidate, freshest)) {
2310
+ if (candidate.validatedAt > freshest.validatedAt)
2311
+ freshest = candidate;
2312
+ else if (candidate.validatedAt.getTime() === freshest.validatedAt.getTime())
2313
+ undecided = true;
2314
+ }
2315
+ } catch (e) {
2316
+ }
2317
+ }
2318
+ if (freshest.activationMethod === "Offline" /* Offline */) {
2319
+ this.ensureCoversAppVersion(freshest);
2320
+ return freshest;
2321
+ }
2322
+ const since = age(freshest.validatedAt);
2323
+ if (!undecided && since < this.checkInterval && since <= this.gracePeriod) {
2324
+ this.ensureCoversAppVersion(freshest);
2325
+ return freshest;
2326
+ }
2327
+ try {
2328
+ const refreshed = await this.licensing.client.validateLicense(freshest);
2329
+ if (await shouldPersist())
2330
+ await this.store.storeLocalLicense(refreshed).catch((err) => this.log.warn(`moonbase: couldn't store the license: ${errorText(err)}`));
2331
+ return refreshed;
2332
+ } catch (err) {
2333
+ if (err instanceof ReleaseNotCoveredError) {
2334
+ if (err.license && await shouldPersist())
2335
+ await this.store.storeLocalLicense(err.license).catch(noop);
2336
+ throw err;
2337
+ }
2338
+ if (isLicenseRejection(err))
2339
+ throw err;
2340
+ if (since <= this.gracePeriod) {
2341
+ this.log.debug(`moonbase: couldn't reach Moonbase, the license is within its grace period: ${errorText(err)}`);
2342
+ this.ensureCoversAppVersion(freshest);
2343
+ return freshest;
2344
+ }
2345
+ throw err;
2346
+ }
2347
+ });
2348
+ }
2349
+ // -- Startup ------------------------------------------------------------------
2350
+ /**
2351
+ * Validate the stored license and start watching it. Call once; the state is
2352
+ * `loading` until the stored license has been checked.
2353
+ */
2354
+ start() {
2355
+ var _a, _b, _c;
2356
+ if (this.started)
2357
+ return;
2358
+ this.started = true;
2359
+ this.loading = true;
2360
+ const generation = this.bump();
2361
+ void (async () => {
2362
+ this.fileStamp = await this.stampFile();
2363
+ const outcome = await this.checkStoredLicense(generation).catch((err) => {
2364
+ this.log.warn(`moonbase: checking the stored license failed: ${errorText(err)}`);
2365
+ return { reason: null };
2366
+ });
2367
+ this.loading = false;
2368
+ if (this.isCurrent(generation)) {
2369
+ const expiredToken = outcome.deleteExpiredOffline;
2370
+ if (expiredToken)
2371
+ await this.deleteStored((stored) => stored === expiredToken);
2372
+ if (outcome.expiredTrial)
2373
+ this.showTrialExpired(outcome.expiredTrial);
2374
+ else if (outcome.notCovered)
2375
+ this.showNotCovered(outcome.notCovered);
2376
+ else if (outcome.license)
2377
+ this.setLicense(outcome.license);
2378
+ else
2379
+ this.lock(outcome.reason);
2380
+ }
2381
+ this.emit();
2382
+ if (!this.shutdown.signal.aborted) {
2383
+ const state = this.state();
2384
+ for (const waiting of this.waitingForReady)
2385
+ waiting.resolve(state);
2386
+ this.waitingForReady.clear();
2387
+ }
2388
+ })();
2389
+ this.watchTimer = setInterval(() => void this.watch(), (_a = this.options.watchInterval) != null ? _a : 2e3);
2390
+ (_c = (_b = this.watchTimer).unref) == null ? void 0 : _c.call(_b);
2391
+ }
2392
+ /** Stop watching and polling, and stop waiting on another process's license check. */
2393
+ dispose() {
2394
+ this.bump();
2395
+ this.shutdown.abort();
2396
+ if (this.watchTimer)
2397
+ clearInterval(this.watchTimer);
2398
+ this.watchTimer = null;
2399
+ this.listeners.clear();
2400
+ for (const waiting of this.waitingForReady)
2401
+ waiting.reject(new ActivationError("internal", "This controller was disposed"));
2402
+ this.waitingForReady.clear();
2403
+ }
2404
+ async checkStoredLicense(generation) {
2405
+ const token = await this.storedToken();
2406
+ if (!token)
2407
+ return { reason: null };
2408
+ let peek;
2409
+ try {
2410
+ peek = await this.validateLocally(token, { allowExpired: true });
2411
+ } catch (err) {
2412
+ if (isType(err, "DeviceIdentityUnavailable" /* DeviceIdentityUnavailable */)) {
2413
+ this.log.warn("moonbase: could not identify this device, so the stored license could not be checked");
2414
+ return { reason: null };
2415
+ }
2416
+ this.log.warn(`moonbase: stored license rejected: ${errorText(err)}`);
2417
+ return { reason: "invalid" };
2418
+ }
2419
+ const acceptLocally = () => {
2420
+ try {
2421
+ this.ensureCoversAppVersion(peek);
2422
+ return { license: peek, reason: null };
2423
+ } catch (err) {
2424
+ this.log.info(`moonbase: the stored license doesn't cover this version: ${errorText(err)}`);
2425
+ return { notCovered: notCoveredFrom(err, peek), reason: null };
2426
+ }
2427
+ };
2428
+ if (peek.activationMethod === "Offline" /* Offline */) {
2429
+ if (peek.expiresAt && peek.expiresAt <= /* @__PURE__ */ new Date()) {
2430
+ this.log.info("moonbase: the stored offline license has expired; removing it");
2431
+ return { deleteExpiredOffline: token, reason: "expired" };
2432
+ }
2433
+ return acceptLocally();
2434
+ }
2435
+ const activationId = activationIdOf(peek);
2436
+ const stillCurrent = async () => this.isCurrent(generation) && await this.storesActivation(activationId);
2437
+ try {
2438
+ if (peek.expiresAt && peek.expiresAt <= /* @__PURE__ */ new Date()) {
2439
+ const refreshed = await this.withStoreLock(async () => {
2440
+ const answer = await this.licensing.client.validateLicense(peek);
2441
+ if (await stillCurrent())
2442
+ await this.store.storeLocalLicense(answer).catch(noop);
2443
+ return answer;
2444
+ });
2445
+ return { license: refreshed, reason: null };
2446
+ }
2447
+ return { license: await this.validateOnline(token, stillCurrent), reason: null };
2448
+ } catch (err) {
2449
+ if (err instanceof ReleaseNotCoveredError) {
2450
+ this.log.info(`moonbase: the stored license doesn't cover this version: ${errorText(err)}`);
2451
+ return { notCovered: notCoveredFrom(err, peek), reason: null };
2452
+ }
2453
+ if (isType(err, "LicenseExpired" /* LicenseExpired */) || peek.expiresAt && peek.expiresAt <= /* @__PURE__ */ new Date() && !isUnanswered(err)) {
2454
+ return peek.trial ? { expiredTrial: peek, reason: "expired" } : { reason: "expired" };
2455
+ }
2456
+ if (isLicenseInvalid(err)) {
2457
+ this.log.warn(`moonbase: re-validating the stored license failed: ${errorText(err)}`);
2458
+ return { reason: "invalid" };
2459
+ }
2460
+ if (peek.expiresAt && peek.expiresAt <= /* @__PURE__ */ new Date()) {
2461
+ return peek.trial ? { expiredTrial: peek, reason: "expired" } : { reason: "expired" };
2462
+ }
2463
+ this.log.warn(`moonbase: re-validating the stored license failed: ${errorText(err)}`);
2464
+ return { reason: "unverified" };
2465
+ }
2466
+ }
2467
+ // -- Activation ---------------------------------------------------------------
2468
+ /**
2469
+ * Start a browser activation: create the request, open the browser, and poll in
2470
+ * the background until it completes. Resolves once the request exists, with its
2471
+ * link in `state.activation`. Moonbase starts trials in the same browser flow as
2472
+ * purchases, so this covers both.
2473
+ */
2474
+ async activate() {
2475
+ if (this.deactivating !== null)
2476
+ throw new ActivationError("busy", "A deactivation is in progress");
2477
+ this.activation = { browserUrl: null, method: "Online" /* Online */, browserOpenFailed: false };
2478
+ this.pending = null;
2479
+ this.error = null;
2480
+ const generation = this.bump();
2481
+ this.emit();
2482
+ let request;
2483
+ try {
2484
+ request = await this.licensing.client.requestActivation();
2485
+ } catch (err) {
2486
+ if (!this.isCurrent(generation))
2487
+ return this.state();
2488
+ this.log.warn(`moonbase: requesting activation failed: ${errorText(err)}`);
2489
+ this.activation = null;
2490
+ this.error = failure("startActivation", err);
2491
+ this.emit();
2492
+ throw err;
2493
+ }
2494
+ if (!this.isCurrent(generation))
2495
+ return this.state();
2496
+ this.pending = request;
2497
+ this.activation = { browserUrl: request.browser, method: "Online" /* Online */, browserOpenFailed: false };
2498
+ if (this.options.openBrowser !== false) {
2499
+ try {
2500
+ await this.options.openUrl(request.browser);
2501
+ } catch (err) {
2502
+ this.log.warn(`moonbase: couldn't open the browser for activation (${errorText(err)}); the state carries the link`);
2503
+ if (this.isCurrent(generation) && this.activation)
2504
+ this.activation.browserOpenFailed = true;
2505
+ }
2506
+ }
2507
+ void this.poll(generation, request);
2508
+ this.emit();
2509
+ return this.state();
2510
+ }
2511
+ async poll(generation, request) {
2512
+ var _a;
2513
+ for (; ; ) {
2514
+ await sleep((_a = this.options.pollInterval) != null ? _a : 2e3);
2515
+ if (this.shutdown.signal.aborted || !this.isCurrent(generation))
2516
+ return;
2517
+ let license;
2518
+ try {
2519
+ license = await this.licensing.client.getRequestedActivation(request);
2520
+ } catch (err) {
2521
+ if (!this.isCurrent(generation))
2522
+ return;
2523
+ if (err instanceof ReleaseNotCoveredError && err.license) {
2524
+ const covered = err.license;
2525
+ await this.storeUnderLock(covered, () => this.isCurrent(generation));
2526
+ if (!this.isCurrent(generation))
2527
+ return;
2528
+ this.endActivationFlows();
2529
+ this.fileStamp = await this.stampFile();
2530
+ this.showNotCovered(notCoveredFrom(err, covered));
2531
+ this.emit();
2532
+ return;
2533
+ }
2534
+ if (endsActivation(err)) {
2535
+ this.log.warn(`moonbase: activation rejected during polling: ${errorText(err)}`);
2536
+ this.activation = null;
2537
+ this.pending = null;
2538
+ this.error = failure("activation", err);
2539
+ this.emit();
2540
+ return;
2541
+ }
2542
+ this.log.debug(`moonbase: activation poll failed, still waiting: ${errorText(err)}`);
2543
+ continue;
2544
+ }
2545
+ if (!license)
2546
+ continue;
2547
+ await this.storeUnderLock(license, () => this.isCurrent(generation));
2548
+ if (!this.isCurrent(generation))
2549
+ return;
2550
+ this.endActivationFlows();
2551
+ this.fileStamp = await this.stampFile();
2552
+ this.setLicense(license);
2553
+ this.error = null;
2554
+ this.emit();
2555
+ return;
2556
+ }
2557
+ }
2558
+ /** Stop waiting for a browser activation. A license held from before stays. */
2559
+ cancelActivation() {
2560
+ if (!this.activation)
2561
+ return this.state();
2562
+ this.activation = null;
2563
+ this.pending = null;
2564
+ this.error = null;
2565
+ this.bump();
2566
+ this.emit();
2567
+ return this.state();
2568
+ }
2569
+ /**
2570
+ * Check the license with Moonbase again and refresh what it unlocks: call it
2571
+ * after a purchase, so new features and add-ons load without a restart. `force`
2572
+ * (the default) skips the throttle on online checks.
2573
+ *
2574
+ * A revoked or ended license locks, and so does one that cannot be checked once
2575
+ * the offline grace period has run out; within it a network failure keeps the
2576
+ * license and rejects. Does nothing for offline licenses, and while an
2577
+ * activation is in progress (it brings a fresh license of its own).
2578
+ *
2579
+ * With `notCovered`, it checks the license that doesn't cover this version, so
2580
+ * once the customer has bought the upgrade the app unlocks.
2581
+ */
2582
+ async refresh(options = {}) {
2583
+ var _a;
2584
+ const force = (_a = options.force) != null ? _a : true;
2585
+ if (this.activation)
2586
+ return this.state();
2587
+ if (this.deactivating !== null)
2588
+ throw new ActivationError("busy", "A deactivation is in progress");
2589
+ const current = this.held();
2590
+ if (!current)
2591
+ throw new ActivationError("notLicensed", "There is no license to check");
2592
+ if (current.activationMethod === "Offline" /* Offline */)
2593
+ return this.state();
2594
+ this.refreshesInFlight++;
2595
+ const generation = this.bump();
2596
+ const notCoveredBefore = !this.license();
2597
+ if (notCoveredBefore)
2598
+ this.emit();
2599
+ const activationId = activationIdOf(current);
2600
+ const stillCurrent = async () => this.isCurrent(generation) && await this.storesActivation(activationId);
2601
+ const result = await this.onlineTurn(async () => {
2602
+ try {
2603
+ if (!force)
2604
+ return { license: await this.validateOnline(current.token, stillCurrent) };
2605
+ return await this.withStoreLock(async () => {
2606
+ try {
2607
+ const refreshed = await this.licensing.client.validateLicense(current);
2608
+ if (await stillCurrent())
2609
+ await this.store.storeLocalLicense(refreshed).catch((err2) => this.log.warn(`moonbase: couldn't persist the refreshed license: ${errorText(err2)}`));
2610
+ return { license: refreshed };
2611
+ } catch (err2) {
2612
+ if (err2 instanceof ReleaseNotCoveredError && err2.license && await stillCurrent())
2613
+ await this.store.storeLocalLicense(err2.license).catch(noop);
2614
+ return { error: err2 };
2615
+ }
2616
+ });
2617
+ } catch (err2) {
2618
+ return { error: err2 };
2619
+ }
2620
+ });
2621
+ this.refreshesInFlight--;
2622
+ if (!this.isCurrent(generation)) {
2623
+ if (notCoveredBefore)
2624
+ this.emit();
2625
+ return this.state();
2626
+ }
2627
+ if ("license" in result) {
2628
+ const refreshed = result.license;
2629
+ const held = this.license();
2630
+ if (!force && refreshed.token === current.token && held && sameActivation(held, refreshed) && held.token !== current.token)
2631
+ return this.state();
2632
+ if (!await this.storesActivation(activationId)) {
2633
+ this.log.debug("moonbase: dropped a re-validation answer for a license another instance removed or replaced");
2634
+ if (notCoveredBefore)
2635
+ this.emit();
2636
+ return this.state();
2637
+ }
2638
+ this.fileStamp = await this.stampFile();
2639
+ if (notCoveredBefore)
2640
+ this.error = null;
2641
+ this.setLicense(refreshed);
2642
+ this.emit();
2643
+ return this.state();
2644
+ }
2645
+ const err = result.error;
2646
+ let rethrow = false;
2647
+ if (err instanceof ReleaseNotCoveredError) {
2648
+ const notCovered = notCoveredFrom(err, current);
2649
+ if (this.isOlderThanHeld(notCovered.license)) {
2650
+ this.log.debug(`moonbase: dropped a re-validation answer older than the license held: ${errorText(err)}`);
2651
+ } else {
2652
+ this.log.info(`moonbase: the license doesn't cover this version on re-validation: ${errorText(err)}`);
2653
+ this.showNotCovered(notCovered);
2654
+ }
2655
+ } else if (isType(err, "LicenseExpired" /* LicenseExpired */) && current.trial) {
2656
+ this.log.info(`moonbase: the trial ended on re-validation: ${errorText(err)}`);
2657
+ this.showTrialExpired(current);
2658
+ } else if (!isLicenseRejection(err) && this.standing.kind === "notCovered") {
2659
+ this.log.warn(`moonbase: couldn't check the license that doesn't cover this version: ${errorText(err)}`);
2660
+ this.error = { message: "Couldn't reach Moonbase to check your license. Try again when you're online.", detail: errorText(err), kind: failureKind(err) };
2661
+ rethrow = true;
2662
+ } else if (isLicenseRejection(err)) {
2663
+ this.log.warn(`moonbase: license rejected on re-validation: ${errorText(err)}`);
2664
+ this.lock(isType(err, "LicenseExpired" /* LicenseExpired */) ? "expired" : "invalid");
2665
+ } else if (age(current.validatedAt) > this.gracePeriod) {
2666
+ this.log.warn(`moonbase: couldn't re-validate within the offline grace period: ${errorText(err)}`);
2667
+ this.lock("unverified");
2668
+ } else {
2669
+ rethrow = true;
2670
+ }
2671
+ this.emit();
2672
+ if (rethrow)
2673
+ throw err;
2674
+ return this.state();
2675
+ }
2676
+ /**
2677
+ * Free this device's seat and lock. Offline and trial licenses cannot be
2678
+ * revoked, so those are forgotten on this device instead. When Moonbase cannot be
2679
+ * reached the license is kept, and the error says so. Also hands back the seat
2680
+ * of a license that doesn't cover this version of the app.
2681
+ */
2682
+ async deactivate() {
2683
+ const license = this.held();
2684
+ if (!license)
2685
+ throw new ActivationError("notLicensed", "There is no license to deactivate");
2686
+ if (license.activationMethod === "Offline" /* Offline */ || license.trial)
2687
+ return await this.forget();
2688
+ if (this.deactivating !== null)
2689
+ throw new ActivationError("busy", "A deactivation is already in progress");
2690
+ if (this.activation)
2691
+ throw new ActivationError("busy", "Finish or cancel the activation first");
2692
+ this.error = null;
2693
+ const generation = this.bump();
2694
+ this.deactivating = generation;
2695
+ this.emit();
2696
+ let outcome = {};
2697
+ try {
2698
+ await this.licensing.client.revokeLicense(license);
2699
+ } catch (err) {
2700
+ outcome = { error: err };
2701
+ }
2702
+ if (this.deactivating === generation)
2703
+ this.deactivating = null;
2704
+ if (!this.isCurrent(generation)) {
2705
+ this.emit();
2706
+ return this.state();
2707
+ }
2708
+ if ("error" in outcome && !isLicenseRejection(outcome.error)) {
2709
+ this.log.warn(`moonbase: deactivating failed, the license is kept: ${errorText(outcome.error)}`);
2710
+ this.error = failure("deactivation", outcome.error);
2711
+ this.emit();
2712
+ throw outcome.error;
2713
+ }
2714
+ const activationId = activationIdOf(license);
2715
+ await this.deleteStored((stored) => activationIdOfToken(stored) === activationId);
2716
+ this.lock("deactivated");
2717
+ this.emit();
2718
+ return this.state();
2719
+ }
2720
+ /** Forget the license on this device only, without telling Moonbase. */
2721
+ async forget() {
2722
+ this.endActivationFlows();
2723
+ this.lock("deactivated");
2724
+ this.error = null;
2725
+ this.emit();
2726
+ await this.deleteStored();
2727
+ return this.state();
2728
+ }
2729
+ /**
2730
+ * The machine file for activating a computer with no internet: save it as a
2731
+ * `.dt` file the customer exchanges at `https://<store>/activate` for a license
2732
+ * file, then pass that file's contents to {@link activateOffline}.
2733
+ */
2734
+ async deviceToken() {
2735
+ return (await this.licensing.generateDeviceToken()).toString("utf8");
2736
+ }
2737
+ /**
2738
+ * Activate from the contents of an offline license file.
2739
+ *
2740
+ * A license file for this device that doesn't cover this version of the app is
2741
+ * stored anyway, as it still covers the versions it did, and the app locks with
2742
+ * `notCovered`; the promise rejects with the `ReleaseNotCoveredError`.
2743
+ */
2744
+ async activateOffline(licenseFile) {
2745
+ try {
2746
+ const license = await this.validateLocally(licenseFile.trim());
2747
+ if (license.activationMethod !== "Offline" /* Offline */)
2748
+ throw new MoonbaseError("Not an offline license", "License token is not an offline-activated license", "LicenseInvalid" /* LicenseInvalid */);
2749
+ try {
2750
+ this.ensureCoversAppVersion(license);
2751
+ } catch (err) {
2752
+ this.log.info(`moonbase: the offline license doesn't cover this version: ${errorText(err)}`);
2753
+ await this.storeUnderLock(license);
2754
+ this.endActivationFlows();
2755
+ this.fileStamp = await this.stampFile();
2756
+ this.showNotCovered(notCoveredFrom(err, license));
2757
+ this.emit();
2758
+ throw err;
2759
+ }
2760
+ await this.storeUnderLock(license);
2761
+ this.endActivationFlows();
2762
+ this.fileStamp = await this.stampFile();
2763
+ this.setLicense(license);
2764
+ this.error = null;
2765
+ this.emit();
2766
+ return this.state();
2767
+ } catch (err) {
2768
+ if (err instanceof ReleaseNotCoveredError)
2769
+ throw err;
2770
+ this.log.warn(`moonbase: offline license file rejected: ${errorText(err)}`);
2771
+ this.error = failure("offlineActivation", err);
2772
+ this.emit();
2773
+ throw err;
2774
+ }
2775
+ }
2776
+ /**
2777
+ * Offer the upgrade the app needs. With `notCovered`, open the upgrade page
2778
+ * Moonbase named for the license or, without one, start an online activation,
2779
+ * whose page offers the upgrade where the store sells one and activates this
2780
+ * device once a license covers this version. Otherwise open the upgrade page
2781
+ * {@link checkUpdate} found for a new version the license doesn't cover. After
2782
+ * the purchase, {@link refresh} picks up the upgraded license.
2783
+ */
2784
+ async upgradeLicense() {
2785
+ const notCovered = this.standing.kind === "notCovered" ? this.standing.notCovered : null;
2786
+ const url = notCovered ? notCovered.upgradeUrl : this.updateUpgradeUrl;
2787
+ if (!url) {
2788
+ if (notCovered)
2789
+ return await this.activate();
2790
+ throw new ActivationError("internal", "There is no upgrade to offer");
2791
+ }
2792
+ try {
2793
+ await this.options.openUrl(url);
2794
+ } catch (err) {
2795
+ this.log.warn(`moonbase: couldn't open the browser for the upgrade: ${errorText(err)}`);
2796
+ if (notCovered) {
2797
+ this.error = { message: `Couldn't open your browser. Upgrade at ${url}`, detail: errorText(err), kind: null };
2798
+ this.emit();
2799
+ }
2800
+ throw new ActivationError("internal", `Couldn't open the browser: ${errorText(err)}`);
2801
+ }
2802
+ return this.state();
2803
+ }
2804
+ /** Clear the last failure, such as when the customer dismisses its message. */
2805
+ dismissError() {
2806
+ this.error = null;
2807
+ this.emit();
2808
+ return this.state();
2809
+ }
2810
+ /** This device, for diagnostics. Never reveals what went into its id, only which parameters did. */
2811
+ async device() {
2812
+ var _a;
2813
+ const resolver = this.licensing.deviceIdResolver;
2814
+ let name = "This computer";
2815
+ try {
2816
+ name = await resolver.resolveDeviceName();
2817
+ } catch (e) {
2818
+ }
2819
+ const platform = (_a = this.licensing.configuration.platform) != null ? _a : "Unknown";
2820
+ const describe = resolver.describeDevice;
2821
+ if (typeof describe !== "function")
2822
+ return { name, platform, description: null, error: null };
2823
+ try {
2824
+ return { name, platform, description: await describe.call(resolver), error: null };
2825
+ } catch (err) {
2826
+ return { name, platform, description: null, error: errorText(err) };
2827
+ }
2828
+ }
2829
+ // -- Updates ------------------------------------------------------------------
2830
+ /**
2831
+ * Whether a newer release than the app is out, with its notes when it is. Only
2832
+ * the notes need the network. For a customer whose licenses don't cover the new
2833
+ * version, says so and where to upgrade.
2834
+ */
2835
+ async checkUpdate() {
2836
+ var _a, _b, _c, _d, _e;
2837
+ const license = this.license();
2838
+ if (!license)
2839
+ throw new ActivationError("notLicensed", "There is no license to check for updates with");
2840
+ const current = (_a = this.options.appVersion) != null ? _a : "";
2841
+ const latest = (_b = license.product.currentReleaseVersion) != null ? _b : null;
2842
+ const info = {
2843
+ available: !!latest && isNewerVersion(current, latest),
2844
+ currentVersion: current,
2845
+ latestVersion: latest,
2846
+ releaseNotes: "",
2847
+ hasDownloads: false,
2848
+ canDownload: false,
2849
+ covered: true,
2850
+ releaseAccess: null,
2851
+ upgradeUrl: null
2852
+ };
2853
+ if (info.available && latest) {
2854
+ const release = await this.licensing.inventory.getRelease(latest, license.token);
2855
+ const platform = this.licensing.configuration.platform;
2856
+ info.hasDownloads = !!platform && release.platforms.includes(platform);
2857
+ info.canDownload = info.hasDownloads && canDownload(license, release);
2858
+ info.releaseNotes = release.description;
2859
+ info.covered = release.releaseCovered;
2860
+ info.releaseAccess = (_c = release.releaseAccess) != null ? _c : null;
2861
+ info.upgradeUrl = (_d = release.upgradeUrl) != null ? _d : null;
2862
+ this.updateUpgradeUrl = (_e = release.upgradeUrl) != null ? _e : null;
2863
+ }
2864
+ return info;
2865
+ }
2866
+ /**
2867
+ * A short-lived link to the latest installer for this platform. Rejects with a
2868
+ * `ReleaseNotCoveredError`, with the upgrade link, when the customer's licenses
2869
+ * don't cover the release.
2870
+ */
2871
+ async updateDownloadUrl() {
2872
+ const license = this.license();
2873
+ if (!license)
2874
+ throw new ActivationError("notLicensed", "There is no license to download the update with");
2875
+ const platform = this.licensing.configuration.platform;
2876
+ if (!platform)
2877
+ throw new ActivationError("internal", "There is no installer for this platform");
2878
+ try {
2879
+ return await this.licensing.inventory.getDownloadUrl(platform, license.token);
2880
+ } catch (err) {
2881
+ if (err instanceof ReleaseNotCoveredError && err.upgradeUrl)
2882
+ this.updateUpgradeUrl = err.upgradeUrl;
2883
+ throw err;
2884
+ }
2885
+ }
2886
+ /**
2887
+ * Download the latest installer for this platform into `directory`, through a
2888
+ * `.part` file moved into place once complete, and resolve with where it is.
2889
+ * Named as Moonbase names the file, or `<productName> installer`, with a number
2890
+ * added when that is taken. Rejects with a `ReleaseNotCoveredError`, with the
2891
+ * upgrade link, when the customer's licenses don't cover the release.
2892
+ */
2893
+ async downloadInstaller(options) {
2894
+ var _a, _b;
2895
+ const target = await this.updateDownloadUrl();
2896
+ const fallback = `${fileSafe((_a = this.options.productName) != null ? _a : "App")} installer`;
2897
+ const name = target.filename ? fileSafe(target.filename) : fallback;
2898
+ await import_promises4.default.mkdir(options.directory, { recursive: true });
2899
+ const file = await reserveFile(options.directory, name === "license" ? fallback : name);
2900
+ try {
2901
+ await downloadFile(target.url, file, (_b = options.onProgress) != null ? _b : noop, options.fetch);
2902
+ } catch (err) {
2903
+ await import_promises4.default.rm(file, { force: true });
2904
+ throw err;
2905
+ }
2906
+ return file;
2907
+ }
2908
+ /** Whether the customer said to skip this release, so the update screen does not come up for it again. */
2909
+ isUpdateSkipped(version2) {
2910
+ return isUpdateSkipped(this.licenseFile, version2);
2911
+ }
2912
+ /**
2913
+ * Never prompt for this release again; a newer one still prompts. Kept in
2914
+ * `<license file>.state.json`, beside the license.
2915
+ */
2916
+ skipUpdate(version2) {
2917
+ return skipUpdate(this.licenseFile, version2);
2918
+ }
2919
+ // -- Add-ons: sub-products the merchant includes in the product's license. The
2920
+ // license in force says which ones this device may unlock; the list says what
2921
+ // else the customer can do: try one, buy one, or take a seat of one they own.
2922
+ /**
2923
+ * List the product's add-ons for this device into `state.addOns`, with their
2924
+ * prices, ownership and trials, for a store or upgrade screen.
2925
+ *
2926
+ * Can take a seat: with `autoActivateSubProducts` on (the default), when the
2927
+ * list shows an add-on the customer owns, with a seat free, that the license
2928
+ * doesn't hold yet (one bought since the license was last checked), the license
2929
+ * is checked once more, which takes that seat as every check does, and the
2930
+ * add-ons are listed again.
2931
+ */
2932
+ loadAddOns() {
2933
+ return this.listAddOns(true);
2934
+ }
2935
+ async listAddOns(pickUpSeats) {
2936
+ const license = this.license();
2937
+ if (!license)
2938
+ throw new ActivationError("notLicensed", "Add-ons are listed from a license");
2939
+ const generation = ++this.addOnsGeneration;
2940
+ this.addOns.phase = "loading";
2941
+ this.addOns.error = null;
2942
+ this.emit();
2943
+ let result;
2944
+ try {
2945
+ result = { catalog: await this.licensing.client.listSubProducts(license) };
2946
+ } catch (err) {
2947
+ result = { error: err };
2948
+ }
2949
+ if (this.addOnsGeneration !== generation)
2950
+ return this.state();
2951
+ this.addOns.phase = "ready";
2952
+ let refused = false;
2953
+ if ("catalog" in result) {
2954
+ this.addOns.currency = result.catalog.currency;
2955
+ this.addOns.addOns = result.catalog.subProducts;
2956
+ this.addOns.error = null;
2957
+ } else {
2958
+ const err = result.error;
2959
+ this.log.warn(`moonbase: listing the add-ons failed: ${errorText(err)}`);
2960
+ if (isType(err, "LicenseExpired" /* LicenseExpired */))
2961
+ this.addOns.error = "Your license has expired.";
2962
+ else if (isLicenseInvalid(err))
2963
+ this.addOns.error = "Your license is no longer valid on this computer.";
2964
+ else
2965
+ this.addOns.error = addOnFailure(err, "Couldn't load the add-ons", "Moonbase couldn't find the add-ons for this license.");
2966
+ refused = isLicenseRejection(err);
2967
+ }
2968
+ const takeSeat = "catalog" in result && pickUpSeats && this.listsSeatToTake();
2969
+ const recheck = refused && this.deactivating === null;
2970
+ this.emit();
2971
+ if (recheck)
2972
+ await this.refresh().catch((err) => this.log.debug(`moonbase: the re-check after a refused add-on list failed: ${errorText(err)}`));
2973
+ if (takeSeat) {
2974
+ this.log.info("moonbase: an add-on the customer owns has a seat free; checking the license again to take it");
2975
+ return await this.refreshAndList();
2976
+ }
2977
+ if ("error" in result)
2978
+ throw result.error;
2979
+ return this.state();
2980
+ }
2981
+ listsSeatToTake() {
2982
+ const license = this.license();
2983
+ if (!license || this.licensing.configuration.autoActivateSubProducts === false || license.trial || license.activationMethod !== "Online" /* Online */)
2984
+ return false;
2985
+ return this.addOns.addOns.some((entry) => {
2986
+ var _a, _b;
2987
+ const owned = entry.product.owned || entry.product.subscribed;
2988
+ if (!entry.includedInLicense || !owned || entry.revoked)
2989
+ return false;
2990
+ const held = findSubProduct(license, entry.id);
2991
+ if (held && !held.trial && hasSubProduct(license, entry.id))
2992
+ return false;
2993
+ return entry.active || ((_b = (_a = entry.seats) == null ? void 0 : _a.remaining) != null ? _b : 0) > 0;
2994
+ });
2995
+ }
2996
+ /**
2997
+ * Check the license again, so an add-on bought since takes its seat, then list
2998
+ * the add-ons again: what "Bought an add-on? Refresh" does after a purchase in
2999
+ * the browser.
3000
+ */
3001
+ refreshAddOns() {
3002
+ this.addOns.actionError = null;
3003
+ return this.refreshAndList();
3004
+ }
3005
+ async refreshAndList() {
3006
+ const license = this.license();
3007
+ if (!license || this.deactivating !== null)
3008
+ return this.state();
3009
+ if (license.activationMethod !== "Offline" /* Offline */) {
3010
+ this.addOns.phase = "loading";
3011
+ this.addOns.error = null;
3012
+ this.emit();
3013
+ await this.refresh().catch((err) => this.log.debug(`moonbase: the re-check before listing the add-ons failed: ${errorText(err)}`));
3014
+ if (!this.license())
3015
+ return this.state();
3016
+ }
3017
+ return await this.listAddOns(false);
3018
+ }
3019
+ /**
3020
+ * Take a seat of an add-on the customer owns for this device, from the full
3021
+ * license in force: one whose seat was revoked here, or any, with
3022
+ * `autoActivateSubProducts` off. Stores the license that comes back, and lists
3023
+ * the add-ons again if they were loaded. One add-on at a time; why one failed is
3024
+ * also in `state.addOns.actionError`, worded for the customer.
3025
+ */
3026
+ activateSubProduct(subProductId) {
3027
+ return this.runSubProductAction(subProductId, false);
3028
+ }
3029
+ /**
3030
+ * Start the trial of an add-on the customer doesn't own on this device, from the
3031
+ * full license in force (owning it, they get a seat instead). Otherwise as
3032
+ * {@link activateSubProduct}.
3033
+ */
3034
+ requestSubProductTrial(subProductId) {
3035
+ return this.runSubProductAction(subProductId, true);
3036
+ }
3037
+ addOnName(subProductId) {
3038
+ var _a, _b;
3039
+ return (_b = (_a = this.addOns.addOns.find((entry) => entry.id === subProductId || entry.product.id === subProductId)) == null ? void 0 : _a.product.name) != null ? _b : null;
3040
+ }
3041
+ async runSubProductAction(subProductId, trial) {
3042
+ var _a, _b;
3043
+ const license = this.license();
3044
+ if (!license || license.trial) {
3045
+ this.addOns.actionError = license ? "Add-ons are activated from a full license, not a trial." : `Activate ${(_a = this.options.productName) != null ? _a : "the app"} first.`;
3046
+ this.emit();
3047
+ throw new ActivationError(license ? "internal" : "notLicensed", this.addOns.actionError);
3048
+ }
3049
+ if (this.addOns.busyId)
3050
+ throw new ActivationError("busy", "Another add-on is still being set up. Try again in a moment.");
3051
+ const activationId = activationIdOf(license);
3052
+ const name = this.addOnName(subProductId);
3053
+ const call = ++this.addOnCalls;
3054
+ this.addOnCall = call;
3055
+ this.addOns.busyId = subProductId;
3056
+ this.addOns.actionError = null;
3057
+ this.emit();
3058
+ const result = await this.onlineTurn(async () => {
3059
+ try {
3060
+ return await this.withStoreLock(async () => {
3061
+ const answer = trial ? await this.licensing.client.requestSubProductTrial(license, subProductId) : await this.licensing.client.activateSubProduct(license, subProductId);
3062
+ if (await this.storesActivation(activationId))
3063
+ await this.store.storeLocalLicense(answer).catch(noop);
3064
+ return { license: answer };
3065
+ });
3066
+ } catch (err2) {
3067
+ return { error: err2 };
3068
+ }
3069
+ });
3070
+ if (this.addOnCall === call) {
3071
+ this.addOnCall = 0;
3072
+ this.addOns.busyId = null;
3073
+ }
3074
+ const now = this.license();
3075
+ const sameLicense = !!now && activationIdOf(now) === activationId;
3076
+ if ("license" in result) {
3077
+ if (!sameLicense || activationIdOf(result.license) !== activationId || !await this.storesActivation(activationId)) {
3078
+ this.emit();
3079
+ throw new ActivationError("busy", LICENSE_CHANGED);
3080
+ }
3081
+ this.fileStamp = await this.stampFile();
3082
+ this.setLicense(result.license);
3083
+ const relist = this.addOns.phase !== "idle";
3084
+ this.emit();
3085
+ if (relist)
3086
+ await this.listAddOns(false).catch((err2) => this.log.debug(`moonbase: listing the add-ons again failed: ${errorText(err2)}`));
3087
+ return this.state();
3088
+ }
3089
+ const err = result.error;
3090
+ this.log.warn(`moonbase: ${trial ? "starting an add-on trial" : "activating an add-on"} failed: ${errorText(err)}`);
3091
+ if (!sameLicense) {
3092
+ this.emit();
3093
+ throw new ActivationError("busy", LICENSE_CHANGED);
3094
+ }
3095
+ const subject = name != null ? name : "This add-on";
3096
+ const object = name != null ? name : "this add-on";
3097
+ const status = err instanceof MoonbaseError ? err.status : void 0;
3098
+ if (isType(err, "NoEligibleLicense" /* NoEligibleLicense */))
3099
+ this.addOns.actionError = `No seat of ${object} is free for this computer. Free one in your ${(_b = this.options.accountName) != null ? _b : "Moonbase"} account, or buy one.`;
3100
+ else if (isType(err, "ApiError" /* ApiError */) && status === 400)
3101
+ this.addOns.actionError = trial ? `${subject} can't be tried on this computer.` : `${subject} can't be activated on this computer.`;
3102
+ else if (isType(err, "LicenseExpired" /* LicenseExpired */))
3103
+ this.addOns.actionError = "Your license has expired.";
3104
+ else if (isLicenseInvalid(err))
3105
+ this.addOns.actionError = "Your license is no longer valid on this computer.";
3106
+ else
3107
+ this.addOns.actionError = addOnFailure(err, trial ? `Couldn't start the trial of ${object}` : `Couldn't activate ${object}`, `Moonbase couldn't find ${object}.`);
3108
+ const recheck = isLicenseRejection(err) && !isType(err, "NoEligibleLicense" /* NoEligibleLicense */) && this.deactivating === null;
3109
+ this.emit();
3110
+ if (recheck)
3111
+ await this.refresh().catch((error) => this.log.debug(`moonbase: the re-check after a refused add-on failed: ${errorText(error)}`));
3112
+ throw err;
3113
+ }
3114
+ /**
3115
+ * Open the add-on's buy link from `state.addOns` in the browser. When the app
3116
+ * then goes to the background (the customer is in the browser) and comes back
3117
+ * to the front, the add-ons are refreshed as {@link refreshAddOns} does, so one
3118
+ * just bought unlocks without a click; see {@link onFocusChanged}.
3119
+ */
3120
+ async buySubProduct(subProductId) {
3121
+ const entry = this.addOns.addOns.find((candidate) => candidate.id === subProductId || candidate.product.id === subProductId);
3122
+ if (!(entry == null ? void 0 : entry.buyUrl))
3123
+ throw new ActivationError("internal", "That add-on isn't for sale here");
3124
+ this.purchaseOpenedAt = Date.now();
3125
+ this.leftForPurchase = null;
3126
+ try {
3127
+ await this.options.openUrl(entry.buyUrl);
3128
+ } catch (err) {
3129
+ this.purchaseOpenedAt = null;
3130
+ this.leftForPurchase = null;
3131
+ this.log.warn(`moonbase: couldn't open the browser to buy an add-on: ${errorText(err)}`);
3132
+ this.addOns.actionError = `Couldn't open your browser to buy ${entry.product.name}.`;
3133
+ this.emit();
3134
+ throw new ActivationError("internal", `Couldn't open the browser: ${errorText(err)}`);
3135
+ }
3136
+ }
3137
+ /**
3138
+ * Tell the controller the app gained or lost the customer's attention (a window
3139
+ * focused or blurred), so it notices the customer coming back from a purchase
3140
+ * in the browser.
3141
+ */
3142
+ onFocusChanged(focused) {
3143
+ const opened = this.purchaseOpenedAt;
3144
+ if (opened === null)
3145
+ return;
3146
+ if (Date.now() - opened > 60 * 6e4) {
3147
+ this.purchaseOpenedAt = null;
3148
+ this.leftForPurchase = null;
3149
+ return;
3150
+ }
3151
+ if (!focused) {
3152
+ this.leftForPurchase = Date.now();
3153
+ return;
3154
+ }
3155
+ const away = this.leftForPurchase !== null && Date.now() - this.leftForPurchase >= 1e3;
3156
+ if (!away || !this.license() || this.deactivating !== null)
3157
+ return;
3158
+ this.purchaseOpenedAt = null;
3159
+ this.leftForPurchase = null;
3160
+ this.log.info("moonbase: back from the browser after opening an add-on's buy link; refreshing the add-ons");
3161
+ this.refreshAddOns().catch((err) => this.log.debug(`moonbase: refreshing the add-ons failed: ${errorText(err)}`));
3162
+ }
3163
+ // -- The watch: local checks only (a stat of the license file, a read when it
3164
+ // changed, and a look at the clock), so no request goes out unless a license or
3165
+ // an add-on has actually run out.
3166
+ async watch() {
3167
+ if (this.loading || this.watching || this.shutdown.signal.aborted)
3168
+ return;
3169
+ this.watching = true;
3170
+ try {
3171
+ await this.checkLicenseFile();
3172
+ if (!await this.checkSubProducts())
3173
+ await this.checkDeadlines();
3174
+ this.checkCountdowns();
3175
+ } catch (err) {
3176
+ this.log.debug(`moonbase: the license watch failed: ${errorText(err)}`);
3177
+ } finally {
3178
+ this.watching = false;
3179
+ }
3180
+ }
3181
+ async checkLicenseFile() {
3182
+ var _a, _b, _c, _d;
3183
+ const stamp = await this.stampFile();
3184
+ const generation = this.generation;
3185
+ if (sameStamp(this.fileStamp, stamp))
3186
+ return;
3187
+ const existed = (_b = (_a = this.fileStamp) == null ? void 0 : _a.exists) != null ? _b : false;
3188
+ this.fileStamp = stamp;
3189
+ if (!stamp.exists) {
3190
+ if (existed)
3191
+ this.onLicenseFileRemoved();
3192
+ return;
3193
+ }
3194
+ const token = await this.storedToken();
3195
+ if (!token || ((_c = this.held()) == null ? void 0 : _c.token) === token)
3196
+ return;
3197
+ let stored;
3198
+ let notCovered = null;
3199
+ try {
3200
+ stored = await this.validateLocally(token, { enforceReleaseAccess: (_d = this.options.enforceReleaseAccess) != null ? _d : true });
3201
+ } catch (err) {
3202
+ if (!(err instanceof ReleaseNotCoveredError) || !err.license)
3203
+ return;
3204
+ stored = err.license;
3205
+ notCovered = notCoveredFrom(err, err.license);
3206
+ }
3207
+ if (stored.activationMethod !== "Offline" /* Offline */ && age(stored.validatedAt) > this.gracePeriod)
3208
+ return;
3209
+ if (notCovered)
3210
+ this.adoptNotCovered(notCovered, generation);
3211
+ else
3212
+ this.adoptStoredLicense(stored, generation);
3213
+ }
3214
+ onLicenseFileRemoved() {
3215
+ if (!this.license() && this.standing.kind !== "notCovered")
3216
+ return;
3217
+ this.log.info("moonbase: the license file was removed by another instance or process; locking");
3218
+ if (!this.activation)
3219
+ this.endActivationFlows();
3220
+ this.lock("deactivated");
3221
+ this.emit();
3222
+ }
3223
+ adoptStoredLicense(stored, generation) {
3224
+ if (!this.isCurrent(generation)) {
3225
+ this.fileStamp = null;
3226
+ return;
3227
+ }
3228
+ if (this.isOlderThanHeld(stored))
3229
+ return;
3230
+ const current = this.license();
3231
+ if (current && sameActivation(current, stored)) {
3232
+ this.setLicense(stored);
3233
+ this.emit();
3234
+ return;
3235
+ }
3236
+ this.log.info("moonbase: picked up a license stored by another instance or process");
3237
+ this.endActivationFlows();
3238
+ this.setLicense(stored);
3239
+ this.emit();
3240
+ }
3241
+ adoptNotCovered(notCovered, generation) {
3242
+ if (!this.isCurrent(generation)) {
3243
+ this.fileStamp = null;
3244
+ return;
3245
+ }
3246
+ if (this.isOlderThanHeld(notCovered.license) || this.activation)
3247
+ return;
3248
+ const held = this.held();
3249
+ const same = !!held && sameActivation(held, notCovered.license);
3250
+ this.log.info("moonbase: another instance or process found that the license doesn't cover this version; locking");
3251
+ if (same && !notCovered.upgradeUrl && this.standing.kind === "notCovered")
3252
+ notCovered = { ...notCovered, upgradeUrl: this.standing.notCovered.upgradeUrl };
3253
+ if (!same)
3254
+ this.endActivationFlows();
3255
+ this.showNotCovered(notCovered);
3256
+ this.emit();
3257
+ }
3258
+ /**
3259
+ * An add-on's trial (or subscription) can run out while the license carries on,
3260
+ * which changes what the app may unlock without a new token. True when it
3261
+ * started a check.
3262
+ */
3263
+ async checkSubProducts() {
3264
+ var _a;
3265
+ const license = this.license();
3266
+ if (!license)
3267
+ return false;
3268
+ const active = activeSubProductsOf(license);
3269
+ const changed = active.join("\n") !== this.emittedSubProducts.join("\n");
3270
+ for (const id of active)
3271
+ this.lapsesChecked.delete(id);
3272
+ const ranOut = [];
3273
+ if (license.activationMethod === "Online" /* Online */ && this.deactivating === null && this.refreshesInFlight === 0 && !this.activation) {
3274
+ const now = /* @__PURE__ */ new Date();
3275
+ for (const entry of (_a = license.subProducts) != null ? _a : []) {
3276
+ if (entry.active && entry.expiresAt && entry.expiresAt <= now && !this.lapsesChecked.has(entry.id))
3277
+ ranOut.push(entry.id);
3278
+ }
3279
+ ranOut.forEach((id) => this.lapsesChecked.add(id));
3280
+ }
3281
+ if (changed)
3282
+ this.emit();
3283
+ if (!ranOut.length)
3284
+ return false;
3285
+ this.log.info("moonbase: an add-on ran out; checking the license in case it was bought or renewed");
3286
+ await this.refresh().catch((err) => this.log.debug(`moonbase: the add-on re-check failed: ${errorText(err)}`));
3287
+ return true;
3288
+ }
3289
+ async checkDeadlines() {
3290
+ const license = this.license();
3291
+ if (!license || this.deactivating !== null || this.refreshesInFlight > 0)
3292
+ return;
3293
+ const expired = !!license.expiresAt && license.expiresAt <= /* @__PURE__ */ new Date();
3294
+ const offline = license.activationMethod === "Offline" /* Offline */;
3295
+ const pastGrace = !offline && age(license.validatedAt) > this.gracePeriod;
3296
+ if (!expired && !pastGrace)
3297
+ return;
3298
+ if (this.activation) {
3299
+ this.log.info("moonbase: the license ran out while an activation was in progress; locking");
3300
+ if (expired && license.trial)
3301
+ this.showTrialExpired(license);
3302
+ else
3303
+ this.lock(expired ? "expired" : "unverified");
3304
+ this.emit();
3305
+ return;
3306
+ }
3307
+ if (offline) {
3308
+ this.log.info("moonbase: the offline license has expired; removing it");
3309
+ this.bump();
3310
+ this.lock("expired");
3311
+ this.emit();
3312
+ await this.deleteStored((stored) => stored === license.token);
3313
+ return;
3314
+ }
3315
+ if (expired) {
3316
+ try {
3317
+ await this.refresh();
3318
+ } catch (err) {
3319
+ this.log.debug(`moonbase: the deadline re-check failed: ${errorText(err)}`);
3320
+ }
3321
+ if (this.license() && this.license().expiresAt && this.license().expiresAt <= /* @__PURE__ */ new Date()) {
3322
+ if (license.trial)
3323
+ this.showTrialExpired(license);
3324
+ else
3325
+ this.lock("expired");
3326
+ this.emit();
3327
+ }
3328
+ return;
3329
+ }
3330
+ if (this.lastGraceCheck !== null && Date.now() - this.lastGraceCheck < this.checkInterval)
3331
+ return;
3332
+ this.lastGraceCheck = Date.now();
3333
+ await this.refresh({ force: false }).catch((err) => this.log.debug(`moonbase: the deadline re-check failed: ${errorText(err)}`));
3334
+ }
3335
+ /**
3336
+ * A UI counts down to when the license and its add-ons end ("5 days left"), and
3337
+ * nothing reports a day going by: emit when one of those counts moves, so a
3338
+ * screen left open keeps up.
3339
+ */
3340
+ checkCountdowns() {
3341
+ var _a, _b;
3342
+ const ends = [];
3343
+ const license = this.license();
3344
+ if (license) {
3345
+ if (license.expiresAt)
3346
+ ends.push(license.expiresAt.getTime());
3347
+ for (const entry of (_a = license.subProducts) != null ? _a : []) {
3348
+ if (entry.expiresAt)
3349
+ ends.push(entry.expiresAt.getTime());
3350
+ }
3351
+ }
3352
+ for (const entry of this.addOns.addOns) {
3353
+ if (entry.expiresAt)
3354
+ ends.push(entry.expiresAt.getTime());
3355
+ if ((_b = entry.trial) == null ? void 0 : _b.expiresAt)
3356
+ ends.push(entry.trial.expiresAt.getTime());
3357
+ }
3358
+ const days = ends.map((end) => daysUntil(new Date(end)));
3359
+ const [previousEnds, previousDays] = this.countdown;
3360
+ const dayWentBy = ends.join() === previousEnds.join() && days.join() !== previousDays.join();
3361
+ this.countdown = [ends, days];
3362
+ if (dayWentBy)
3363
+ this.emit();
3364
+ }
3365
+ };
1388
3366
  // Annotate the CommonJS export names for ESM import in node:
1389
3367
  0 && (module.exports = {
3368
+ ActivationController,
3369
+ ActivationError,
1390
3370
  ActivationMethod,
1391
3371
  DEVICE_ID_SOURCE_TAGS,
1392
3372
  ErrorType,
@@ -1396,6 +3376,7 @@ var MoonbaseLicensing = class {
1396
3376
  IDENTIFYING_PARAM_NAMES,
1397
3377
  InMemoryLicenseStore,
1398
3378
  InsufficientDeviceIdentityError,
3379
+ InventoryClient,
1399
3380
  LegacyDeviceIdResolver,
1400
3381
  LicenseClient,
1401
3382
  LicenseValidator,
@@ -1406,14 +3387,18 @@ var MoonbaseLicensing = class {
1406
3387
  MoonbaseLicensing,
1407
3388
  ReleaseNotCoveredError,
1408
3389
  buildFingerprintMaterial,
3390
+ canDownload,
1409
3391
  canonicalizeParams,
1410
3392
  canonicalizeValue,
1411
3393
  coversVersion,
1412
3394
  defaultDeviceIdentityReader,
3395
+ filenameFromDownloadUrl,
1413
3396
  fingerprintDeviceId,
1414
3397
  fingerprintDigest,
1415
3398
  hasSubProduct,
1416
3399
  identitySource,
3400
+ isNewerVersion,
3401
+ licensingVersion,
1417
3402
  parseAppVersion,
1418
3403
  parseDeviceIdStamp,
1419
3404
  parseIoregPlatformUuid,