@moonbase.sh/licensing 3.5.1 → 3.6.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/README.md CHANGED
@@ -65,6 +65,20 @@ await licensing.store.storeLocalLicense(license)
65
65
  console.log('License stored locally')
66
66
  ```
67
67
 
68
+ ## Start a trial
69
+
70
+ A product that allows trials without an account can start one on the device directly, without the browser.
71
+ When the app knows the marketing it came from, such as the UTM tags of the link its installer was downloaded
72
+ from, pass them along: Moonbase puts the trial down to them, so the merchant can see which marketing brings
73
+ trials. Without them, a trial is put down to how its signed-in customer first came to the store.
74
+
75
+ ```ts
76
+ const trial = await licensing.client.requestTrial({
77
+ utm: { source: 'newsletter', medium: 'email', campaign: 'spring-launch' },
78
+ })
79
+ await licensing.store.storeLocalLicense(trial)
80
+ ```
81
+
68
82
  ## Validate on startup
69
83
 
70
84
  Only delete the stored license when Moonbase says the license is gone. Deleting it on any error makes
@@ -526,6 +540,11 @@ What runs in the background:
526
540
  before locking. An add-on that runs out changes the state, and so does a day going by on a countdown.
527
541
  - **Online checks** are at most every `checkInterval` (5 minutes), and instances sharing the license file take turns,
528
542
  so a later one picks up the license an earlier one just refreshed.
543
+ - **A revoked license is removed.** When an online check hears that the license was revoked (by hand, or with a
544
+ refund) or that this device's activation was, the app locks as `invalid` and the stored license is deleted, so a
545
+ later launch without a connection can't fall back to it within the grace period. Other instances sharing the file
546
+ lock as `deactivated`. Any other refusal leaves the file for the next launch to check: a lapsed subscription
547
+ (`expired`) unlocks again once it is renewed.
529
548
 
530
549
  Every result is gated by a generation counter: a cancel, a new activation or a deactivation supersedes whatever was
531
550
  in flight, so a slow response never overwrites a newer state or writes back a license the customer just removed.
package/dist/index.cjs CHANGED
@@ -75,7 +75,7 @@ __export(index_exports, {
75
75
  module.exports = __toCommonJS(index_exports);
76
76
 
77
77
  // package.json
78
- var version = "3.5.1";
78
+ var version = "3.6.0";
79
79
 
80
80
  // src/activation/controller.ts
81
81
  var import_promises4 = __toESM(require("fs/promises"), 1);
@@ -579,12 +579,14 @@ var LicenseClient = class {
579
579
  return null;
580
580
  return await this.handleLicenseResponse(response);
581
581
  }
582
- async requestTrial() {
582
+ async requestTrial(options) {
583
+ var _a;
583
584
  const content = {
584
585
  deviceName: await this.deviceIdResolver.resolveDeviceName(),
585
586
  deviceSignature: await this.deviceIdResolver.resolveDeviceId()
586
587
  };
587
- const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/trials/${this.configuration.productId}/request${this.buildQueryString()}`, {
588
+ const utm = Object.entries((_a = options == null ? void 0 : options.utm) != null ? _a : {}).filter(([_, value]) => !!value).map(([key, value]) => `utm_${key}=${encodeURIComponent(value)}`);
589
+ const response = await (0, import_cross_fetch2.default)(`${this.configuration.endpoint}/api/client/trials/${this.configuration.productId}/request${this.buildQueryString(utm)}`, {
588
590
  ...this.defaultFetchOptions,
589
591
  method: "POST",
590
592
  headers: {
@@ -683,7 +685,7 @@ var LicenseClient = class {
683
685
  }
684
686
  return await this.licenseValidator.validateLicense(await response.text());
685
687
  }
686
- buildQueryString() {
688
+ buildQueryString(extra = []) {
687
689
  const parts = ["format=JWT"];
688
690
  const { platform, appVersion, metadata } = this.configuration;
689
691
  if (platform)
@@ -699,6 +701,7 @@ var LicenseClient = class {
699
701
  }
700
702
  if (this.configuration.autoActivateSubProducts === false)
701
703
  parts.push("autoActivateSubProducts=false");
704
+ parts.push(...extra);
702
705
  return `?${parts.join("&")}`;
703
706
  }
704
707
  };
@@ -1863,6 +1866,9 @@ function isLicenseInvalid(error) {
1863
1866
  function isLicenseRejection(error) {
1864
1867
  return isLicenseInvalid(error) || error instanceof MoonbaseError && (error.type === "LicenseExpired" /* LicenseExpired */ || error.type === "NoEligibleLicense" /* NoEligibleLicense */);
1865
1868
  }
1869
+ function isRevocation(error) {
1870
+ return isType(error, "LicenseRevoked" /* LicenseRevoked */) || isType(error, "LicenseActivationRevoked" /* LicenseActivationRevoked */);
1871
+ }
1866
1872
  function isType(error, type) {
1867
1873
  return error instanceof MoonbaseError && error.type === type;
1868
1874
  }
@@ -2163,7 +2169,10 @@ var ActivationController = class {
2163
2169
  setLicense(license) {
2164
2170
  this.setStanding({ kind: "licensed", license });
2165
2171
  }
2166
- /** Drop the license and say why. The file stays, so the next launch checks it again. */
2172
+ /**
2173
+ * Drop the license and say why. The file stays, so the next launch checks it
2174
+ * again, unless Moonbase revoked it (see {@link forgetRevoked}).
2175
+ */
2167
2176
  lock(reason) {
2168
2177
  this.setStanding({ kind: "unlicensed", reason });
2169
2178
  }
@@ -2250,6 +2259,25 @@ var ActivationController = class {
2250
2259
  }
2251
2260
  this.fileStamp = kept ? null : await this.stampFile();
2252
2261
  }
2262
+ /**
2263
+ * Delete the stored license when Moonbase answered that it, or this device's
2264
+ * activation, was revoked. Left on disk, it would unlock every launch that can't
2265
+ * reach Moonbase until the grace period ran out, since a refusal stores nothing
2266
+ * newer to measure that from. Call under the store's lock: `shouldPersist` says
2267
+ * whether the file still holds the activation that was refused, so a license
2268
+ * another instance stored in its place is kept.
2269
+ */
2270
+ async forgetRevoked(error, shouldPersist) {
2271
+ if (!isRevocation(error) || !await shouldPersist())
2272
+ return;
2273
+ this.log.info(`moonbase: Moonbase revoked the stored license; removing it: ${errorText(error)}`);
2274
+ try {
2275
+ await this.store.deleteLocalLicense();
2276
+ } catch (err) {
2277
+ this.log.warn(`moonbase: couldn't delete the revoked license: ${errorText(err)}`);
2278
+ }
2279
+ this.fileStamp = await this.stampFile();
2280
+ }
2253
2281
  /** In-process turns for a re-check and an add-on call, so their answers land in the order they reached the store. */
2254
2282
  onlineTurn(action) {
2255
2283
  const run = this.onlineQueue.then(action, action);
@@ -2335,8 +2363,10 @@ var ActivationController = class {
2335
2363
  await this.store.storeLocalLicense(err.license).catch(noop);
2336
2364
  throw err;
2337
2365
  }
2338
- if (isLicenseRejection(err))
2366
+ if (isLicenseRejection(err)) {
2367
+ await this.forgetRevoked(err, shouldPersist);
2339
2368
  throw err;
2369
+ }
2340
2370
  if (since <= this.gracePeriod) {
2341
2371
  this.log.debug(`moonbase: couldn't reach Moonbase, the license is within its grace period: ${errorText(err)}`);
2342
2372
  this.ensureCoversAppVersion(freshest);
@@ -2437,10 +2467,15 @@ var ActivationController = class {
2437
2467
  try {
2438
2468
  if (peek.expiresAt && peek.expiresAt <= /* @__PURE__ */ new Date()) {
2439
2469
  const refreshed = await this.withStoreLock(async () => {
2440
- const answer = await this.licensing.client.validateLicense(peek);
2441
- if (await stillCurrent())
2442
- await this.store.storeLocalLicense(answer).catch(noop);
2443
- return answer;
2470
+ try {
2471
+ const answer = await this.licensing.client.validateLicense(peek);
2472
+ if (await stillCurrent())
2473
+ await this.store.storeLocalLicense(answer).catch(noop);
2474
+ return answer;
2475
+ } catch (err) {
2476
+ await this.forgetRevoked(err, stillCurrent);
2477
+ throw err;
2478
+ }
2444
2479
  });
2445
2480
  return { license: refreshed, reason: null };
2446
2481
  }
@@ -2611,6 +2646,7 @@ var ActivationController = class {
2611
2646
  } catch (err2) {
2612
2647
  if (err2 instanceof ReleaseNotCoveredError && err2.license && await stillCurrent())
2613
2648
  await this.store.storeLocalLicense(err2.license).catch(noop);
2649
+ await this.forgetRevoked(err2, stillCurrent);
2614
2650
  return { error: err2 };
2615
2651
  }
2616
2652
  });
package/dist/index.d.cts CHANGED
@@ -1448,6 +1448,23 @@ declare enum ActivationMethod {
1448
1448
  }
1449
1449
  type Metadata = Record<string, string>;
1450
1450
  type Platform = 'Windows' | 'Linux' | 'Mac';
1451
+ /** The UTM tags of a link, and the site that referred the visitor to it. */
1452
+ interface UrchinTrackingModule {
1453
+ source?: string;
1454
+ medium?: string;
1455
+ campaign?: string;
1456
+ term?: string;
1457
+ content?: string;
1458
+ referrer?: string;
1459
+ }
1460
+ interface RequestTrialOptions {
1461
+ /**
1462
+ * The marketing the trial came from, when the app knows it: the tags of the link its installer was
1463
+ * downloaded from, say. Moonbase puts the trial down to them, so the merchant can see which marketing
1464
+ * brings trials; without them, to how the signed-in customer first came to the store.
1465
+ */
1466
+ utm?: UrchinTrackingModule;
1467
+ }
1451
1468
  type License = z.infer<typeof licenseSchema>;
1452
1469
  type ReleaseAccess = z.infer<typeof releaseAccessSchema>;
1453
1470
  type SubProduct = z.infer<typeof subProductSchema>;
@@ -1493,9 +1510,10 @@ interface ILicenseClient {
1493
1510
  * the browser activation process. This currently requires that
1494
1511
  * the product allows anonymous trials, since there is no authentication.
1495
1512
  *
1513
+ * @param options The marketing the trial came from, when the app knows it
1496
1514
  * @returns The allocated trial license, throws if the trial license cannot be allocated (e.g. user already had a trial) or if the request failed
1497
1515
  */
1498
- requestTrial: () => Promise<License>;
1516
+ requestTrial: (options?: RequestTrialOptions) => Promise<License>;
1499
1517
  /**
1500
1518
  * Takes a seat of one of the product's sub-products (add-ons) for this
1501
1519
  * device, from the license the device holds for the product, and returns
@@ -1583,7 +1601,7 @@ declare class LicenseClient implements ILicenseClient {
1583
1601
  constructor(configuration: MoonbaseConfiguration, deviceIdResolver: IDeviceIdResolver, licenseValidator: ILicenseValidator);
1584
1602
  requestActivation(): Promise<ActivationRequestResponse>;
1585
1603
  getRequestedActivation(request: ActivationRequestResponse): Promise<License | null>;
1586
- requestTrial(): Promise<License>;
1604
+ requestTrial(options?: RequestTrialOptions): Promise<License>;
1587
1605
  activateSubProduct(license: License, subProductId: string): Promise<License>;
1588
1606
  requestSubProductTrial(license: License, subProductId: string): Promise<License>;
1589
1607
  listSubProducts(license: License): Promise<SubProductCatalog>;
@@ -2241,7 +2259,10 @@ declare class ActivationController {
2241
2259
  private resetAddOns;
2242
2260
  private setStanding;
2243
2261
  private setLicense;
2244
- /** Drop the license and say why. The file stays, so the next launch checks it again. */
2262
+ /**
2263
+ * Drop the license and say why. The file stays, so the next launch checks it
2264
+ * again, unless Moonbase revoked it (see {@link forgetRevoked}).
2265
+ */
2245
2266
  private lock;
2246
2267
  private showTrialExpired;
2247
2268
  /** Lock like an ended trial, but keep the license stored: it still covers the versions it did. */
@@ -2267,6 +2288,15 @@ declare class ActivationController {
2267
2288
  * license it picks out: another instance may have stored a new one since.
2268
2289
  */
2269
2290
  private deleteStored;
2291
+ /**
2292
+ * Delete the stored license when Moonbase answered that it, or this device's
2293
+ * activation, was revoked. Left on disk, it would unlock every launch that can't
2294
+ * reach Moonbase until the grace period ran out, since a refusal stores nothing
2295
+ * newer to measure that from. Call under the store's lock: `shouldPersist` says
2296
+ * whether the file still holds the activation that was refused, so a license
2297
+ * another instance stored in its place is kept.
2298
+ */
2299
+ private forgetRevoked;
2270
2300
  /** In-process turns for a re-check and an add-on call, so their answers land in the order they reached the store. */
2271
2301
  private onlineTurn;
2272
2302
  private ensureCoversAppVersion;
@@ -2584,4 +2614,4 @@ declare function isNewerVersion(current: string, latest: string): boolean;
2584
2614
  /** This SDK's version, as it names itself to Moonbase. */
2585
2615
  declare const licensingVersion: string;
2586
2616
 
2587
- export { ActivationController, type ActivationControllerOptions, ActivationError, type ActivationErrorKind, type ActivationFailure, type ActivationLogger, ActivationMethod, type ActivationRequestResponse, type ActivationScreen, type ActivationState, type ActivationStatus, type ActivationStrings, type ActivationUiOptions, type AddOnsPhase, type AddOnsState, type AppVersion, DEVICE_ID_SOURCE_TAGS, type DeviceIdDescription, type DeviceIdSource, type DeviceIdStamp, type DeviceIdentity, type DeviceIdentityReader, type DeviceInfo, type DeviceToken, type DownloadTarget, ErrorType, FINGERPRINT_PREFIX, FINGERPRINT_VERSION, FileLicenseStore, type FingerprintParam, IDENTIFYING_PARAM_NAMES, type IDescribableDeviceIdResolver, type IDeviceIdResolver, type ILicenseClient, type ILicenseStore, type ILicenseValidator, type IMigratingDeviceIdResolver, InMemoryLicenseStore, InsufficientDeviceIdentityError, InventoryClient, LegacyDeviceIdResolver, type License, LicenseClient, type LicenseValidationOptions, LicenseValidator, type LicenseView, type LockReason, MAX_VALUE_LENGTH, type Metadata, MigratingDeviceIdResolver, type MoonbaseConfiguration, MoonbaseDeviceIdResolver, type MoonbaseDeviceIdResolverOptions, MoonbaseError, MoonbaseLicensing, type NotCoveredView, type PendingActivation, type Platform, type PlatformTag, type Product, type ReleaseAccess, type ReleaseInfo, type ReleaseNotCoveredDetails, ReleaseNotCoveredError, type SubProduct, type SubProductCatalog, type SubProductCatalogEntry, type TrialFeature, type UpdateHint, type UpdateInfo, type User, buildFingerprintMaterial, canDownload, canonicalizeParams, canonicalizeValue, coversVersion, defaultDeviceIdentityReader, filenameFromDownloadUrl, fingerprintDeviceId, fingerprintDigest, hasSubProduct, identitySource, isNewerVersion, licensingVersion, parseAppVersion, parseDeviceIdStamp, parseIoregPlatformUuid, parseSmbiosParams, platformTag, selectMachineId, stampDeviceId };
2617
+ export { ActivationController, type ActivationControllerOptions, ActivationError, type ActivationErrorKind, type ActivationFailure, type ActivationLogger, ActivationMethod, type ActivationRequestResponse, type ActivationScreen, type ActivationState, type ActivationStatus, type ActivationStrings, type ActivationUiOptions, type AddOnsPhase, type AddOnsState, type AppVersion, DEVICE_ID_SOURCE_TAGS, type DeviceIdDescription, type DeviceIdSource, type DeviceIdStamp, type DeviceIdentity, type DeviceIdentityReader, type DeviceInfo, type DeviceToken, type DownloadTarget, ErrorType, FINGERPRINT_PREFIX, FINGERPRINT_VERSION, FileLicenseStore, type FingerprintParam, IDENTIFYING_PARAM_NAMES, type IDescribableDeviceIdResolver, type IDeviceIdResolver, type ILicenseClient, type ILicenseStore, type ILicenseValidator, type IMigratingDeviceIdResolver, InMemoryLicenseStore, InsufficientDeviceIdentityError, InventoryClient, LegacyDeviceIdResolver, type License, LicenseClient, type LicenseValidationOptions, LicenseValidator, type LicenseView, type LockReason, MAX_VALUE_LENGTH, type Metadata, MigratingDeviceIdResolver, type MoonbaseConfiguration, MoonbaseDeviceIdResolver, type MoonbaseDeviceIdResolverOptions, MoonbaseError, MoonbaseLicensing, type NotCoveredView, type PendingActivation, type Platform, type PlatformTag, type Product, type ReleaseAccess, type ReleaseInfo, type ReleaseNotCoveredDetails, ReleaseNotCoveredError, type RequestTrialOptions, type SubProduct, type SubProductCatalog, type SubProductCatalogEntry, type TrialFeature, type UpdateHint, type UpdateInfo, type UrchinTrackingModule, type User, buildFingerprintMaterial, canDownload, canonicalizeParams, canonicalizeValue, coversVersion, defaultDeviceIdentityReader, filenameFromDownloadUrl, fingerprintDeviceId, fingerprintDigest, hasSubProduct, identitySource, isNewerVersion, licensingVersion, parseAppVersion, parseDeviceIdStamp, parseIoregPlatformUuid, parseSmbiosParams, platformTag, selectMachineId, stampDeviceId };
package/dist/index.d.ts CHANGED
@@ -1448,6 +1448,23 @@ declare enum ActivationMethod {
1448
1448
  }
1449
1449
  type Metadata = Record<string, string>;
1450
1450
  type Platform = 'Windows' | 'Linux' | 'Mac';
1451
+ /** The UTM tags of a link, and the site that referred the visitor to it. */
1452
+ interface UrchinTrackingModule {
1453
+ source?: string;
1454
+ medium?: string;
1455
+ campaign?: string;
1456
+ term?: string;
1457
+ content?: string;
1458
+ referrer?: string;
1459
+ }
1460
+ interface RequestTrialOptions {
1461
+ /**
1462
+ * The marketing the trial came from, when the app knows it: the tags of the link its installer was
1463
+ * downloaded from, say. Moonbase puts the trial down to them, so the merchant can see which marketing
1464
+ * brings trials; without them, to how the signed-in customer first came to the store.
1465
+ */
1466
+ utm?: UrchinTrackingModule;
1467
+ }
1451
1468
  type License = z.infer<typeof licenseSchema>;
1452
1469
  type ReleaseAccess = z.infer<typeof releaseAccessSchema>;
1453
1470
  type SubProduct = z.infer<typeof subProductSchema>;
@@ -1493,9 +1510,10 @@ interface ILicenseClient {
1493
1510
  * the browser activation process. This currently requires that
1494
1511
  * the product allows anonymous trials, since there is no authentication.
1495
1512
  *
1513
+ * @param options The marketing the trial came from, when the app knows it
1496
1514
  * @returns The allocated trial license, throws if the trial license cannot be allocated (e.g. user already had a trial) or if the request failed
1497
1515
  */
1498
- requestTrial: () => Promise<License>;
1516
+ requestTrial: (options?: RequestTrialOptions) => Promise<License>;
1499
1517
  /**
1500
1518
  * Takes a seat of one of the product's sub-products (add-ons) for this
1501
1519
  * device, from the license the device holds for the product, and returns
@@ -1583,7 +1601,7 @@ declare class LicenseClient implements ILicenseClient {
1583
1601
  constructor(configuration: MoonbaseConfiguration, deviceIdResolver: IDeviceIdResolver, licenseValidator: ILicenseValidator);
1584
1602
  requestActivation(): Promise<ActivationRequestResponse>;
1585
1603
  getRequestedActivation(request: ActivationRequestResponse): Promise<License | null>;
1586
- requestTrial(): Promise<License>;
1604
+ requestTrial(options?: RequestTrialOptions): Promise<License>;
1587
1605
  activateSubProduct(license: License, subProductId: string): Promise<License>;
1588
1606
  requestSubProductTrial(license: License, subProductId: string): Promise<License>;
1589
1607
  listSubProducts(license: License): Promise<SubProductCatalog>;
@@ -2241,7 +2259,10 @@ declare class ActivationController {
2241
2259
  private resetAddOns;
2242
2260
  private setStanding;
2243
2261
  private setLicense;
2244
- /** Drop the license and say why. The file stays, so the next launch checks it again. */
2262
+ /**
2263
+ * Drop the license and say why. The file stays, so the next launch checks it
2264
+ * again, unless Moonbase revoked it (see {@link forgetRevoked}).
2265
+ */
2245
2266
  private lock;
2246
2267
  private showTrialExpired;
2247
2268
  /** Lock like an ended trial, but keep the license stored: it still covers the versions it did. */
@@ -2267,6 +2288,15 @@ declare class ActivationController {
2267
2288
  * license it picks out: another instance may have stored a new one since.
2268
2289
  */
2269
2290
  private deleteStored;
2291
+ /**
2292
+ * Delete the stored license when Moonbase answered that it, or this device's
2293
+ * activation, was revoked. Left on disk, it would unlock every launch that can't
2294
+ * reach Moonbase until the grace period ran out, since a refusal stores nothing
2295
+ * newer to measure that from. Call under the store's lock: `shouldPersist` says
2296
+ * whether the file still holds the activation that was refused, so a license
2297
+ * another instance stored in its place is kept.
2298
+ */
2299
+ private forgetRevoked;
2270
2300
  /** In-process turns for a re-check and an add-on call, so their answers land in the order they reached the store. */
2271
2301
  private onlineTurn;
2272
2302
  private ensureCoversAppVersion;
@@ -2584,4 +2614,4 @@ declare function isNewerVersion(current: string, latest: string): boolean;
2584
2614
  /** This SDK's version, as it names itself to Moonbase. */
2585
2615
  declare const licensingVersion: string;
2586
2616
 
2587
- export { ActivationController, type ActivationControllerOptions, ActivationError, type ActivationErrorKind, type ActivationFailure, type ActivationLogger, ActivationMethod, type ActivationRequestResponse, type ActivationScreen, type ActivationState, type ActivationStatus, type ActivationStrings, type ActivationUiOptions, type AddOnsPhase, type AddOnsState, type AppVersion, DEVICE_ID_SOURCE_TAGS, type DeviceIdDescription, type DeviceIdSource, type DeviceIdStamp, type DeviceIdentity, type DeviceIdentityReader, type DeviceInfo, type DeviceToken, type DownloadTarget, ErrorType, FINGERPRINT_PREFIX, FINGERPRINT_VERSION, FileLicenseStore, type FingerprintParam, IDENTIFYING_PARAM_NAMES, type IDescribableDeviceIdResolver, type IDeviceIdResolver, type ILicenseClient, type ILicenseStore, type ILicenseValidator, type IMigratingDeviceIdResolver, InMemoryLicenseStore, InsufficientDeviceIdentityError, InventoryClient, LegacyDeviceIdResolver, type License, LicenseClient, type LicenseValidationOptions, LicenseValidator, type LicenseView, type LockReason, MAX_VALUE_LENGTH, type Metadata, MigratingDeviceIdResolver, type MoonbaseConfiguration, MoonbaseDeviceIdResolver, type MoonbaseDeviceIdResolverOptions, MoonbaseError, MoonbaseLicensing, type NotCoveredView, type PendingActivation, type Platform, type PlatformTag, type Product, type ReleaseAccess, type ReleaseInfo, type ReleaseNotCoveredDetails, ReleaseNotCoveredError, type SubProduct, type SubProductCatalog, type SubProductCatalogEntry, type TrialFeature, type UpdateHint, type UpdateInfo, type User, buildFingerprintMaterial, canDownload, canonicalizeParams, canonicalizeValue, coversVersion, defaultDeviceIdentityReader, filenameFromDownloadUrl, fingerprintDeviceId, fingerprintDigest, hasSubProduct, identitySource, isNewerVersion, licensingVersion, parseAppVersion, parseDeviceIdStamp, parseIoregPlatformUuid, parseSmbiosParams, platformTag, selectMachineId, stampDeviceId };
2617
+ export { ActivationController, type ActivationControllerOptions, ActivationError, type ActivationErrorKind, type ActivationFailure, type ActivationLogger, ActivationMethod, type ActivationRequestResponse, type ActivationScreen, type ActivationState, type ActivationStatus, type ActivationStrings, type ActivationUiOptions, type AddOnsPhase, type AddOnsState, type AppVersion, DEVICE_ID_SOURCE_TAGS, type DeviceIdDescription, type DeviceIdSource, type DeviceIdStamp, type DeviceIdentity, type DeviceIdentityReader, type DeviceInfo, type DeviceToken, type DownloadTarget, ErrorType, FINGERPRINT_PREFIX, FINGERPRINT_VERSION, FileLicenseStore, type FingerprintParam, IDENTIFYING_PARAM_NAMES, type IDescribableDeviceIdResolver, type IDeviceIdResolver, type ILicenseClient, type ILicenseStore, type ILicenseValidator, type IMigratingDeviceIdResolver, InMemoryLicenseStore, InsufficientDeviceIdentityError, InventoryClient, LegacyDeviceIdResolver, type License, LicenseClient, type LicenseValidationOptions, LicenseValidator, type LicenseView, type LockReason, MAX_VALUE_LENGTH, type Metadata, MigratingDeviceIdResolver, type MoonbaseConfiguration, MoonbaseDeviceIdResolver, type MoonbaseDeviceIdResolverOptions, MoonbaseError, MoonbaseLicensing, type NotCoveredView, type PendingActivation, type Platform, type PlatformTag, type Product, type ReleaseAccess, type ReleaseInfo, type ReleaseNotCoveredDetails, ReleaseNotCoveredError, type RequestTrialOptions, type SubProduct, type SubProductCatalog, type SubProductCatalogEntry, type TrialFeature, type UpdateHint, type UpdateInfo, type UrchinTrackingModule, type User, buildFingerprintMaterial, canDownload, canonicalizeParams, canonicalizeValue, coversVersion, defaultDeviceIdentityReader, filenameFromDownloadUrl, fingerprintDeviceId, fingerprintDigest, hasSubProduct, identitySource, isNewerVersion, licensingVersion, parseAppVersion, parseDeviceIdStamp, parseIoregPlatformUuid, parseSmbiosParams, platformTag, selectMachineId, stampDeviceId };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "3.5.1";
2
+ var version = "3.6.0";
3
3
 
4
4
  // src/activation/controller.ts
5
5
  import fs4 from "fs/promises";
@@ -503,12 +503,14 @@ var LicenseClient = class {
503
503
  return null;
504
504
  return await this.handleLicenseResponse(response);
505
505
  }
506
- async requestTrial() {
506
+ async requestTrial(options) {
507
+ var _a;
507
508
  const content = {
508
509
  deviceName: await this.deviceIdResolver.resolveDeviceName(),
509
510
  deviceSignature: await this.deviceIdResolver.resolveDeviceId()
510
511
  };
511
- const response = await fetch3(`${this.configuration.endpoint}/api/client/trials/${this.configuration.productId}/request${this.buildQueryString()}`, {
512
+ const utm = Object.entries((_a = options == null ? void 0 : options.utm) != null ? _a : {}).filter(([_, value]) => !!value).map(([key, value]) => `utm_${key}=${encodeURIComponent(value)}`);
513
+ const response = await fetch3(`${this.configuration.endpoint}/api/client/trials/${this.configuration.productId}/request${this.buildQueryString(utm)}`, {
512
514
  ...this.defaultFetchOptions,
513
515
  method: "POST",
514
516
  headers: {
@@ -607,7 +609,7 @@ var LicenseClient = class {
607
609
  }
608
610
  return await this.licenseValidator.validateLicense(await response.text());
609
611
  }
610
- buildQueryString() {
612
+ buildQueryString(extra = []) {
611
613
  const parts = ["format=JWT"];
612
614
  const { platform, appVersion, metadata } = this.configuration;
613
615
  if (platform)
@@ -623,6 +625,7 @@ var LicenseClient = class {
623
625
  }
624
626
  if (this.configuration.autoActivateSubProducts === false)
625
627
  parts.push("autoActivateSubProducts=false");
628
+ parts.push(...extra);
626
629
  return `?${parts.join("&")}`;
627
630
  }
628
631
  };
@@ -1787,6 +1790,9 @@ function isLicenseInvalid(error) {
1787
1790
  function isLicenseRejection(error) {
1788
1791
  return isLicenseInvalid(error) || error instanceof MoonbaseError && (error.type === "LicenseExpired" /* LicenseExpired */ || error.type === "NoEligibleLicense" /* NoEligibleLicense */);
1789
1792
  }
1793
+ function isRevocation(error) {
1794
+ return isType(error, "LicenseRevoked" /* LicenseRevoked */) || isType(error, "LicenseActivationRevoked" /* LicenseActivationRevoked */);
1795
+ }
1790
1796
  function isType(error, type) {
1791
1797
  return error instanceof MoonbaseError && error.type === type;
1792
1798
  }
@@ -2087,7 +2093,10 @@ var ActivationController = class {
2087
2093
  setLicense(license) {
2088
2094
  this.setStanding({ kind: "licensed", license });
2089
2095
  }
2090
- /** Drop the license and say why. The file stays, so the next launch checks it again. */
2096
+ /**
2097
+ * Drop the license and say why. The file stays, so the next launch checks it
2098
+ * again, unless Moonbase revoked it (see {@link forgetRevoked}).
2099
+ */
2091
2100
  lock(reason) {
2092
2101
  this.setStanding({ kind: "unlicensed", reason });
2093
2102
  }
@@ -2174,6 +2183,25 @@ var ActivationController = class {
2174
2183
  }
2175
2184
  this.fileStamp = kept ? null : await this.stampFile();
2176
2185
  }
2186
+ /**
2187
+ * Delete the stored license when Moonbase answered that it, or this device's
2188
+ * activation, was revoked. Left on disk, it would unlock every launch that can't
2189
+ * reach Moonbase until the grace period ran out, since a refusal stores nothing
2190
+ * newer to measure that from. Call under the store's lock: `shouldPersist` says
2191
+ * whether the file still holds the activation that was refused, so a license
2192
+ * another instance stored in its place is kept.
2193
+ */
2194
+ async forgetRevoked(error, shouldPersist) {
2195
+ if (!isRevocation(error) || !await shouldPersist())
2196
+ return;
2197
+ this.log.info(`moonbase: Moonbase revoked the stored license; removing it: ${errorText(error)}`);
2198
+ try {
2199
+ await this.store.deleteLocalLicense();
2200
+ } catch (err) {
2201
+ this.log.warn(`moonbase: couldn't delete the revoked license: ${errorText(err)}`);
2202
+ }
2203
+ this.fileStamp = await this.stampFile();
2204
+ }
2177
2205
  /** In-process turns for a re-check and an add-on call, so their answers land in the order they reached the store. */
2178
2206
  onlineTurn(action) {
2179
2207
  const run = this.onlineQueue.then(action, action);
@@ -2259,8 +2287,10 @@ var ActivationController = class {
2259
2287
  await this.store.storeLocalLicense(err.license).catch(noop);
2260
2288
  throw err;
2261
2289
  }
2262
- if (isLicenseRejection(err))
2290
+ if (isLicenseRejection(err)) {
2291
+ await this.forgetRevoked(err, shouldPersist);
2263
2292
  throw err;
2293
+ }
2264
2294
  if (since <= this.gracePeriod) {
2265
2295
  this.log.debug(`moonbase: couldn't reach Moonbase, the license is within its grace period: ${errorText(err)}`);
2266
2296
  this.ensureCoversAppVersion(freshest);
@@ -2361,10 +2391,15 @@ var ActivationController = class {
2361
2391
  try {
2362
2392
  if (peek.expiresAt && peek.expiresAt <= /* @__PURE__ */ new Date()) {
2363
2393
  const refreshed = await this.withStoreLock(async () => {
2364
- const answer = await this.licensing.client.validateLicense(peek);
2365
- if (await stillCurrent())
2366
- await this.store.storeLocalLicense(answer).catch(noop);
2367
- return answer;
2394
+ try {
2395
+ const answer = await this.licensing.client.validateLicense(peek);
2396
+ if (await stillCurrent())
2397
+ await this.store.storeLocalLicense(answer).catch(noop);
2398
+ return answer;
2399
+ } catch (err) {
2400
+ await this.forgetRevoked(err, stillCurrent);
2401
+ throw err;
2402
+ }
2368
2403
  });
2369
2404
  return { license: refreshed, reason: null };
2370
2405
  }
@@ -2535,6 +2570,7 @@ var ActivationController = class {
2535
2570
  } catch (err2) {
2536
2571
  if (err2 instanceof ReleaseNotCoveredError && err2.license && await stillCurrent())
2537
2572
  await this.store.storeLocalLicense(err2.license).catch(noop);
2573
+ await this.forgetRevoked(err2, stillCurrent);
2538
2574
  return { error: err2 };
2539
2575
  }
2540
2576
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@moonbase.sh/licensing",
3
3
  "type": "module",
4
- "version": "3.5.1",
4
+ "version": "3.6.0",
5
5
  "description": "Package to add sotftware licensing using Moonbase.sh to your node.js apps",
6
6
  "author": "Tobias Lønnerød Madsen <m@dsen.tv>",
7
7
  "license": "MIT",