@codeo-engineering/licenserail-youtrack 0.1.1 → 0.1.6

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
@@ -42,9 +42,36 @@ exports.httpHandler = {
42
42
  };
43
43
  ```
44
44
 
45
- `check(ctx)` returns `{ valid, status, summary }`; `summary` has `isTrial`, `expiresAt`, `entitlements`, `metadata`,
46
- `maxHostUsers`, `hostUserPolicy` and `hostUsersOverLimit`. The License page and its endpoints are for administrators only
47
- and never return the key or the token.
45
+ `check(ctx)` returns `{ valid, status, summary }`; `summary` has `isTrial` (keyless trials only; a keyed license of kind
46
+ `trial` is an ordinary license that refreshes and is released on the server), `expiresAt` (what the offline check enforces:
47
+ the end of grace, or null when the expiration strategy keeps the license working), `licenseExpiresAt` (the license's own
48
+ expiry for display, null = perpetual; never enforced; `status(ctx)` and the License page show it), `entitlements`, `metadata`,
49
+ `maxHostUsers`, `hostUserPolicy`, `hostUsersOverLimit`, `expired` (expired but kept working), `inGrace` / `graceUntil`,
50
+ `maxAppVersion`, `maxUses` / `uses`, `borrowedUntil`, `overage` and `matching`. `status` is `AppVersionNotAllowed` when
51
+ `appVersion` in `licenserail-config.js` is newer than the license's `maxAppVersion`; `check(ctx)` then schedules a refresh at
52
+ once (at most every 5 minutes) instead of waiting a day, so an app updated before the license expires gets a new cap (a keyless
53
+ trial is not refreshed). Requests carry the instance's clock
54
+ (`clientTime`); the server refuses them when it is far off (`clock_offset`). The License page and its endpoints are for
55
+ administrators only and never return the key or the token.
56
+
57
+ ### Use-limited licenses
58
+
59
+ ```js
60
+ // in a handler that declares asyncFunctions: licenserail.asyncFunctions
61
+ if (!licenserail.consume(ctx, 1)) { /* not sent: no license, or a count below 1 (see status(ctx).lastError) */ }
62
+ ```
63
+
64
+ `consume(ctx, count = 1)` counts uses on the license server with async HTTP, like refresh. The answer arrives later:
65
+ `status(ctx)` then shows the server's `uses` / `maxUses`, or `lastError` (`use_limit_reached` when they are used up). It
66
+ returns false without a request for a count that isn't a whole number of at least 1 (`bad_request`) or when there is no
67
+ license (`no_license`), and for a keyless trial (`bad_request`: a trial is never sent to the server; `refresh` skips it too).
68
+ Like refresh, only a revoking code (for example `license_revoked`) or `lease_expired` removes the license; other refusals keep
69
+ it.
70
+
71
+ `returnBorrow(ctx)` releases the seat of a floating license early (async, like deactivate). On a node-locked license or a
72
+ keyless trial it sends nothing, stores `borrow_not_allowed` as `lastError` and returns false, so it never uses up a
73
+ deactivation. Without a license there is nothing to return: it sends nothing, clears `lastError` and returns true (like the
74
+ other SDKs).
48
75
 
49
76
  ## How it works
50
77
 
@@ -53,10 +80,19 @@ and never return the key or the token.
53
80
  ever changes (a move or a restore), activate again and release the old instance in LicenseRail.
54
81
  - **License key:** the administrator enters it in the app's settings (a secret setting). YouTrack sends it only as
55
82
  `Authorization: Bearer`; scripts never see it.
56
- - **Activation, trial, refresh, release:** async HTTP (`postAsync`); the answer is stored in app storage and the page
83
+ - **Activation, trial, refresh, release, consume:** async HTTP (`postAsync`); the answer is stored in app storage and the page
57
84
  shows the result. The license is refreshed daily; network errors keep it working until its offline period ends.
58
85
  - **Users:** the instance's user count is sent with activations and refreshes; the license decides (block, warn or report).
59
- - **Trials:** one per YouTrack instance, reinstalls included; no key ships with the app.
86
+ - **Trials:** one per YouTrack instance, reinstalls included; no key ships with the app. LicenseRail confirms the instance at its
87
+ address first, so it must be reachable from the internet (self-hosted behind a firewall: give a trial key instead). Needs 0.1.2
88
+ or later for trials started from your own code.
89
+
90
+ ## Changes
91
+
92
+ - 2026-12-01: additions only, existing apps keep working. New: `consume(ctx, count)` and its async function
93
+ `licenserailUsed`; the `AppVersionNotAllowed` status (when `appVersion` is newer than the license's `maxAppVersion`). Changed
94
+ behaviour: `summary.isTrial` is true only for keyless trials, so a keyed license of kind `trial` is refreshed and released on
95
+ the server; versions compare like the server (a part above 2147483647 counts as 0).
60
96
 
61
97
  ## Marketplace listing
62
98
 
@@ -11,6 +11,7 @@
11
11
  "licenserailToken": { "type": "string" },
12
12
  "licenserailLastSeen": { "type": "string" },
13
13
  "licenserailInstallation": { "type": "string" },
14
+ "licenserailBaseUrls": { "type": "string" },
14
15
  "licenserailState": { "type": "string" }
15
16
  },
16
17
  "widget": {
@@ -26,7 +26,11 @@ __export(index_exports, {
26
26
  REVOKING_CODES: () => REVOKING_CODES,
27
27
  UNAVAILABLE: () => UNAVAILABLE,
28
28
  activateRequest: () => activateRequest,
29
+ appVersionAllowed: () => appVersionAllowed,
29
30
  base64Decode: () => base64Decode,
31
+ borrowRequest: () => borrowRequest,
32
+ compareVersions: () => compareVersions,
33
+ consumeRequest: () => consumeRequest,
30
34
  createLicenseClient: () => createLicenseClient,
31
35
  deactivateRequest: () => deactivateRequest,
32
36
  decodeTokenUnverified: () => decodeTokenUnverified,
@@ -37,8 +41,10 @@ __export(index_exports, {
37
41
  hex: () => hex,
38
42
  installationFingerprint: () => installationFingerprint,
39
43
  isHostInstallation: () => isHostInstallation,
44
+ isVersion: () => isVersion,
40
45
  parsePublicKey: () => parsePublicKey,
41
46
  readResponse: () => readResponse,
47
+ readUseResponse: () => readUseResponse,
42
48
  refreshDueAt: () => refreshDueAt,
43
49
  refreshRequest: () => refreshRequest,
44
50
  sha256: () => sha256,
@@ -418,10 +424,21 @@ function installationFingerprint(vendor, product, platform, installationId) {
418
424
  var isHostInstallation = (f) => !!f.os && HOST_PLATFORMS.indexOf(f.os.toLowerCase()) >= 0;
419
425
  var available = (v) => !!v && v !== UNAVAILABLE;
420
426
  var same = (a, b) => available(a) && a === b;
421
- function fingerprintMatches(registered, presented) {
427
+ function fingerprintMatches(registered, presented, strategy) {
422
428
  if (isHostInstallation(registered) || isHostInstallation(presented))
423
429
  return (registered.os ?? "").toLowerCase() === (presented.os ?? "").toLowerCase() && same(registered.machineId, presented.machineId);
424
430
  if (registered.os && presented.os && registered.os.toLowerCase() !== presented.os.toLowerCase()) return false;
431
+ if (strategy === "strict" || strategy === "loose") {
432
+ const parts = [
433
+ [registered.machineId, presented.machineId],
434
+ [registered.diskId, presented.diskId],
435
+ [registered.hostName, presented.hostName],
436
+ [registered.boardId, presented.boardId]
437
+ ];
438
+ const mine = parts.filter((p) => available(p[0]));
439
+ if (strategy === "strict") return mine.length > 0 && mine.every((p) => same(p[0], p[1]));
440
+ return mine.some((p) => same(p[0], p[1]));
441
+ }
425
442
  let matches = 0;
426
443
  if (same(registered.machineId, presented.machineId)) matches++;
427
444
  if (same(registered.diskId, presented.diskId)) matches++;
@@ -432,11 +449,45 @@ function fingerprintMatches(registered, presented) {
432
449
  // ../embedded/src/evaluate.ts
433
450
  var CLOCK_TOLERANCE_MS = 10 * 60 * 1e3;
434
451
  var ISSUED_AT_TOLERANCE_MS = 24 * 60 * 60 * 1e3;
435
- function evaluate(payload, product, machine, now, lastSeen) {
452
+ var DOTNET_WHITESPACE = " -\r \x85\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000";
453
+ var EDGE_WHITESPACE = new RegExp(`^[${DOTNET_WHITESPACE}]+|[${DOTNET_WHITESPACE}]+$`, "g");
454
+ function trimVersion(v) {
455
+ return v.replace(EDGE_WHITESPACE, "");
456
+ }
457
+ var INT32_MAX = 2147483647;
458
+ function versionPart(p) {
459
+ const digits = p.replace(/^0+(?=[0-9])/, "");
460
+ if (digits.length > 10) return 0;
461
+ const n = Number(digits);
462
+ return n > INT32_MAX ? 0 : n;
463
+ }
464
+ function versionParts(v) {
465
+ const core = /^[0-9.]*/.exec(trimVersion(v).replace(/^[vV]+/, ""))[0];
466
+ return core.split(".").filter((p) => p !== "").map(versionPart);
467
+ }
468
+ function isVersion(v) {
469
+ if (typeof v !== "string") return false;
470
+ const t = trimVersion(v);
471
+ return t.length > 0 && t.length <= 50 && /^[0-9]/.test(t);
472
+ }
473
+ function compareVersions(a, b) {
474
+ const x = versionParts(a);
475
+ const y = versionParts(b);
476
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
477
+ const d = (i < x.length ? x[i] : 0) - (i < y.length ? y[i] : 0);
478
+ if (d !== 0) return d < 0 ? -1 : 1;
479
+ }
480
+ return 0;
481
+ }
482
+ function appVersionAllowed(maxAppVersion, appVersion) {
483
+ return !isVersion(maxAppVersion) || !isVersion(appVersion) || compareVersions(appVersion, maxAppVersion) <= 0;
484
+ }
485
+ function evaluate(payload, product, machine, now, lastSeen, appVersion) {
436
486
  if (!payload) return "InvalidSignature";
437
487
  if (payload.product.toLowerCase() !== product.toLowerCase()) return "WrongProduct";
438
- if (!fingerprintMatches(payload.fingerprint, machine)) return "WrongMachine";
488
+ if (!fingerprintMatches(payload.fingerprint, machine, payload.matching)) return "WrongMachine";
439
489
  if (payload.suspended) return "Suspended";
490
+ if (!appVersionAllowed(payload.maxAppVersion, appVersion)) return "AppVersionNotAllowed";
440
491
  if (!lastSeen) return "Unverified";
441
492
  const t = now.getTime();
442
493
  if (t + ISSUED_AT_TOLERANCE_MS < Date.parse(payload.issuedAt) || t + CLOCK_TOLERANCE_MS < lastSeen.getTime()) return "ClockTampered";
@@ -447,14 +498,24 @@ function evaluate(payload, product, machine, now, lastSeen) {
447
498
  function summarize(payload, hostUsers) {
448
499
  const max = typeof payload.maxHostUsers === "number" ? payload.maxHostUsers : null;
449
500
  return {
450
- isTrial: payload.trial === true || payload.kind === "trial",
501
+ isTrial: payload.trial === true,
451
502
  isTest: payload.test === true,
452
503
  expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : null,
504
+ licenseExpiresAt: payload.licenseExpiresAt ? new Date(payload.licenseExpiresAt) : null,
453
505
  entitlements: payload.entitlements ?? [],
454
506
  metadata: payload.metadata ?? {},
455
507
  maxHostUsers: max,
456
508
  hostUserPolicy: max === null ? null : payload.hostUserPolicy ?? "block",
457
- hostUsersOverLimit: payload.hostUsersExceeded === true || max !== null && typeof hostUsers === "number" && hostUsers > max
509
+ hostUsersOverLimit: payload.hostUsersExceeded === true || max !== null && typeof hostUsers === "number" && hostUsers > max,
510
+ matching: typeof payload.matching === "string" ? payload.matching : "default",
511
+ maxAppVersion: typeof payload.maxAppVersion === "string" ? payload.maxAppVersion : null,
512
+ expired: payload.expired === true,
513
+ inGrace: !!payload.graceUntil,
514
+ graceUntil: payload.graceUntil ? new Date(payload.graceUntil) : null,
515
+ borrowedUntil: payload.borrowedUntil ? new Date(payload.borrowedUntil) : null,
516
+ maxUses: typeof payload.maxUses === "number" ? payload.maxUses : null,
517
+ uses: typeof payload.uses === "number" ? payload.uses : null,
518
+ overage: payload.overage === true
458
519
  };
459
520
  }
460
521
  var hasFeature = (payload, code) => (payload.entitlements ?? []).indexOf(code) >= 0;
@@ -469,6 +530,12 @@ function headers(fingerprint) {
469
530
  if (fingerprint.os) h[INSTALLATION_HEADER] = `${fingerprint.os}:${fingerprint.machineId}`.slice(0, 128);
470
531
  return h;
471
532
  }
533
+ function clientTime(t) {
534
+ if (t === null) return void 0;
535
+ if (typeof t === "string") return isNaN(Date.parse(t)) ? void 0 : t;
536
+ const d = t instanceof Date ? t : t === void 0 ? /* @__PURE__ */ new Date() : null;
537
+ return d && !isNaN(d.getTime()) ? d.toISOString() : void 0;
538
+ }
472
539
  function clean(o) {
473
540
  const out = {};
474
541
  for (const k of Object.keys(o)) if (o[k] !== void 0 && o[k] !== null) out[k] = o[k];
@@ -488,7 +555,8 @@ function activateRequest(o) {
488
555
  licenseKey: inHeader ? void 0 : o.licenseKey,
489
556
  machineName: o.machineName,
490
557
  appVersion: o.appVersion,
491
- hostUsers: o.hostUsers
558
+ hostUsers: o.hostUsers,
559
+ clientTime: clientTime(o.clientTime)
492
560
  }))
493
561
  };
494
562
  }
@@ -498,7 +566,7 @@ function refreshRequest(o) {
498
566
  url: url(o.apiUrl, o.floating ? "/floating/heartbeat" : "/refresh"),
499
567
  headers: headers(o.fingerprint),
500
568
  // appVersion is a required field of the refresh request (null allowed).
501
- body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers }), appVersion: o.appVersion ?? null })
569
+ body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, anomalies: o.anomalies, hostUsers: o.hostUsers, clientTime: clientTime(o.clientTime) }), appVersion: o.appVersion ?? null })
502
570
  };
503
571
  }
504
572
  function deactivateRequest(o) {
@@ -509,6 +577,22 @@ function deactivateRequest(o) {
509
577
  body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint })
510
578
  };
511
579
  }
580
+ function borrowRequest(o) {
581
+ return {
582
+ method: "POST",
583
+ url: url(o.apiUrl, "/floating/borrow"),
584
+ headers: headers(o.fingerprint),
585
+ body: JSON.stringify({ ...clean({ token: o.token, fingerprint: o.fingerprint, hours: o.hours, clientTime: clientTime(o.clientTime) }), appVersion: o.appVersion ?? null })
586
+ };
587
+ }
588
+ function consumeRequest(o) {
589
+ return {
590
+ method: "POST",
591
+ url: url(o.apiUrl, "/use"),
592
+ headers: headers(o.fingerprint),
593
+ body: JSON.stringify({ token: o.token, fingerprint: o.fingerprint, count: o.count })
594
+ };
595
+ }
512
596
  function trialRequest(o) {
513
597
  return {
514
598
  method: "POST",
@@ -521,7 +605,8 @@ function trialRequest(o) {
521
605
  machineName: o.machineName,
522
606
  appVersion: o.appVersion,
523
607
  hostUsers: o.hostUsers,
524
- host: o.host
608
+ host: o.host,
609
+ clientTime: clientTime(o.clientTime)
525
610
  }))
526
611
  };
527
612
  }
@@ -534,17 +619,28 @@ var REVOKING_CODES = [
534
619
  "invalid_token",
535
620
  "license_revoked"
536
621
  ];
537
- function readResponse(status, bodyText) {
538
- let body = null;
622
+ function parseBody(bodyText) {
539
623
  try {
540
- body = bodyText ? JSON.parse(bodyText) : null;
624
+ return bodyText ? JSON.parse(bodyText) : null;
541
625
  } catch {
542
- body = null;
626
+ return null;
543
627
  }
628
+ }
629
+ function readResponse(status, bodyText) {
630
+ const body = parseBody(bodyText);
544
631
  if (status >= 200 && status < 300) {
545
632
  if (status === 204) return { ok: true, token: null };
546
633
  if (body && typeof body.token === "string") return { ok: true, token: body.token };
547
634
  }
635
+ return errorResponse(status, body);
636
+ }
637
+ function readUseResponse(status, bodyText) {
638
+ const body = parseBody(bodyText);
639
+ if (status >= 200 && status < 300 && body && (typeof body.uses === "number" || typeof body.maxUses === "number"))
640
+ return { ok: true, uses: typeof body.uses === "number" ? body.uses : null, maxUses: typeof body.maxUses === "number" ? body.maxUses : null };
641
+ return errorResponse(status, body);
642
+ }
643
+ function errorResponse(status, body) {
548
644
  const code = body && typeof body.code === "string" ? body.code : status === 0 ? "network_error" : `http_${status}`;
549
645
  const message = body && typeof body.message === "string" ? body.message : status === 0 ? "The license server could not be reached." : "Unexpected response from the license server.";
550
646
  return {
@@ -575,6 +671,7 @@ var fetchTransport = (timeoutMs) => async (r) => {
575
671
  if (timer !== null) host.clearTimeout?.(timer);
576
672
  }
577
673
  };
674
+ var removesLicense = (code, revoking) => revoking || code === "lease_expired";
578
675
  function createLicenseClient(o) {
579
676
  const send = o.transport ?? fetchTransport(o.timeoutMs ?? 1e4);
580
677
  const now = () => o.now ? o.now() : /* @__PURE__ */ new Date();
@@ -589,7 +686,7 @@ function createLicenseClient(o) {
589
686
  const { token, lastSeen } = await load();
590
687
  if (!token) return { status: "Missing", payload: null, summary: null };
591
688
  const payload = await verifyTokenAsync(token, o.publicKeyPem);
592
- const status = evaluate(payload, o.product, o.fingerprint, now(), lastSeen);
689
+ const status = evaluate(payload, o.product, o.fingerprint, now(), lastSeen, o.appVersion);
593
690
  if (status === "Valid") await o.storage.set(key("lastSeen"), String(now().getTime()));
594
691
  return { status, payload, summary: payload ? summarize(payload, o.hostUsers?.()) : null };
595
692
  }
@@ -607,11 +704,26 @@ function createLicenseClient(o) {
607
704
  return { ok: true, state: await state() };
608
705
  }
609
706
  if (!r.ok) {
610
- if (r.revokesLocalLicense) await o.storage.remove(key("token"));
707
+ if (removesLicense(r.code, r.revokesLocalLicense)) await o.storage.remove(key("token"));
611
708
  return { ok: false, code: r.code, message: r.message, state: await state() };
612
709
  }
613
710
  return { ok: true, state: await state() };
614
711
  }
712
+ async function deactivate() {
713
+ const { token } = await load();
714
+ const current = await state();
715
+ if (!token || !current.payload || current.payload.trial === true) {
716
+ await o.storage.remove(key("token"));
717
+ return { ok: true, state: await state() };
718
+ }
719
+ const res = await send(deactivateRequest({ ...target, token, floating: current.payload.floating === true }));
720
+ const r = readResponse(res.status, res.body);
721
+ if (r.ok || r.revokesLocalLicense) {
722
+ await o.storage.remove(key("token"));
723
+ return { ok: true, state: await state() };
724
+ }
725
+ return { ok: false, code: r.code, message: r.message, state: current };
726
+ }
615
727
  return {
616
728
  /** The current license, checked offline. */
617
729
  state,
@@ -623,7 +735,8 @@ function createLicenseClient(o) {
623
735
  machineName: o.machineName,
624
736
  appVersion: o.appVersion,
625
737
  hostUsers: o.hostUsers?.(),
626
- floating
738
+ floating,
739
+ clientTime: now()
627
740
  })));
628
741
  },
629
742
  /** Starts (or gets back) this device's or installation's keyless trial; apps inside a host pass the installation. */
@@ -634,39 +747,80 @@ function createLicenseClient(o) {
634
747
  machineName: o.machineName,
635
748
  appVersion: o.appVersion,
636
749
  hostUsers: o.hostUsers?.(),
637
- host
750
+ host,
751
+ clientTime: now()
638
752
  })));
639
753
  },
640
- /** Refreshes when the token asks for it (or always with force); keeps the token on network errors. */
754
+ /** Refreshes when the token asks for it (or always with force); keeps the token on network errors. A keyless trial is never
755
+ * sent to the server, even with force: it is returned as it is. When the offline check refuses the app version
756
+ * (AppVersionNotAllowed: the app was updated past the token's maxAppVersion), it refreshes at once, so an app updated before
757
+ * the license expires gets a new cap without waiting for refreshAfter. */
641
758
  async refresh(force = false) {
642
759
  const { token } = await load();
643
760
  const current = await state();
644
761
  if (!token || !current.payload) return { ok: false, code: "no_license", message: "No license to refresh.", state: current };
762
+ if (current.payload.trial === true) return { ok: true, state: current };
645
763
  const due = refreshDueAt(current.payload);
646
- if (!force && (!due || due.getTime() > now().getTime())) return { ok: true, state: current };
764
+ const versionRefused = current.status === "AppVersionNotAllowed";
765
+ if (!force && !versionRefused && (!due || due.getTime() > now().getTime())) return { ok: true, state: current };
647
766
  return accept(await send(refreshRequest({
648
767
  ...target,
649
768
  token,
650
769
  appVersion: o.appVersion,
651
770
  hostUsers: o.hostUsers?.(),
652
- floating: current.payload.floating === true
771
+ floating: current.payload.floating === true,
772
+ clientTime: now()
653
773
  })));
654
774
  },
655
- /** Releases the license on this device or installation and removes it locally. */
656
- async deactivate() {
775
+ /**
776
+ * Floating: keeps the checked-out seat for offline use for `hours` (up to the license's limit). Refused without a request
777
+ * with `no_license` when there is no license and `borrow_not_allowed` when it isn't a checked-out floating license; a keyless
778
+ * trial gets `bad_request` (it is never sent to the server). The license is removed only on a revoking code or lease_expired;
779
+ * other refusals keep it.
780
+ */
781
+ async borrow(hours) {
657
782
  const { token } = await load();
658
783
  const current = await state();
659
- if (!token || !current.payload || current.payload.trial) {
660
- await o.storage.remove(key("token"));
661
- return { ok: true, state: await state() };
662
- }
663
- const res = await send(deactivateRequest({ ...target, token, floating: current.payload.floating === true }));
664
- const r = readResponse(res.status, res.body);
665
- if (r.ok || r.revokesLocalLicense) {
666
- await o.storage.remove(key("token"));
667
- return { ok: true, state: await state() };
668
- }
669
- return { ok: false, code: r.code, message: r.message, state: current };
670
- }
784
+ if (typeof hours !== "number" || !Number.isInteger(hours) || hours < 1)
785
+ return { ok: false, code: "bad_request", message: "Borrow for a whole number of hours (at least 1).", state: current };
786
+ if (!token) return { ok: false, code: "no_license", message: "There is no license on this device.", state: current };
787
+ if (current.payload?.trial === true) return { ok: false, code: "bad_request", message: "A trial can't be borrowed.", state: current };
788
+ if (current.payload?.floating !== true)
789
+ return { ok: false, code: "borrow_not_allowed", message: "Only a checked-out floating license can be borrowed.", state: current };
790
+ return accept(await send(borrowRequest({ ...target, token, hours, appVersion: o.appVersion, clientTime: now() })));
791
+ },
792
+ /**
793
+ * Returns a borrowed floating seat early (releases the seat of a floating license). On a node-locked license or a keyless
794
+ * trial it returns `borrow_not_allowed` without a request, so it can never use up a deactivation. Without a license it
795
+ * succeeds.
796
+ */
797
+ async returnBorrow() {
798
+ const { token } = await load();
799
+ const current = await state();
800
+ if (!token) return { ok: true, state: current };
801
+ if (current.payload?.floating !== true || current.payload.trial === true)
802
+ return { ok: false, code: "borrow_not_allowed", message: "Only a floating license can be borrowed and returned.", state: current };
803
+ return deactivate();
804
+ },
805
+ /**
806
+ * Licenses with a use limit: consumes `count` uses on the server (use_limit_reached when they are used up). A count below 1
807
+ * is refused with `bad_request` and no license with `no_license`, both without a request; so is a keyless trial (`bad_request`:
808
+ * it is never sent to the server). The license is removed only on a revoking code or lease_expired; any other refusal keeps it.
809
+ */
810
+ async consume(count = 1) {
811
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 1)
812
+ return { ok: false, code: "bad_request", message: "Consume a whole number of uses (at least 1)." };
813
+ const { token } = await load();
814
+ if (!token) return { ok: false, code: "no_license", message: "There is no license on this device." };
815
+ if ((await verifyTokenAsync(token, o.publicKeyPem))?.trial === true)
816
+ return { ok: false, code: "bad_request", message: "A trial has no uses to consume." };
817
+ const res = await send(consumeRequest({ ...target, token, count }));
818
+ const r = readUseResponse(res.status, res.body);
819
+ if (r.ok) return r;
820
+ if (removesLicense(r.code, r.revokesLocalLicense)) await o.storage.remove(key("token"));
821
+ return { ok: false, code: r.code, message: r.message };
822
+ },
823
+ /** Releases the license on this device or installation and removes it locally. */
824
+ deactivate
671
825
  };
672
826
  }
@@ -26,8 +26,8 @@ function body(ctx) {
26
26
  }
27
27
 
28
28
  function remember(ctx) {
29
- const id = body(ctx).installationId;
30
- if (id) licenserail.setInstallation(ctx, id);
29
+ const b = body(ctx);
30
+ if (b.installationId) licenserail.setInstallation(ctx, b.installationId, b.baseUrls);
31
31
  }
32
32
 
33
33
  exports.httpHandler = {
@@ -18,13 +18,16 @@ const PROPERTY = {
18
18
  token: 'licenserailToken',
19
19
  lastSeen: 'licenserailLastSeen',
20
20
  installation: 'licenserailInstallation',
21
+ baseUrls: 'licenserailBaseUrls',
21
22
  state: 'licenserailState',
22
23
  };
23
24
  const PLATFORM = 'youtrack';
24
25
  const REFRESH = 'licenserailRefresh';
25
26
  const RESPONSE = 'licenserailResponse';
26
27
  const RELEASED = 'licenserailReleased';
28
+ const USED = 'licenserailUsed';
27
29
  const LAST_SEEN_WRITE_MS = 60 * 60 * 1000; // store "last run" at most hourly: few writes, enough for the clock check
30
+ const VERSION_RETRY_MS = 5 * 60 * 1000; // AppVersionNotAllowed: refresh at once, but not more often than every 5 minutes
28
31
 
29
32
  function props(ctx) {
30
33
  return ctx.globalStorage.extensionProperties;
@@ -74,7 +77,9 @@ function send(ctx, request, callback, withKey) {
74
77
  /**
75
78
  * The license, checked offline from app storage (no network). `valid` is true for a valid license or trial.
76
79
  * Schedules the daily refresh when the token asks for it (needs `asyncFunctions: licenserail.asyncFunctions` in the
77
- * calling handler).
80
+ * calling handler). When the app version is refused offline (AppVersionNotAllowed: the app was updated past the token's
81
+ * maxAppVersion) it schedules a refresh at once (at most every 5 minutes), so an app updated before the license expires gets a
82
+ * new cap without waiting a day. A keyless trial is never refreshed.
78
83
  */
79
84
  function check(ctx) {
80
85
  return inspect(ctx, true);
@@ -88,27 +93,49 @@ function inspect(ctx, scheduleRefresh) {
88
93
  const seenText = props(ctx)[PROPERTY.lastSeen];
89
94
  const lastSeen = seenText ? new Date(Number(seenText)) : null;
90
95
  const now = new Date();
91
- const status = core.evaluate(payload, config.product, fp, now, lastSeen);
96
+ // The app version is checked against the license's maxAppVersion; the token's matching and expiry flags are applied too.
97
+ const status = core.evaluate(payload, config.product, fp, now, lastSeen, config.appVersion);
92
98
  if (status === 'Valid' && (!lastSeen || now.getTime() - lastSeen.getTime() > LAST_SEEN_WRITE_MS)) props(ctx)[PROPERTY.lastSeen] = String(now.getTime());
93
99
  if (payload) {
94
- const due = core.refreshDueAt(payload);
95
- if (scheduleRefresh && due && due.getTime() <= now.getTime() && typeof ctx.invokeAsync === 'function') {
96
- try { ctx.invokeAsync(REFRESH, 0, 'licenserail-refresh'); } catch (e) { /* the calling handler doesn't declare the async functions */ }
100
+ const due = core.refreshDueAt(payload); // null for a keyless trial: never refreshed
101
+ const versionRefused = status === 'AppVersionNotAllowed' && due !== null && !versionRefreshedRecently(ctx, now);
102
+ if (scheduleRefresh && due && (due.getTime() <= now.getTime() || versionRefused) && typeof ctx.invokeAsync === 'function') {
103
+ try {
104
+ ctx.invokeAsync(REFRESH, 0, 'licenserail-refresh');
105
+ if (versionRefused) writeState(ctx, { versionRefreshAt: now.toISOString() });
106
+ } catch (e) { /* the calling handler doesn't declare the async functions */ }
97
107
  }
98
108
  }
99
109
  return { valid: status === 'Valid', status: status, summary: payload ? core.summarize(payload, hostUsers()) : null };
100
110
  }
101
111
 
112
+ /** Whether a refused version already scheduled a refresh in the last few minutes (so it isn't sent on every check). */
113
+ function versionRefreshedRecently(ctx, now) {
114
+ const at = Date.parse(readState(ctx).versionRefreshAt || '');
115
+ return !isNaN(at) && now.getTime() - at >= 0 && now.getTime() - at < VERSION_RETRY_MS;
116
+ }
117
+
102
118
  /** Feature flag from the license (entitlements set in LicenseRail). */
103
119
  function hasFeature(ctx, code) {
104
120
  const license = inspect(ctx, false);
105
121
  return license.valid && license.summary.entitlements.indexOf(code) >= 0;
106
122
  }
107
123
 
108
- /** Remembers this YouTrack instance's id (read by the admin page from /api/config). */
109
- function setInstallation(ctx, id) {
124
+ /** Addresses like https://acme.youtrack.cloud (scheme and host only), at most three. */
125
+ function cleanBaseUrls(baseUrls) {
126
+ return (Array.isArray(baseUrls) ? baseUrls : [])
127
+ .filter(function (u) { return typeof u === 'string' && /^https?:\/\/[^\s/]+$/.test(u); }).slice(0, 3);
128
+ }
129
+
130
+ /**
131
+ * Remembers this YouTrack instance's id (read by the admin page from /api/config) and the addresses the page was opened from,
132
+ * which a trial started later from the app's own code uses.
133
+ */
134
+ function setInstallation(ctx, id, baseUrls) {
110
135
  if (typeof id !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(id)) throw new Error('Invalid installation id.');
111
136
  if (props(ctx)[PROPERTY.installation] !== id) props(ctx)[PROPERTY.installation] = id;
137
+ const urls = cleanBaseUrls(baseUrls);
138
+ if (urls.length && props(ctx)[PROPERTY.baseUrls] !== urls.join(' ')) props(ctx)[PROPERTY.baseUrls] = urls.join(' ');
112
139
  }
113
140
 
114
141
  function common(ctx) {
@@ -123,14 +150,14 @@ function activate(ctx) {
123
150
  }
124
151
 
125
152
  /**
126
- * Starts the keyless trial. LicenseRail asks this YouTrack instance for its id at baseUrls (the addresses the admin page was
127
- * opened from) before the trial starts, so the instance must be reachable from the internet.
153
+ * Starts the keyless trial. LicenseRail asks this YouTrack instance for its id at its address before the trial starts, so the
154
+ * instance must be reachable from the internet. Without baseUrls the addresses remembered from the License page are used.
128
155
  */
129
156
  function startTrial(ctx, baseUrls) {
130
157
  const t = target(ctx);
131
158
  if (!t.fingerprint) throw new Error('Open the license page once so the app knows this YouTrack instance.');
132
- const urls = (Array.isArray(baseUrls) ? baseUrls : [])
133
- .filter(function (u) { return typeof u === 'string' && /^https?:\/\/[^\s/]+$/.test(u); }).slice(0, 3);
159
+ let urls = cleanBaseUrls(baseUrls);
160
+ if (!urls.length) urls = cleanBaseUrls(String(props(ctx)[PROPERTY.baseUrls] || '').split(' '));
134
161
  writeState(ctx, { pending: 'trial', lastAttemptAt: new Date().toISOString() });
135
162
  send(ctx, core.trialRequest(Object.assign(t, common(ctx), {
136
163
  keyId: config.keyId, host: { instanceId: installationId(ctx), baseUrls: urls },
@@ -142,7 +169,7 @@ function refresh(ctx) {
142
169
  const t = target(ctx);
143
170
  if (!token || !t.fingerprint) return false;
144
171
  const payload = core.verifyToken(token, config.publicKeyPem);
145
- if (!payload || payload.trial) return false;
172
+ if (!payload || payload.trial === true) return false; // only keyless trials (trial: true) are never refreshed
146
173
  writeState(ctx, { pending: 'refresh', lastAttemptAt: new Date().toISOString() });
147
174
  send(ctx, core.refreshRequest(Object.assign(t, { token: token, appVersion: config.appVersion, hostUsers: hostUsers(), floating: payload.floating === true })), RESPONSE, false);
148
175
  return true;
@@ -152,7 +179,7 @@ function deactivate(ctx) {
152
179
  const token = props(ctx)[PROPERTY.token];
153
180
  const t = target(ctx);
154
181
  const payload = token ? core.verifyToken(token, config.publicKeyPem) : null;
155
- if (!token || !t.fingerprint || !payload || payload.trial) {
182
+ if (!token || !t.fingerprint || !payload || payload.trial === true) {
156
183
  props(ctx)[PROPERTY.token] = null;
157
184
  writeState(ctx, { pending: null, lastError: null });
158
185
  return false;
@@ -162,6 +189,60 @@ function deactivate(ctx) {
162
189
  return true;
163
190
  }
164
191
 
192
+ /**
193
+ * Licenses with a use limit: consumes `count` uses (default 1) on the license server. Like refresh, the answer arrives later:
194
+ * `status(ctx)` then shows `uses` / `maxUses`, or `lastError` (`use_limit_reached` when they are used up). Returns false
195
+ * without a request when the count is not a whole number of at least 1 (`bad_request`) or there is no license
196
+ * (`no_license`), or when it is a keyless trial (`bad_request`: a trial is never sent to the server); the reason is stored as
197
+ * `lastError`. The license is removed only on a revoking code or lease_expired (the same rule as refresh).
198
+ */
199
+ function consume(ctx, count) {
200
+ const n = count === undefined ? 1 : count;
201
+ if (typeof n !== 'number' || n < 1 || Math.floor(n) !== n) {
202
+ writeState(ctx, { lastError: { code: 'bad_request', message: 'Consume a whole number of uses (at least 1).' } });
203
+ return false;
204
+ }
205
+ const token = props(ctx)[PROPERTY.token];
206
+ const t = target(ctx);
207
+ if (!token || !t.fingerprint) {
208
+ writeState(ctx, { lastError: { code: 'no_license', message: 'There is no license on this YouTrack instance.' } });
209
+ return false;
210
+ }
211
+ const payload = core.verifyToken(token, config.publicKeyPem);
212
+ if (payload && payload.trial === true) {
213
+ writeState(ctx, { lastError: { code: 'bad_request', message: 'A trial has no uses to consume.' } });
214
+ return false;
215
+ }
216
+ writeState(ctx, { pending: 'consume', lastAttemptAt: new Date().toISOString() });
217
+ send(ctx, core.consumeRequest(Object.assign(t, { token: token, count: n })), USED, false);
218
+ return true;
219
+ }
220
+
221
+ /**
222
+ * Returns a borrowed floating seat early (releases the seat; the answer arrives later, like deactivate). On a node-locked license
223
+ * or a keyless trial it sends nothing, stores `borrow_not_allowed` as `lastError` and returns false, so it can never use up a
224
+ * deactivation. Without a license there is nothing to return: it succeeds (returns true, clears `lastError`) and sends nothing,
225
+ * like the other SDKs.
226
+ */
227
+ function returnBorrow(ctx) {
228
+ const token = props(ctx)[PROPERTY.token];
229
+ if (!token) {
230
+ writeState(ctx, { lastError: null });
231
+ return true;
232
+ }
233
+ const payload = core.verifyToken(token, config.publicKeyPem);
234
+ if (!payload || payload.floating !== true || payload.trial === true) {
235
+ writeState(ctx, { lastError: { code: 'borrow_not_allowed', message: 'Only a floating license can be borrowed and returned.' } });
236
+ return false;
237
+ }
238
+ return deactivate(ctx);
239
+ }
240
+
241
+ /** The one rule (refresh, consume, borrow) for removing the local license: a revoking code or lease_expired. */
242
+ function removesLicense(r) {
243
+ return r.revokesLocalLicense || r.code === 'lease_expired';
244
+ }
245
+
165
246
  /** Admin page data: never the token or the key. */
166
247
  function status(ctx) {
167
248
  const license = inspect(ctx, false);
@@ -172,11 +253,22 @@ function status(ctx) {
172
253
  valid: license.valid,
173
254
  isTrial: s ? s.isTrial : false,
174
255
  isTest: s ? s.isTest : false,
256
+ // What the offline check enforces (end of grace; null when the strategy keeps the license working after expiry).
175
257
  expiresAt: s && s.expiresAt ? s.expiresAt.toISOString() : null,
258
+ // The license's own expiry, for showing to the admin (null = perpetual); never enforced.
259
+ licenseExpiresAt: s && s.licenseExpiresAt ? s.licenseExpiresAt.toISOString() : null,
176
260
  entitlements: s ? s.entitlements : [],
177
261
  hostUsers: hostUsers() === undefined ? null : hostUsers(),
178
262
  maxHostUsers: s ? s.maxHostUsers : null,
179
263
  hostUsersOverLimit: s ? s.hostUsersOverLimit : false,
264
+ expired: s ? s.expired : false,
265
+ inGrace: s ? s.inGrace : false,
266
+ graceUntil: s && s.graceUntil ? s.graceUntil.toISOString() : null,
267
+ maxAppVersion: s ? s.maxAppVersion : null,
268
+ appVersion: config.appVersion || null,
269
+ // After consume() the server's latest counter; otherwise the counter when the token was issued.
270
+ maxUses: typeof state.maxUses === 'number' ? state.maxUses : (s ? s.maxUses : null),
271
+ uses: typeof state.uses === 'number' ? state.uses : (s ? s.uses : null),
180
272
  installationKnown: !!installationId(ctx),
181
273
  keyConfigured: !!ctx.settings.licenseKey,
182
274
  pending: state.pending || null,
@@ -207,11 +299,12 @@ asyncFunctions[RESPONSE] = function (ctx) {
207
299
  }
208
300
  props(ctx)[PROPERTY.token] = r.token;
209
301
  props(ctx)[PROPERTY.lastSeen] = String(Date.now());
210
- writeState(ctx, { pending: null, lastError: null, lastSuccessAt: new Date().toISOString() });
302
+ // The new token carries the current use counter.
303
+ writeState(ctx, { pending: null, lastError: null, lastSuccessAt: new Date().toISOString(), uses: null, maxUses: null });
211
304
  return;
212
305
  }
213
306
  if (!r.ok) {
214
- if (r.revokesLocalLicense) props(ctx)[PROPERTY.token] = null;
307
+ if (removesLicense(r)) props(ctx)[PROPERTY.token] = null;
215
308
  writeState(ctx, { pending: null, lastError: { code: r.code, message: r.message } });
216
309
  }
217
310
  };
@@ -227,6 +320,17 @@ asyncFunctions[RELEASED] = function (ctx) {
227
320
  }
228
321
  };
229
322
 
323
+ asyncFunctions[USED] = function (ctx) {
324
+ const res = responseOf(ctx);
325
+ const r = core.readUseResponse(res.status, res.body);
326
+ if (r.ok) {
327
+ writeState(ctx, { pending: null, lastError: null, lastSuccessAt: new Date().toISOString(), uses: r.uses, maxUses: r.maxUses });
328
+ return;
329
+ }
330
+ if (removesLicense(r)) props(ctx)[PROPERTY.token] = null; // any other refusal keeps the license
331
+ writeState(ctx, { pending: null, lastError: { code: r.code, message: r.message } });
332
+ };
333
+
230
334
  module.exports = {
231
335
  check: check,
232
336
  hasFeature: hasFeature,
@@ -235,6 +339,8 @@ module.exports = {
235
339
  startTrial: startTrial,
236
340
  refresh: refresh,
237
341
  deactivate: deactivate,
342
+ consume: consume,
343
+ returnBorrow: returnBorrow,
238
344
  status: status,
239
345
  asyncFunctions: asyncFunctions,
240
346
  };
@@ -42,13 +42,22 @@ const LABELS = {
42
42
  Unverified: 'Waiting for the first check',
43
43
  InvalidSignature: 'Invalid license data',
44
44
  WrongProduct: 'The license is for another app',
45
+ AppVersionNotAllowed: 'This app version is newer than the license covers',
45
46
  }
46
47
 
47
48
  function render(s) {
48
49
  const lines = []
49
50
  const label = s.valid && s.isTrial ? 'Trial' : (LABELS[s.status] ?? s.status)
50
51
  lines.push(`<p class="state ${s.valid ? 'ok' : 'bad'}">${label}${s.isTest ? ' (test)' : ''}</p>`)
51
- if (s.expiresAt) lines.push(`<p>${s.valid ? 'Valid until' : 'Ended'} ${new Date(s.expiresAt).toLocaleDateString()}</p>`)
52
+ // The license's own date (licenseExpiresAt); expiresAt is what the offline check enforces (end of grace, or absent)
53
+ const shownExpiry = s.licenseExpiresAt ?? s.expiresAt
54
+ if (shownExpiry) lines.push(`<p>${s.valid && !s.expired && !s.inGrace ? 'Valid until' : 'Ended'} ${new Date(shownExpiry).toLocaleDateString()}</p>`)
55
+ if (s.valid && s.expired) lines.push('<p class="warn">The license has expired; this version keeps working. Renew it for updates.</p>')
56
+ if (s.valid && s.inGrace && s.graceUntil) lines.push(`<p class="warn">The license has expired; it keeps working until ${new Date(s.graceUntil).toLocaleDateString()}.</p>`)
57
+ if (s.status === 'AppVersionNotAllowed' && s.maxAppVersion) {
58
+ lines.push(`<p>The license covers versions up to ${escapeHtml(s.maxAppVersion)}; this is ${escapeHtml(s.appVersion ?? '?')}.</p>`)
59
+ }
60
+ if (s.maxUses !== null && s.maxUses !== undefined) lines.push(`<p>Uses: ${s.uses ?? 0} of ${s.maxUses}</p>`)
52
61
  if (s.maxHostUsers !== null) {
53
62
  lines.push(`<p${s.hostUsersOverLimit ? ' class="warn"' : ''}>Users: ${s.hostUsers ?? '?'} of ${s.maxHostUsers} allowed</p>`)
54
63
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeo-engineering/licenserail-youtrack",
3
- "version": "0.1.1",
3
+ "version": "0.1.6",
4
4
  "description": "LicenseRail for YouTrack apps: license keys, keyless trials and per-user limits for apps sold outside JetBrains Marketplace billing. Adds readable backend modules and a License admin page to your app.",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },
@@ -12,7 +12,7 @@
12
12
  "files": ["bin", "dist"],
13
13
  "scripts": {
14
14
  "build": "node scripts/build.mjs",
15
- "test": "npm run build && node --test test/"
15
+ "test": "npm run build && node --test"
16
16
  },
17
17
  "devDependencies": {
18
18
  "esbuild": "^0.25.0"