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