@moonbase.sh/licensing 3.2.3 → 3.4.0

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