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